Debian Codegraph @

citeproc/data/schema/tools/rnc-validate-format.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 import os
4 import subprocess
5 import argparse
6 from shutil import which
7 from glob import glob
8
9 # to validate and pretty print the rnc schema files before commit:
10 # tools/rnc-validate-format.py
11
12 parser = argparse.ArgumentParser(description="process csl schema files")
13 parser.add_argument("--commit", action="store_true", help="commit the file(s)")
14 args, unknown = parser.parse_known_args()
15
16 rncdir = os.path.join("schemas", "styles")
17
18
19 def rnc_format(rncfile):
20 try:
21 which("trang") is not None
22 except Exception:
23 raise SystemExit("trang commnd not found; please install")
24
25 rng_new = rncfile + "_new.rng"
26
27 # round-trip the rnc file through trang
28 subprocess.run(["trang", rncfile, rng_new])
29 subprocess.run(["trang", rng_new, rncfile])
30
31 # remove the intermediate files
32 tempfiles = glob(os.path.join(rncdir, "csl*.rng"))
33 for file in tempfiles:
34 os.remove(file)
35
36
37 def rnc_pre_commit():
38
39 # this will only work as part of a pre-commit process, where it will run
40 # rnc_format on any staged rnc files, and then restage
41 cmd = ["git", "diff", "--name-only", "--cached"]
42 changed_files = subprocess.check_output(cmd, text=True).splitlines()
43
44 for changed_file in changed_files:
45 if changed_file.endswith(".rnc"):
46 rnc_format(changed_file)
47 subprocess.run(["git", "add", changed_file])
48
49
50 def main():
51 if args.commit:
52 rnc_pre_commit()
53 else:
54 rnc_format(os.path.join("schemas", "styles", "csl.rnc"))
55 print("\n====> rnc schema files validated and formatted .....")
56
57
58 if __name__ == "__main__":
59 main()