1 #!/usr/bin/env python 2 3 """ 4 Moin serialiser support. 5 6 Copyright (C) 2017, 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 class Serialiser: 23 24 "General serialisation support." 25 26 format = None # defined by subclasses 27 28 def __init__(self, output, formats=None, linker=None, pagename=None): 29 30 """ 31 Initialise the serialiser with an 'output' context, an optional 32 'formats' mapping from names to serialiser classes, an optional 'linker' 33 object for translating links, and an optional 'pagename'. 34 """ 35 36 self.output = output 37 self.formats = formats 38 self.linker = linker 39 self.pagename = pagename 40 41 # Initialise a callable for use in serialisation. 42 43 self.out = output.out 44 45 # Initialisation of any other state. 46 47 self.init() 48 49 def init(self): 50 51 "Initialisation method to be overridden by subclasses." 52 53 pass 54 55 def __repr__(self): 56 return "%s(%r, %r, %r, %r)" % (self.__class__.__name__, self.output, 57 self.formats, self.linker, self.pagename) 58 59 def get_serialiser(self, format): 60 61 """ 62 Return a serialiser for the given 'format'. Return self if no suitable 63 serialiser can be obtained. 64 """ 65 66 cls = self.formats and self.formats.get(format) 67 if cls: 68 return self.instantiate(cls) 69 else: 70 return self 71 72 def get_output(self): 73 74 "Return the output as a string." 75 76 return self.output.to_string() 77 78 def instantiate(self, cls): 79 80 """ 81 Instantiate 'cls' and return the result if 'cls' is a different class to 82 this instance. Otherwise, return this instance. 83 """ 84 85 if cls is self.__class__: 86 return self 87 else: 88 return cls(self.output, self.formats, self.linker, self.pagename) 89 90 def escape_attr(s): 91 92 "Escape XML document attribute." 93 94 return escape_text(s).replace("'", "'").replace('"', """) 95 96 def escape_text(s): 97 98 "Escape XML document text." 99 100 return s.replace("&", "&").replace("<", "<").replace(">", ">") 101 102 # vim: tabstop=4 expandtab shiftwidth=4