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