# HG changeset patch # User Paul Boddie # Date 1533488847 -7200 # Node ID 390bf818f5f1c7c8e426fbd77e0f6bf7bb320b74 # Parent 5f8102d2d05bb87cd69ec86adc199a4c39bf8cdb Introduced directory-relative methods for common file operations. diff -r 5f8102d2d05b -r 390bf818f5f1 moinformat/utils/directory.py --- a/moinformat/utils/directory.py Sun Aug 05 19:06:31 2018 +0200 +++ b/moinformat/utils/directory.py Sun Aug 05 19:07:27 2018 +0200 @@ -19,8 +19,8 @@ this program. If not, see . """ -from os import makedirs, walk -from os.path import abspath, commonprefix, exists, join +from os import makedirs, rename, walk +from os.path import abspath, commonprefix, exists, isdir, isfile, join import fnmatch # Get the directory with trailing path separator when assessing path prefixes @@ -57,14 +57,12 @@ self.filename = abspath(filename) - def exists(self, filename): + def ensure(self): - """ - Return whether 'filename' exists within the directory. This filename - is relative to the directory. - """ + "Ensure that this directory exists." - return exists(self.get_filename(filename)) + if not exists(self.filename): + makedirs(self.filename) def get_filename(self, filename): @@ -82,6 +80,32 @@ else: raise ValueError, filename + # File operations acting on relative filenames. + + def _apply(self, fn, filename): + + "Apply 'fn' to the relative 'filename'." + + return fn(self.get_filename(filename)) + + def exists(self, filename): + + "Return whether the relative 'filename' exists within the directory." + + return self._apply(exists, filename) + + def isdir(self, filename): + + "Return whether the relative 'filename' is a directory." + + return self._apply(isdir, filename) + + def isfile(self, filename): + + "Return whether the relative 'filename' is a file." + + return self._apply(isfile, filename) + def makedirs(self, filename): """ @@ -95,6 +119,15 @@ if not exists(pathname): makedirs(pathname) + def rename(self, old, new): + + """ + Rename the file with the 'old' relative filename to the 'new' relative + filename. + """ + + rename(self.get_filename(old), self.get_filename(new)) + def select_files(self, pattern): """ @@ -124,10 +157,14 @@ return selected + # File operations involving complete filenames. + def within(self, filename): """ - Return the given 'filename' translated to be relative to this directory. + Return the given complete 'filename' translated to be relative to this + directory, or return None if the filename describes a location outside + the directory. """ return within(filename, self.filename)