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