xref: /openbsd-src/gnu/llvm/clang/docs/tools/dump_format_help.py (revision 12c855180aad702bbcca06e0398d774beeafb155)
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
5import os
6import re
7import subprocess
8import sys
9
10CLANG_DIR = os.path.join(os.path.dirname(__file__), '../..')
11DOC_FILE = os.path.join(CLANG_DIR, 'docs/ClangFormat.rst')
12
13
14def 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, '%s', text, flags=re.S) % replacement
18
19
20def 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
28def get_help_output():
29    args = ["clang-format", "--help"]
30    cmd = subprocess.Popen(args, stdout=subprocess.PIPE,
31                           stderr=subprocess.STDOUT)
32    out, _ = cmd.communicate()
33    out = out.decode(sys.stdout.encoding)
34    return out
35
36
37def get_help_text():
38    out = get_help_output()
39    out = re.sub(r' clang-format\.exe ', ' clang-format ', out)
40
41    out = '''.. code-block:: console
42
43$ clang-format -help
44''' + out
45    out = indent(out, 2, indent_first_line=False)
46    return out
47
48
49def validate(text, columns):
50    for line in text.splitlines():
51        if len(line) > columns:
52            print('warning: line too long:\n', line, file=sys.stderr)
53
54
55help_text = get_help_text()
56validate(help_text, 95)
57
58with open(DOC_FILE) as f:
59    contents = f.read()
60
61contents = substitute(contents, 'FORMAT_HELP', help_text)
62
63with open(DOC_FILE, 'wb') as output:
64    output.write(contents.encode())
65