1 #!/usr/bin/env python 2 3 """ 4 Input context common functionality. 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 os.path import split 23 import codecs 24 25 class Input: 26 27 "A common input context abstraction." 28 29 default_encoding = "utf-8" 30 31 def __init__(self, parameters=None): 32 33 "Initialise the input context with the optional 'parameters'." 34 35 self.parameters = parameters 36 self.encoding = parameters and parameters.get("encoding") or self.default_encoding 37 38 def all(self): 39 40 "Return all pages in the context." 41 42 return [] 43 44 # Page characteristics. 45 46 def parent(self, pagename): 47 48 "Return the parent of 'pagename'." 49 50 return pagename.rsplit("/", 1)[0] 51 52 def subpages(self, pagename): 53 54 "Return the subpages of 'pagename'." 55 56 return [] 57 58 # Page access methods. 59 60 def readfile(self, filename, encoding=None): 61 62 """ 63 Return the contents of the file having the given 'filename' and optional 64 'encoding'. This implementation treats 'filename' as a path. 65 """ 66 67 return self.readpath(filename, encoding) 68 69 def readpage(self, pagename, encoding=None): 70 71 """ 72 Return the contents of the file having the given 'pagename' and optional 73 'encoding'. 74 """ 75 76 return self.readfile(self.to_filename(pagename), encoding) 77 78 # Input methods. 79 80 def readpath(self, filename, encoding=None): 81 82 """ 83 Return the contents of the file having the given 'filename'. If the 84 optional 'encoding' is specified, override the general encoding. 85 """ 86 87 f = codecs.open(filename, encoding=encoding or self.encoding) 88 try: 89 return f.read() 90 finally: 91 f.close() 92 93 # Name translation methods. 94 95 def to_filename(self, pagename): 96 97 "Return the filename corresponding to 'pagename'." 98 99 return pagename 100 101 def to_pagename(self, filename): 102 103 "Return the pagename corresponding to 'filename'." 104 105 # Take the leafname as the pagename from an arbitrary filename. 106 107 return split(filename)[-1] 108 109 # vim: tabstop=4 expandtab shiftwidth=4