Debian Codegraph @

clang/docs/tools/dump_format_help.py

raw
1 #!/usr/bin/env python3
2 # A tool to parse the output of `clang-format --help` and update the
3 # documentation in ../ClangFormat.rst automatically.
4
5 import os
6 import re
7 import subprocess
8 import sys
9
10 PARENT_DIR = os.path.join(os.path.dirname(__file__), "..")
11 DOC_FILE = os.path.join(PARENT_DIR, "ClangFormat.rst")
12
13
14 def substitute(text, tag, contents):
15 replacement = "\n.. START_%s\n\n%s\n\n.. END_%s\n" % (tag, contents, tag)
16 pattern = r"\n\.\. START_%s\n.*\n\.\. END_%s\n" % (tag, tag)
17 return re.sub(pattern, replacement, text, flags=re.S)
18
19
20 def indent(text, columns, indent_first_line=True):
21 indent_str = " " * columns
22 s = re.sub(r"\n([^\n])", "\n" + indent_str + "\\1", text, flags=re.S)
23 if not indent_first_line or s.startswith("\n"):
24 return s
25 return indent_str + s
26
27
28 def get_help_output():
29 args = ["clang-format", "--help"]
30 cmd = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
31 out, _ = cmd.communicate()
32 out = out.decode(sys.stdout.encoding)
33 return out
34
35
36 def get_help_text():
37 out = get_help_output()
38 out = re.sub(r" clang-format\.exe ", " clang-format ", out)
39
40 out = (
41 """.. code-block:: console
42
43 $ clang-format --help
44 """
45 + out
46 )
47 out = indent(out, 2, indent_first_line=False)
48 return out
49
50
51 def validate(text, columns):
52 for line in text.splitlines():
53 if len(line) > columns:
54 print("warning: line too long:\n", line, file=sys.stderr)
55
56
57 help_text = get_help_text()
58 validate(help_text, 100)
59
60 with open(DOC_FILE) as f:
61 contents = f.read()
62
63 contents = substitute(contents, "FORMAT_HELP", help_text)
64
65 with open(DOC_FILE, "wb") as output:
66 output.write(contents.encode())