1 #!/usr/bin/env python 2 3 """ 4 Directory input context. 5 6 Copyright (C) 2018 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from moinformat.input.common import Input 23 from moinformat.utils.directory import Directory 24 from os.path import sep 25 26 class DirectoryInput(Input): 27 28 "A directory output context." 29 30 name = "directory" 31 32 def __init__(self, parameters=None): 33 34 "Initialise the context with the given 'parameters'." 35 36 if not parameters or not parameters.has_key("filename"): 37 raise ValueError, parameters 38 39 Input.__init__(self, parameters) 40 self.dir = Directory(parameters["filename"]) 41 42 # Support an encoding of the level separator for the filesystem. 43 # Where it is the same as the directory separator, documents are stored 44 # using nested directories, not as a flat list. 45 46 self.level_sep = parameters and parameters.get("separator") or sep 47 48 def all(self): 49 50 "Return all pages in the context." 51 52 return map(self.to_pagename, self.dir.select_files("*")) 53 54 # Page characteristics. 55 56 def subpage_filenames(self, pagename): 57 58 "Return the subpage filenames of 'pagename'." 59 60 pattern = self.to_filename("%s/*" % pagename) 61 return self.dir.select_files(pattern) 62 63 def subpages(self, pagename): 64 65 "Return the subpages of 'pagename'." 66 67 return map(self.to_pagename, self.subpage_filenames(pagename)) 68 69 # Page access methods. 70 71 def readfile(self, filename, encoding=None): 72 73 """ 74 Return the contents of the file having the given 'filename' and optional 75 'encoding'. 76 """ 77 78 return self.readpath(self.dir.get_filename(filename), encoding) 79 80 # NOTE: Translation methods should encode filenames appropriately. 81 82 def to_filename(self, pagename): 83 84 "Return the filename corresponding to 'pagename'." 85 86 if sep == self.level_sep: 87 return pagename 88 else: 89 return self.level_sep.join(pagename.split("/")) 90 91 def to_pagename(self, filename): 92 93 "Return the pagename corresponding to 'filename'." 94 95 if sep == self.level_sep: 96 return filename 97 else: 98 return "/".join(filename.split(self.level_sep)) 99 100 input = DirectoryInput 101 102 # vim: tabstop=4 expandtab shiftwidth=4