1 #!/usr/bin/env python 2 3 """ 4 Output 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 import codecs 23 24 class Output: 25 26 "A common output context abstraction." 27 28 default_encoding = "utf-8" 29 30 def __init__(self, parameters=None): 31 32 "Initialise the output context with the optional 'parameters'." 33 34 self.parameters = parameters 35 self.encoding = parameters and parameters.get("encoding") or self.default_encoding 36 self.reset() 37 38 def reset(self): 39 40 "Set up an output collector." 41 42 self.output = [] 43 44 def encode(self, text): 45 46 "Encode 'text' using the configured encoding." 47 48 return encode(text, self.encoding) 49 50 def out(self, text): 51 52 "Add 'text' to the output collector." 53 54 self.output.append(self.encode(text)) 55 56 # Serialisation methods. 57 58 def to_string(self): 59 60 "Return the output as a plain string." 61 62 s = "".join(self.output) 63 self.reset() 64 return s 65 66 # Serialisation methods. 67 68 def can_write(self): 69 70 "Return whether this context supports page writing." 71 72 return False 73 74 def writefile(self, text, filename, encoding=None): 75 76 """ 77 Write 'text' to the file having the given 'filename'. If the 78 optional 'encoding' is specified, override the general encoding. 79 80 Subclasses need to override this method for it to have an effect. 81 """ 82 83 pass 84 85 def writepage(self, text, pagename, encoding=None): 86 87 """ 88 Write 'text' to the file having the given 'pagename' and optional 89 'encoding'. 90 """ 91 92 return self.writefile(text, self.to_filename(pagename), encoding) 93 94 # Output methods. 95 96 def writepath(self, text, filename, encoding=None): 97 98 """ 99 Write 'text' to the file having the given 'filename'. If the 100 optional 'encoding' is specified, override the general encoding. 101 """ 102 103 f = codecs.open(filename, "w", encoding=encoding or self.encoding) 104 try: 105 f.write(text) 106 finally: 107 f.close() 108 109 def encode(s, encoding): 110 111 "Encode 's' using 'encoding' if Unicode." 112 113 if isinstance(s, unicode): 114 return s.encode(encoding) 115 else: 116 return s 117 118 # vim: tabstop=4 expandtab shiftwidth=4