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