adding a function to swap directories

This commit is contained in:
Martin A. Brown 2016-03-07 15:04:16 -08:00
parent 5f24879875
commit 8c6ceba912
1 changed files with 26 additions and 1 deletions

View File

@ -11,10 +11,15 @@ import operator
import subprocess
import functools
from functools import wraps
from tempfile import mkstemp
from tempfile import mkstemp, mkdtemp
import logging
logger = logging.getLogger(__name__)
opa = os.path.abspath
opb = os.path.basename
opd = os.path.dirname
opj = os.path.join
logdir = 'tldp-document-build-logs'
@ -75,6 +80,26 @@ def stem_and_ext(name):
return os.path.splitext(os.path.basename(os.path.normpath(name)))
def swapdirs(a, b):
'''use os.rename() to make "a" become "b"'''
if not os.path.isdir(a):
raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), a)
tname = None
if os.path.isdir(b):
tdir = mkdtemp(prefix='swapdirs-', dir=opd(opa(a)))
logger.debug("Created tempdir %s.", tdir)
tname = opj(tdir, opb(b))
logger.debug("About to rename %s to %s.", b, tname)
os.rename(b, tname)
logger.debug("About to rename %s to %s.", a, b)
os.rename(a, b)
if tname:
logger.debug("About to rename %s to %s.", tname, a)
os.rename(tname, a)
logger.debug("About to remove %s.", tdir)
os.rmdir(tdir)
def conditionallogging(result, prefix, fname):
if logger.isEnabledFor(logging.DEBUG):
logfilecontents(logger.info, prefix, fname) # -- always