File: xmlparser.py

package info (click to toggle)
dblatex 0.3.12py3-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 12,684 kB
  • sloc: xml: 102,889; python: 8,259; makefile: 119; sh: 48
file content (325 lines) | stat: -rw-r--r-- 9,763 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import os
import re
import xml.etree.ElementTree as ET
from .txtparser import texinputs_parse

class BaseOption:
    def __init__(self, config, optname):
        self.config = config
        self.optname = optname
        self._value = None

    def optvalue(self):
        return self._value

    def get(self, what, default=None):
        return None

    def options(self):
        value = self.optvalue()
        if self.optname and value:
            return ["%s=%s" % (self.optname, value)]
        else:
            return []

    def fromnode(self, xmlnode):
        self._value = xmlnode.text

    def modules(self):
        return {}

class CommandConfig:
    def __init__(self, config, type="command"):
        self.config = config
        self.type = type
        self.args = []
        self.stdin = None
        self.stdout = None
        self.shell = False

    def options(self):
        return self.args

    def modules(self):
        return {}

    def fromnode(self, xmlnode):
        self.stdin = xmlnode.get("input")
        self.stdout = xmlnode.get("output")
        self.shell = xmlnode.get("shell")
        args = (xmlnode.text or "").split()
        for arg in xmlnode:
            if arg.text: args.append(arg.text)
            args.extend((arg.tail or "").split())
        self.args = args

class TexStyle(BaseOption):
    def __init__(self, config, optname):
        BaseOption.__init__(self, config, optname)
        self.filepath = ""

    def optvalue(self):
        return self.filepath

    def fromnode(self, xmlnode):
        self.filepath = xmlnode.get("fileref") or xmlnode.get("use")

class TexPath(BaseOption):
    def __init__(self, config, optname):
        BaseOption.__init__(self, config, optname)
        self.paths = []

    def optvalue(self):
        return os.pathsep.join(self.paths)

    def fromnode(self, xmlnode):
        if not(xmlnode.text): return
        self.paths = texinputs_parse(xmlnode.text, self.config.basedir)

class FilePath(BaseOption):
    def __init__(self, config, optname):
        BaseOption.__init__(self, config, optname)
        self.filepath = ""

    def optvalue(self):
        return self.filepath

    def fromnode(self, xmlnode):
        filepath = xmlnode.get("fileref")
        if not(filepath):
            return
        if not(os.path.isabs(filepath)):
            filepath = os.path.normpath(os.path.join(self.config.basedir,
                                                     filepath))
        self.filepath = filepath


class ModuleConfig(BaseOption):
    def __init__(self, config, optname):
        BaseOption.__init__(self, config, optname)
        self.commands = []
        self.extra_args = None
        self.module_name = ""
        self.module_file = ""

    def optvalue(self):
        return self.module_name or self.module_file

    def modules(self):
        if self.module_name:
            return {self.module_name: self}
        else:
            return {}

    def fromnode(self, xmlnode):
        ns = { "x": self.config.xmlns }
        self._handle_location(xmlnode)
        xmlopts = xmlnode.find("x:options", ns)
        xmlcmds = xmlnode.find("x:command", ns)
        xmlchain = xmlnode.find("x:commandchain", ns)
        if not(xmlchain is None):
            xmlcmds = xmlchain.findall("x:command", ns)
            for cmd in xmlcmds:
                args = CommandConfig(self.config)
                args.fromnode(cmd)
                self.commands.append(args)
        elif not(xmlcmds is None):
            args = CommandConfig(self.config)
            args.fromnode(xmlcmds)
            self.commands.append(args)
        elif not(xmlopts is None):
            # FIXME
            self.extra_args = CommandConfig(self.config, type="option")
            self.extra_args.fromnode(xmlopts)

    def _handle_location(self, xmlnode):
        self.module_name = xmlnode.get("use")
        self.module_file = xmlnode.get("fileref")
        if not(self.module_name) and self.module_file:
            p = FilePath(self.config, "")
            p.fromnode(xmlnode)
            self.module_file = p.filepath

class ImageConverterConfig(ModuleConfig):
    def __init__(self, config, optname):
        ModuleConfig.__init__(self, config, optname)

    def __repr__(self):
        return self.module_name

    def fromnode(self, xmlnode):
        self.imgsrc = xmlnode.get("src")
        self.imgdst = xmlnode.get("dst")
        self.docformat = xmlnode.get("docformat") or "*"
        self.backend = xmlnode.get("backend") or "*"
        ModuleConfig.fromnode(self, xmlnode)
        name = "%s/%s/%s/%s" % (self.imgsrc, self.imgdst,
                                self.docformat, self.backend)
        self.module_name = name

