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