|
| 1 | +#!/bin/env python3 |
| 2 | + |
| 3 | +"""cross platform wrapper around codeql generate query-help to check .qhelp files |
| 4 | +
|
| 5 | +This takes care of: |
| 6 | +* providing a temporary directory to --output |
| 7 | +* finding usages of .inc.qhelp arguments |
| 8 | +""" |
| 9 | + |
| 10 | +import pathlib |
| 11 | +import tempfile |
| 12 | +import sys |
| 13 | +import subprocess |
| 14 | +import xml.sax |
| 15 | + |
| 16 | + |
| 17 | +include_cache = {} |
| 18 | + |
| 19 | +class IncludeHandler(xml.sax.ContentHandler): |
| 20 | + def __init__(self, xml): |
| 21 | + self.__xml = xml |
| 22 | + |
| 23 | + def startElement(self, name, attrs): |
| 24 | + if name == "include": |
| 25 | + src = (self.__xml.parent / attrs["src"]).resolve() |
| 26 | + include_cache.setdefault(src, set()).add(self.__xml) |
| 27 | + |
| 28 | +class IgnoreErrorsHandler(xml.sax.ErrorHandler): |
| 29 | + def error(self, exc): |
| 30 | + pass |
| 31 | + |
| 32 | + def fatalError(self, exc): |
| 33 | + pass |
| 34 | + |
| 35 | + def warning(self, exc): |
| 36 | + pass |
| 37 | + |
| 38 | +def init_include_cache(): |
| 39 | + if not include_cache: |
| 40 | + for qhelp in pathlib.Path().rglob("*.qhelp"): |
| 41 | + xml.sax.parse(qhelp, IncludeHandler(qhelp), IgnoreErrorsHandler()) |
| 42 | + |
| 43 | + |
| 44 | +def find_inc_qhelp_usages(arg): |
| 45 | + init_include_cache() |
| 46 | + return include_cache.get(arg.resolve(), ()) |
| 47 | + |
| 48 | +def transform_inputs(args): |
| 49 | + for arg in args: |
| 50 | + arg = pathlib.Path(arg) |
| 51 | + if arg.suffixes == ['.inc', '.qhelp']: |
| 52 | + for qhelp in find_inc_qhelp_usages(arg): |
| 53 | + yield str(qhelp) |
| 54 | + else: |
| 55 | + yield str(arg) |
| 56 | + |
| 57 | +affected_qhelp_files = list(transform_inputs(sys.argv[1:])) |
| 58 | +if not affected_qhelp_files: |
| 59 | + # can happen with changes on an unused .inc.qhelp file |
| 60 | + print("nothing to do!") |
| 61 | + sys.exit(0) |
| 62 | + |
| 63 | +cmd = ["codeql", "generate", "query-help", "--format=markdown"] |
| 64 | + |
| 65 | +with tempfile.TemporaryDirectory() as tmp: |
| 66 | + cmd += [f"--output={tmp}", "--"] |
| 67 | + cmd += affected_qhelp_files |
| 68 | + res = subprocess.run(cmd) |
| 69 | + |
| 70 | +sys.exit(res.returncode) |
0 commit comments