Debian Codegraph @

python-scripts/validate-tables/bin/validate-tables.py

raw
1 #!/usr/bin/env python3
2 #
3 # validate-tables.py - Validate that DocBook tables are properly formatted
4 # Copyright (C) 2019 SUSE LLC / Martin Doucha <[email protected]>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 2 or 3 of the License.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17
18 import sys
19 import traceback
20 from lxml import etree
21
22 docbook_nsmap = {'d': 'http://docbook.org/ns/docbook'}
23
24 class DocBookError(RuntimeError):
25 """Exception class for DocBook formatting errors"""
26
27 def __init__(self, elem, message, *args, **kwargs):
28 tmp = element_info(elem)
29 super().__init__(tmp + ' ' + message, *args, **kwargs)
30
31 class CALSTable:
32 """
33 Validation class for CALS tables.
34 https://www.oasis-open.org/specs/a502.htm
35 """
36
37 def __init__(self, node):
38 self.node = node
39 self.tgroups = []
40
41 if node.tag == 'entrytbl':
42 self.tgroups.append(parse_tgroup(node))
43 else:
44 tgroup_list = node.xpath('tgroup|d:tgroup',
45 namespaces=docbook_nsmap)
46 for item in tgroup_list:
47 self.tgroups.append(parse_tgroup(item))
48
49 def validate(self):
50 err_list = []
51 for colcount, blocks in self.tgroups:
52 tmp = validate_table(blocks, colcount)
53 if tmp:
54 err_list.append(tmp)
55 if err_list:
56 raise DocBookError(self.node, 'Errors in table:\n' +
57 '\n'.join(err_list))
58
59 class HTMLTable:
60 """
61 Validation class for HTML-style tables.
62 """
63
64 def __init__(self, node):
65 self.node = node
66 thead = optional_node(node, 'thead|d:thead')
67 tfoot = optional_node(node, 'tfoot|d:tfoot')
68 tbody_list = node.xpath('tbody|d:tbody', namespaces=docbook_nsmap)
69 tr_list = node.xpath('tr|d:tr', namespaces=docbook_nsmap)
70
71 if len(tbody_list) > 0 and len(tr_list) > 0:
72 raise DocBookError(node, 'HTML table cannot contain both <tbody> and <tr>')
73
74 if len(tbody_list) <= 0 and len(tr_list) <= 0:
75 raise DocBookError(node, 'HTML table must contain <tbody> or <tr>')
76
77 self.blocks = []
78 self.colcount = count_coldefs(node)
79
80 if thead is not None:
81 self.blocks.append((thead, parse_html_tblock(thead)))
82
83 for item in tbody_list:
84 self.blocks.append((item, parse_html_tblock(item)))
85
86 if len(tr_list) > 0:
87 self.blocks.append((node, parse_html_tblock(node)))
88
89 if tfoot is not None:
90 self.blocks.append((tfoot, parse_html_tblock(tfoot)))
91
92 if self.colcount is None:
93 self.colcount = 0
94 for cnum, rspan, cspan in self.blocks[0][1][0]:
95 self.colcount += cspan
96
97 def validate(self):
98 msg = validate_table(self.blocks, self.colcount)
99
100 if msg:
101 raise DocBookError(self.node, 'Errors in table:\n' + msg)
102
103 def optional_node(parent, xpath):
104 """Find single XML node or return NULL. Multiple nodes result in error."""
105 tmp = parent.xpath(xpath, namespaces=docbook_nsmap)
106
107 if len(tmp) > 1:
108 raise DocBookError(parent, 'XPath returned too many results: ' + xpath)
109 elif len(tmp) > 0:
110 return tmp[0]
111 return None
112
113 def element_info(elem):
114 """Generate element info string: "filename:line: <tag>"."""
115 return '%s:%d: <%s>' % (elem.base, elem.sourceline, elem.tag)
116
117 def intattr(node, attrname, default=None, required=True):
118 """Get and validate int() value of XML attribute."""
119 value = node.attrib.get(attrname, default)
120
121 if value is None:
122 if required:
123 raise DocBookError(node, 'Missing attribute %s' % attrname)
124 return None
125
126 try:
127 return int(value)
128 except ValueError as err:
129 raise DocBookError(node, 'Invalid %s value' % attrname) from err
130
131 def parse_tgroup(node):
132 """Parse CALS table <tgroup> or <entrytbl> element"""
133 blocks = []
134 colcount = intattr(node, 'cols')
135
136 if colcount is None or colcount < 1:
137 raise DocBookError(node, 'Invalid cols attribute')
138
139 colspec = parse_colspec(node, colcount)
140 spanspec = parse_spanspec(node, colspec)
141 thead = optional_node(node, 'thead|d:thead')
142 tfoot = optional_node(node, 'tfoot|d:tfoot')
143 tbody_list = node.xpath('tbody|d:tbody', namespaces=docbook_nsmap)
144
145 if len(tbody_list) != 1:
146 raise DocBookError(node, 'Element must contain exactly one <tbody>')
147
148 if thead is not None:
149 tmpspec = parse_colspec(thead, colcount)
150 if tmpspec:
151 blocks.append((thead, parse_cals_tblock(thead, tmpspec, dict())))
152 else:
153 blocks.append((thead, parse_cals_tblock(thead, colspec, spanspec)))
154 tbody = tbody_list[0]
155 blocks.append((tbody, parse_cals_tblock(tbody, colspec, spanspec)))
156 if tfoot is not None:
157 tmpspec = parse_colspec(tfoot, colcount)
158 if tmpspec:
159 blocks.append((tfoot, parse_cals_tblock(tfoot, tmpspec, dict())))
160 else:
161 blocks.append((tfoot, parse_cals_tblock(tfoot, colspec, spanspec)))
162
163 return (colcount, blocks)
164
165 def parse_colspec(node, colcount):
166 """Parse CALS table <colspec> list"""
167 ret = dict()
168 nodelist = node.xpath('colspec|d:colspec', namespaces=docbook_nsmap)
169 checklist = [None] * colcount
170 pos = 1
171
172 for item in nodelist:
173 pos = intattr(item, 'colnum', pos)
174 if pos < 1 or pos > colcount:
175 raise DocBookError(item, 'Invalid colnum attribute')
176 if checklist[pos - 1] is not None:
177 raise DocBookError(item, 'Duplicate <colspec> element for column %d'
178 % pos)
179
180 colname = item.attrib.get('colname')
181 if colname is not None and colname in ret:
182 raise DocBookError(item, 'Duplicate colname value')
183
184 checklist[pos - 1] = item
185
186 if colname is not None:
187 ret[colname] = pos - 1
188 pos += 1
189
190 return ret
191
192 def parse_spanspec(node, colspec):
193 """Parse CALS table <spanspec> list"""
194 ret = dict()
195 nodelist = node.xpath('spanspec|d:spanspec', namespaces=docbook_nsmap)
196
197 for item in nodelist:
198 name = item.attrib.get('spanname')
199 startname = item.attrib.get('namest')
200 endname = item.attrib.get('nameend')
201 if name is None or startname is None or endname is None:
202 raise DocBookError(item, 'Missing required attributes')
203 if name in ret:
204 raise DocBookError(item, 'Duplicate spanname value')
205
206 startcol = colspec.get(startname)
207 endcol = colspec.get(endname)
208 if startcol is None:
209 raise DocBookError(item, 'Invalid namest attribute')
210 if endcol is None:
211 raise DocBookError(item, 'Invalid nameend attribute')
212 if startcol >= endcol:
213 raise DocBookError(item, 'Span start column must be before end column')
214
215 ret[name] = (startcol, endcol - startcol + 1)
216 return ret
217
218 def parse_cals_tblock(node, colspec, spanspec):
219 """Parse CALS table <thead>, <tfoot> or <tbody> element"""
220 ret = []
221 row_list = node.xpath('row|d:row', namespaces=docbook_nsmap)
222
223 if len(row_list) <= 0:
224 raise DocBookError(node, 'Element contains no <row>')
225
226 for row in row_list:
227 nodelist = row.xpath('entry|d:entry|entrytbl|d:entrytbl',
228 namespaces=docbook_nsmap)
229 col_list = []
230
231 if len(nodelist) <= 0:
232 raise DocBookError(row, 'Empty row')
233
234 for col in nodelist:
235 colname = col.attrib.get('colname')
236 spanname = col.attrib.get('spanname')
237 namest = col.attrib.get('namest')
238 nameend = col.attrib.get('nameend')
239
240 colnum = None
241 rowspan = intattr(col, 'morerows', 0) + 1
242 colspan = 1
243
244 if rowspan <= 0:
245 raise DocBookError(col, 'Invalid morerows value')
246
247 if spanname is not None:
248 tmp = spanspec.get(spanname)
249 if tmp is None:
250 raise DocBookError(col, 'Invalid spanname value')
251 colnum, colspan = tmp
252 elif namest is not None:
253 colnum = colspec.get(namest)
254 if colnum is None:
255 raise DocBookError(col, 'Invalid namest value')
256 if nameend is not None:
257 endcol = colspec.get(nameend)
258 if endcol is None:
259 raise DocBookError(col, 'Invalid nameend value')
260 if colnum >= endcol:
261 raise DocBookError(col, 'Span start column must be before end column')
262 colspan = endcol - colnum + 1
263 elif colname is not None:
264 colnum = colspec.get(colname)
265 if colnum is None:
266 raise DocBookError(col, 'Invalid colname value')
267 col_list.append((colnum, rowspan, colspan))
268 ret.append(col_list)
269 return ret
270
271 def parse_html_tblock(node):
272 """
273 Parse HTML table <thead>, <tfoot>, <tbody> element or rows directly
274 under <table> or <informaltable>
275 """
276 ret = []
277 row_list = node.xpath('tr|d:tr', namespaces=docbook_nsmap)
278
279 if len(row_list) <= 0:
280 raise DocBookError(node, 'Element contains no <tr>')
281
282 for row in row_list:
283 nodelist = row.xpath('td|d:td|th|d:th', namespaces=docbook_nsmap)
284 col_list = []
285
286 if len(nodelist) <= 0:
287 raise DocBookError(row, 'Empty row')
288
289 for col in nodelist:
290 rowspan = intattr(col, 'rowspan', 1)
291 colspan = intattr(col, 'colspan', 1)
292
293 if rowspan <= 0:
294 raise DocBookError(col, 'Invalid rowspan')
295 if colspan <= 0:
296 raise DocBookError(col, 'Invalid colspan')
297
298 col_list.append((None, rowspan, colspan))
299 ret.append(col_list)
300
301 return ret
302
303 def count_coldefs(node):
304 """Validate <col>/<colgroup> definitions and calculate column count"""
305 ret = None
306 coldef = node.xpath('col|d:col', namespaces=docbook_nsmap)
307
308 if len(coldef) > 0:
309 ret = len(coldef)
310
311 coldef = node.xpath('colgroup|d:colgroup', namespaces=docbook_nsmap)
312
313 if len(coldef) <= 0:
314 return ret
315 if ret is not None:
316 raise DocBookError(node, 'Table cannot contain both <col> and <colgroup>')
317
318 ret = 0
319 for item in coldef:
320 tmp = int(item.xpath('count(col|d:col)', namespaces=docbook_nsmap))
321 if tmp > 0:
322 ret += tmp
323 else:
324 ret += intattr(item, 'span', 1)
325 return ret
326
327 def expand_cells(parent, tblock, colcount):
328 """Generate table layout for validation/rendering"""
329 ret = []
330 for row in tblock:
331 ret.append(colcount * [0])
332 for rpos, row in enumerate(tblock):
333 cpos = 0
334 for startpos, rspan, cspan in row:
335 # handle rowspan from preceding rows
336 while cpos < len(ret[rpos]) and ret[rpos][cpos] > 0:
337 cpos += 1
338 if startpos is not None:
339 if startpos < cpos:
340 raise DocBookError(parent, 'Swapped cells on row %d' %
341 (rpos+1))
342 cpos = startpos
343 for y in range(rspan):
344 if rpos + y >= len(ret):
345 ret.append(colcount * [0])
346 cell_list = ret[rpos + y]
347 for x in range(cspan):
348 if cpos + x >= len(cell_list):
349 cell_list.append(1)
350 else:
351 cell_list[cpos + x] += 1
352 cpos += cspan
353 return ret
354
355 def render_cells(row_prefix, cell_block, rowcount, colcount):
356 """Render table layout in ASCII art"""
357 ret = []
358 for rpos, row in enumerate(cell_block):
359 err = (len(row) != colcount) or rpos >= rowcount
360 err = err or bool([x for x in row if x != 1])
361 tmp = []
362 tmp.append('!!' if err else ' ')
363 tmp.append(row_prefix if rpos < rowcount else (' ' * len(row_prefix)))
364 tmp.append(' ')
365
366 for cpos, item in enumerate(row):
367 if item > 1:
368 tmp.append('X')
369 elif item <= 0:
370 tmp.append(' ')
371 elif cpos >= colcount or rpos >= rowcount:
372 tmp.append('+')
373 else:
374 tmp.append('o')
375 ret.append(''.join(tmp))
376 return '\n'.join(ret)
377
378 def validate_cells(cell_block, rowcount, colcount):
379 """
380 Validate layout of a single table block (<thead>, <tfoot> or <tbody>).
381 Check for holes, overflows and intersecting cells.
382 """
383 err_list = []
384 if len(cell_block) > rowcount:
385 err_list.append('Rowspan overflow')
386 for rpos, row in enumerate(cell_block[:rowcount], start=1):
387 if len(row) > colcount:
388 err_list.append('Column overflow on row %d' % rpos)
389 if [x for x in row if x < 1]:
390 err_list.append('Holes in row %d' % rpos)
391 if [x for x in row if x > 1]:
392 err_list.append('Intersecting cells on row %d' % rpos)
393 return err_list
394
395 def validate_table(blocklist, colcount):
396 """Validate entire HTML table or CALS <tgroup> (from layout)"""
397 pmap = dict(thead='H', tfoot='F', tbody='B', table='T', informaltable='T')
398 cell_blocks = []
399 for parent, rowlist in blocklist:
400 cell_blocks.append((parent, rowlist, pmap.get(parent.tag, '?'),
401 expand_cells(parent, rowlist, colcount)))
402
403 err_list = []
404 for parent, rowlist, prefix, block in cell_blocks:
405 tmp = validate_cells(block, len(rowlist), colcount)
406 if tmp:
407 tmp.insert(0, '- ' + element_info(parent))
408 err_list.append('\n - '.join(tmp))
409
410 if not err_list:
411 return None
412
413 block_list = []
414 for parent, rowlist, prefix, block in cell_blocks:
415 block_list.append(render_cells(prefix, block, len(rowlist), colcount))
416 sep = '\n ' + ('-' * colcount) + '\n'
417 rendered = sep.join(block_list)
418 return '\n'.join(err_list) + '\n\n' + rendered
419
420 # Validate entire table
421 def check_table(node):
422 """Validate <table>, <informaltable> or <entrytbl> element"""
423 tr_list = node.xpath('.//tr|.//d:tr', namespaces=docbook_nsmap)
424 row_list = node.xpath('.//row|.//d:row', namespaces=docbook_nsmap)
425
426 if len(tr_list) > 0 and len(row_list) > 0:
427 raise DocBookError(node, 'Table cannot contain both CALS and HTML elements')
428
429 if len(tr_list) <= 0 and len(row_list) <= 0:
430 raise DocBookError(node, 'Empty table')
431
432 if len(tr_list) > 0:
433 table = HTMLTable(node)
434 else:
435 table = CALSTable(node)
436
437 table.validate()
438
439 # Validate DocBook file
440 def check_file(filename):
441 """Validate tables in DocBook file."""
442 parser = etree.XMLParser(load_dtd=True, huge_tree=True)
443 try:
444 xml = etree.parse(filename, parser)
445 xml.xinclude()
446 except (etree.XIncludeError, etree.XMLSyntaxError) as error:
447 print(error, file=sys.stderr)
448 sys.exit(10)
449 tablist = xml.xpath('//table|//informaltable|//entrytbl|//d:table|//d:informaltable|//d:entrytbl',
450 namespaces=docbook_nsmap)
451 ret = 0
452 for table in tablist:
453 try:
454 check_table(table)
455 except DocBookError as err:
456 print(err.args[0], '\n', file=sys.stderr)
457 ret = 1
458 return ret
459
460 if __name__ == '__main__':
461 ret = 0
462 for filename in sys.argv[1:]:
463 try:
464 ret |= check_file(filename)
465 except:
466 print('Error checking file %s:' % filename, file=sys.stderr)
467 traceback.print_exc()
468 ret |= 2
469 exit(ret)