1.1 --- a/moinformat/utils/directory.py Sun Aug 05 19:06:31 2018 +0200
1.2 +++ b/moinformat/utils/directory.py Sun Aug 05 19:07:27 2018 +0200
1.3 @@ -19,8 +19,8 @@
1.4 this program. If not, see <http://www.gnu.org/licenses/>.
1.5 """
1.6
1.7 -from os import makedirs, walk
1.8 -from os.path import abspath, commonprefix, exists, join
1.9 +from os import makedirs, rename, walk
1.10 +from os.path import abspath, commonprefix, exists, isdir, isfile, join
1.11 import fnmatch
1.12
1.13 # Get the directory with trailing path separator when assessing path prefixes
1.14 @@ -57,14 +57,12 @@
1.15
1.16 self.filename = abspath(filename)
1.17
1.18 - def exists(self, filename):
1.19 + def ensure(self):
1.20
1.21 - """
1.22 - Return whether 'filename' exists within the directory. This filename
1.23 - is relative to the directory.
1.24 - """
1.25 + "Ensure that this directory exists."
1.26
1.27 - return exists(self.get_filename(filename))
1.28 + if not exists(self.filename):
1.29 + makedirs(self.filename)
1.30
1.31 def get_filename(self, filename):
1.32
1.33 @@ -82,6 +80,32 @@
1.34 else:
1.35 raise ValueError, filename
1.36
1.37 + # File operations acting on relative filenames.
1.38 +
1.39 + def _apply(self, fn, filename):
1.40 +
1.41 + "Apply 'fn' to the relative 'filename'."
1.42 +
1.43 + return fn(self.get_filename(filename))
1.44 +
1.45 + def exists(self, filename):
1.46 +
1.47 + "Return whether the relative 'filename' exists within the directory."
1.48 +
1.49 + return self._apply(exists, filename)
1.50 +
1.51 + def isdir(self, filename):
1.52 +
1.53 + "Return whether the relative 'filename' is a directory."
1.54 +
1.55 + return self._apply(isdir, filename)
1.56 +
1.57 + def isfile(self, filename):
1.58 +
1.59 + "Return whether the relative 'filename' is a file."
1.60 +
1.61 + return self._apply(isfile, filename)
1.62 +
1.63 def makedirs(self, filename):
1.64
1.65 """
1.66 @@ -95,6 +119,15 @@
1.67 if not exists(pathname):
1.68 makedirs(pathname)
1.69
1.70 + def rename(self, old, new):
1.71 +
1.72 + """
1.73 + Rename the file with the 'old' relative filename to the 'new' relative
1.74 + filename.
1.75 + """
1.76 +
1.77 + rename(self.get_filename(old), self.get_filename(new))
1.78 +
1.79 def select_files(self, pattern):
1.80
1.81 """
1.82 @@ -124,10 +157,14 @@
1.83
1.84 return selected
1.85
1.86 + # File operations involving complete filenames.
1.87 +
1.88 def within(self, filename):
1.89
1.90 """
1.91 - Return the given 'filename' translated to be relative to this directory.
1.92 + Return the given complete 'filename' translated to be relative to this
1.93 + directory, or return None if the filename describes a location outside
1.94 + the directory.
1.95 """
1.96
1.97 return within(filename, self.filename)