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 10PARENT_DIR = os.path.join(os.path.dirname(__file__), "..") 11DOC_FILE = os.path.join(PARENT_DIR, "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, replacement, text, flags=re.S) 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, stderr=subprocess.STDOUT) 31 out, _ = cmd.communicate() 32 out = out.decode(sys.stdout.encoding) 33 return out 34 35 36def 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 51def 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 57help_text = get_help_text() 58validate(help_text, 100) 59 60with open(DOC_FILE) as f: 61 contents = f.read() 62 63contents = substitute(contents, "FORMAT_HELP", help_text) 64 65with open(DOC_FILE, "wb") as output: 66 output.write(contents.encode()) 67