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