Debian Codegraph @

python-scripts/daps-xmlwellformed/tests/dxwf.py

raw
1 #!/usr/bin/env python3
2 #
3 """Performs a well-formedness check on XML.
4
5 This script is needed as xmllint cannot ignore duplicated IDs.
6 This tool:
7
8 * Processes XIncludes (if requested using the option --xinclude)
9 * Ignores non-unique IDs (attributes xml:id or id)
10 * Outputs errors about undeclared entities
11 """
12
13 __author__ = "Thomas Schraitle"
14 __version__ = "0.3.1"
15
16 import argparse
17 import enum
18 import logging
19 from io import StringIO
20 import re
21 import sys
22
23 from lxml import etree
24
25
26 ROOTLOGGER = "lxmlerrors"
27 # Hint: file keyword needs to be filled with extra keyword on the
28 # logger methods .critical, .debug(), .error(), .fatal(), and .warn().
29 # For example:
30 # log.error("...", extra=dict(file="foo.xml", ))
31 # Basically everything can be used what is in ERROR_PATTERN
32 FORMAT = "%(file)s:\n %(levelname)s: %(message)s (line %(line)s column %(col)s)"
33
34 logger = logging.getLogger(ROOTLOGGER)
35 ch = logging.StreamHandler()
36 ch.setLevel(logging.ERROR)
37 ch.setFormatter(logging.Formatter(FORMAT))
38 logger.addHandler(ch)
39
40 if etree.LXML_VERSION < (4, 4, 2):
41 logger.fatal("Need a minimum version of 4.4.2 of lxml, got %s",
42 ".".join([str(e) for e in etree.LXML_VERSION]),
43 extra=dict(file=__file__,
44 line="", col=""))
45 sys.exit(10)
46
47
48 # Format of libxml error messages:
49 # foo.xml:3:16:FATAL:PARSER:ERR_UNDECLARED_ENTITY:
50 # This regex was tested against XML files with ":"
51 ERROR_PATTERN = re.compile(
52 r"(?P<file>.*)"
53 r":(?P<line>\d+)"
54 r":(?P<col>\d+)"
55 r":(?P<level>[A-Z]+)"
56 r":(?P<origin>[A-Z]+)"
57 r":(?P<domain>[A-Z_]+)"
58 r":\s*"
59 r"(?P<message>.*)$"
60 )
61
62
63 class ExitCode(enum.IntEnum):
64 """Our return codes
65 """
66 ok, syntax, entities, xinclude, multiple, file_not_found = range(0, 60, 10)
67 unknown = 200
68
69
70 def extract_log(stream):
71 """Extract log record from stream
72 """
73 for line in stream.getvalue().split("\n"):
74 if not line:
75 continue
76 match = ERROR_PATTERN.search(line)
77 yield match.groupdict()
78
79
80 def print_error_msg(stream) -> int:
81 """Print log line from stream
82
83 :param stream: the stream we want to extract the messages from
84 :return: the number of found entries (=error message lines)
85 """
86 error_map = {
87 "FATAL": logging.FATAL, # etree.ErrorLevels.FATAL
88 "ERROR": logging.ERROR, # etree.ErrorLevels.ERROR
89 "WARNING": logging.WARNING, # etree.ErrorLevels.WARNING
90 }
91 idx = 0
92 for entry in extract_log(stream):
93 level = error_map.get(entry["level"], logging.ERROR)
94 msg = entry.pop("message")
95 logger.log(level, msg, extra=entry)
96 idx += 1
97
98 return idx
99
100
101 def check_wellformedness(xmlfile: str, xinclude: bool = True) -> int:
102 """Checks a file for well-formedness
103
104 This only works with lxml >= 3.4.0 (because of collect_ids option)
105
106 :param xmlfile: filename to XML file
107 :param xinclude: do xinclude processing (default: True) or not
108 :return: 0 (everything ok) or != 0 (some problem)
109 :rtype: int
110 """
111 # We don't want to collect all IDs to avoid problems when
112 # IDs are non-unique:
113 result = ExitCode.ok
114
115 log_stream = StringIO()
116 log = logging.getLogger(ROOTLOGGER).getChild("wellformedness")
117 log.propagate = False
118 ch = logging.StreamHandler(log_stream)
119 ch.setLevel(logging.WARNING)
120 log.addHandler(ch)
121 #
122 etree.use_global_python_log(etree.PyErrorLog(xmlfile, log))
123 xmlparser = etree.XMLParser(collect_ids=False)
124
125 try:
126 tree = etree.parse(xmlfile, parser=xmlparser)
127
128 if xinclude:
129 tree.xinclude()
130
131 except OSError as err:
132 # FATAL:PARSER:ERR_UNDECLARED_ENTITY:
133 # Write artificial error message to our log stream:
134 log_stream.write(f"{xmlfile}:0:0:FATAL:PARSER:FILE_NOT_FOUND:File does not exist\n")
135 result = ExitCode.file_not_found.value
136
137 except etree.XMLSyntaxError as err:
138 result = ExitCode.syntax.value
139
140 except etree.XIncludeError as err:
141 result = ExitCode.xinclude.value
142
143 idx = print_error_msg(log_stream)
144
145 # HACK:
146 # For some unknown reason, when parsing MAIN.SLEDS.xml with an unknown
147 # entity, it doesn't raise XIncludeError or XMLSyntaxError exceptions. :-(
148 #
149 # If the return code hasn't changed but there are error messages,
150 # make sure to return some error code:
151 if idx and result == ExitCode.ok:
152 result = ExitCode.multiple
153 return result
154
155
156 def parse_cli(args=None) -> argparse.Namespace:
157 """Parse CLI arguments
158
159 :param list args: Use the list or sys.args
160 :return: parsed arguments
161 :rtype: :class:`argparse.Namespace`
162 """
163 parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0],
164 epilog=__doc__.split("\n", 1)[-1],
165 )
166 parser.add_argument("--version",
167 action="version",
168 version="%(prog)s {}".format(__version__),
169 )
170 parser.add_argument("--xinclude",
171 action="store_true",
172 default=False,
173 help="Do XInclude processing"
174 )
175 parser.add_argument("-W", "--warnings-as-errors",
176 action="store_true",
177 default=False,
178 help=("Flag to set the behavior when "
179 "referenced files with XIncludes cannot "
180 "be found; "
181 "(default: %(default)s)")
182 )
183 parser.add_argument("-S", "--stats",
184 action="store_true",
185 default=False,
186 help=("Print statistic about successful/"
187 "failed files"
188 )
189 )
190 parser.add_argument("xmlfiles",
191 nargs="+",
192 help="XML file(s) to check for well-formedness"
193 )
194 args = parser.parse_args(args)
195 return args
196
197
198 def main(cliargs=None) -> int:
199 """Entry point for the application script
200
201 :param list cliargs: Arguments to parse or None (=use :class:`sys.argv`)
202 :return: error code; 0 => everything was successful, !=0 => error
203 :rtype: int
204 """
205 endresult = ExitCode.ok
206 failures = 0
207 successes = 0
208
209 args = parse_cli(cliargs)
210
211 for xmlfile in args.xmlfiles:
212 result = check_wellformedness(xmlfile,
213 xinclude=args.xinclude
214 )
215 if result and args.warnings_as_errors:
216 break
217 if result:
218 failures += 1
219 else:
220 successes += 1
221 endresult += result
222
223 if args.stats:
224 msg = (f"--- Successful Files={successes}, "
225 f"Failed files={failures} ---"
226 )
227 print(msg, file=sys.stderr)
228
229 return int(endresult)
230
231
232 if __name__ == "__main__":
233 sys.exit(main())