1.1 --- a/moinformat/output/directory.py Sun Aug 05 18:07:02 2018 +0200
1.2 +++ b/moinformat/output/directory.py Sun Aug 05 18:13:36 2018 +0200
1.3 @@ -21,6 +21,8 @@
1.4
1.5 from moinformat.output.common import Output
1.6 from moinformat.utils.directory import Directory
1.7 +from os import makedirs, rename
1.8 +from os.path import exists, isdir, isfile, join, split
1.9
1.10 class DirectoryOutput(Output, Directory):
1.11
1.12 @@ -38,6 +40,85 @@
1.13 Output.__init__(self, parameters)
1.14 Directory.__init__(self, parameters["filename"])
1.15
1.16 + if not exists(self.filename):
1.17 + makedirs(self.filename)
1.18 +
1.19 + self.index_name = parameters and parameters.get("index_name") or "index"
1.20 +
1.21 + # Name translation methods.
1.22 +
1.23 + def to_filename(self, pagename):
1.24 +
1.25 + "Return the filename corresponding to 'pagename'."
1.26 +
1.27 + return pagename
1.28 +
1.29 + def to_pagename(self, filename):
1.30 +
1.31 + "Return the pagename corresponding to 'filename'."
1.32 +
1.33 + # Take the leafname as the pagename from an arbitrary filename.
1.34 +
1.35 + return split(filename)[-1]
1.36 +
1.37 + # Serialisation methods.
1.38 +
1.39 + def can_write(self):
1.40 +
1.41 + "Return whether this context supports page writing."
1.42 +
1.43 + return True
1.44 +
1.45 + def writefile(self, text, filename, encoding=None):
1.46 +
1.47 + """
1.48 + Write 'text' to the file having the given 'filename'. If the
1.49 + optional 'encoding' is specified, override the general encoding.
1.50 + """
1.51 +
1.52 + return self.writepath(text, self.get_filename(filename), encoding)
1.53 +
1.54 + def writepage(self, text, pagename, encoding=None):
1.55 +
1.56 + """
1.57 + Write 'text' to the file having the given 'pagename' and optional
1.58 + 'encoding'. If 'parent' is specified and a true value, it indicates that
1.59 + the page is a parent of other pages.
1.60 + """
1.61 +
1.62 + filename = self.to_filename(pagename)
1.63 + parent = split(filename)[0]
1.64 +
1.65 + # The page may have a parent.
1.66 +
1.67 + if parent and parent != filename:
1.68 + dirpath = self.get_filename(parent)
1.69 +
1.70 + # Relocate any file for the parent to an index file within a page
1.71 + # directory.
1.72 +
1.73 + if isfile(dirpath):
1.74 + parent_tmp = "%s.tmp" % dirpath
1.75 + rename(dirpath, parent_tmp)
1.76 + makedirs(dirpath)
1.77 + rename(parent_tmp, join(dirpath, self.index_name))
1.78 +
1.79 + # Or make a directory for the parent.
1.80 +
1.81 + elif not exists(dirpath):
1.82 + makedirs(dirpath)
1.83 +
1.84 + # Obtain a complete filename for the content.
1.85 +
1.86 + pathname = self.get_filename(filename)
1.87 +
1.88 + # Write to an index filename within any existing directory.
1.89 +
1.90 + if isdir(pathname):
1.91 + pathname = join(pathname, self.index_name)
1.92 +
1.93 + self.writefile(text, pathname, encoding)
1.94 +
1.95 output = DirectoryOutput
1.96
1.97 # vim: tabstop=4 expandtab shiftwidth=4