class ImageFormatConfig(BaseOption):
    def __init__(self, config, optname):
        BaseOption.__init__(self, config, optname)
        self.imgsrc = ""
        self.imgdst = ""
        self.docformat = ""
        self.backend = ""

    def fromnode(self, xmlnode):
        self.imgsrc = xmlnode.get("src")
        self.imgdst = xmlnode.get("dst")
        self.docformat = xmlnode.get("docformat") or "*"
        self.backend = xmlnode.get("backend") or "*"

class XsltEngineConfig(ModuleConfig):
    def __init__(self, config, optname):
        ModuleConfig.__init__(self, config, optname)

    def __repr__(self):
        return self.module_name

    def fromnode(self, xmlnode):
        self.param_format = xmlnode.get("param-format")
        ModuleConfig.fromnode(self, xmlnode)
        if not(self.module_name or self.module_file):
            self.module_name = "xsltconf"

class XmlConfigGroup:
    node_parsers = {}

    def __init__(self, config):
        self.config = config
        self.tagname = ""
        self.infos = {}

    def get(self, tag, default=""):
        if default == "": default = BaseOption(self, "")
        return self.infos.get(tag, default)

    def _register(self, xmlnode, info):
        tag = self.strip_ns(xmlnode.tag)
        taglist = self.infos.get(tag, [])
        taglist.append(info)
        self.infos[tag] = taglist

    def strip_ns(self, tag):
        return self.config.strip_ns(tag)

    def options(self):
        opts = []
        for parsers in self.infos.values():
            for parser in parsers:
                opts.extend(parser.options())
        return opts

    def modules(self):
        mods = {}
        for parsers in self.infos.values():
            for parser in parsers:
                mods.update(parser.modules())
        return mods

    def fromnode(self, xmlnode):
        self.tagname = xmlnode.tag
        for child in xmlnode:
            found = self.node_parsers.get(self.strip_ns(child.tag))
            if found:
                optname, parser_cls = found
                parser = parser_cls(self.config, optname)
                parser.fromnode(child)
                self._register(child, parser)

class LatexConfig(XmlConfigGroup):
    node_parsers = {
        "texinputs":  ("--texinputs", TexPath),
        "bibinputs":  ("--bib-path", TexPath),
        "bstinputs":  ("--bst-path", TexPath),
        "texstyle":   ("--texstyle", TexStyle),
        "indexstyle": ("--indexstyle", FilePath),
        "backend":    ("--backend", ModuleConfig),
        "texpost":    ("--texpost", ModuleConfig)
    }

class XsltConfig(XmlConfigGroup):
    node_parsers = {
        "stylesheet": ("--xsl-user", FilePath),
        "engine":     ("--xslt", XsltEngineConfig)
    }

class ImageConfig(XmlConfigGroup):
    node_parsers = {
        "figpath": ("--fig-path", FilePath),
        "figformat": ("--fig-format", BaseOption),
        "converter": ("", ImageConverterConfig),
        "formatrule": ("", ImageFormatConfig)
    }


class XmlConfig:
    """
    Parses an XML configuration file and stores its data in
    configuration objects.
    """
    node_parsers = {
        "latex": LatexConfig,
        "xslt": XsltConfig,
        "imagedata": ImageConfig,
        "options": CommandConfig
    }
    xmlns = "http://dblatex.sourceforge.net/config"
    root_tag = "config"

    def __init__(self):
        self.basedir = ""
        self.infos = {}

    def _register(self, xmlnode, info):
        self.infos[self.strip_ns(xmlnode.tag)] = info

    def get(self, tag, default=""):
        if default == "": default = BaseOption(self, "")
        return self.infos.get(tag, default)

    def options(self):
        opts = []
        for parser in self.infos.values():
            opts.extend(parser.options())
        return opts

    def modules(self):
        mods = {}
        for parser in self.infos.values():
            mods.update(parser.modules())
        return mods

    def strip_ns(self, tag):
        return tag.replace("{%s}" % self.xmlns, "", 1)

    def fromfile(self, filename):
        self.basedir = os.path.dirname(os.path.realpath(filename))

        document = ET.parse(filename)
        root = document.getroot()
        self._check_root(root.tag)
        for child in root:
            parser_cls = self.node_parsers.get(self.strip_ns(child.tag))
            if parser_cls:
                parser = parser_cls(self)
                parser.fromnode(child)
                self._register(child, parser)

    def _check_root(self, root):
        xmlns, tag = self._split_xmlns(root)
        if tag != self.root_tag:
            raise ValueError("Expect the XML config root element being '%s'" % \
                             self.root_tag)
        if xmlns and xmlns != self.xmlns:
            raise ValueError("Invalid XML config xmlns: '%s'" % xmlns)

    def _split_xmlns(self, tag):
        m = re.match("{([^}]+)}(.*)", tag)
        if m:
            return m.group(1), m.group(2)
        else:
            return "", tag