Debian Codegraph @

tools/regenerate_docs.py

raw
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: Apache-2.0
3 # Copyright 2018 The Meson development team
4
5 '''
6 Regenerate markdown docs by using `meson.py` from the root dir
7 '''
8
9 import argparse
10 import os
11 import re
12 import subprocess
13 import sys
14 import textwrap
15 import json
16 import typing as T
17 from pathlib import Path
18 from urllib.request import urlopen
19
20 PathLike = T.Union[Path,str]
21
22 def _get_meson_output(root_dir: Path, args: T.List) -> str:
23 env = os.environ.copy()
24 env['COLUMNS'] = '80'
25 return subprocess.run([str(sys.executable), str(root_dir/'meson.py')] + args, check=True, capture_output=True, text=True, env=env).stdout.strip()
26
27 def get_commands(help_output: str) -> T.Set[str]:
28 # Python's argument parser might put the command list to its own line. Or it might not.
29 assert(help_output.startswith('usage: '))
30 lines = help_output.split('\n')
31 line1 = lines[0]
32 line2 = lines[1]
33 if '{' in line1:
34 cmndline = line1
35 else:
36 assert('{' in line2)
37 cmndline = line2
38 cmndstr = cmndline.split('{')[1]
39 assert('}' in cmndstr)
40 help_commands = set(cmndstr.split('}')[0].split(','))
41 assert(len(help_commands) > 0)
42 return {c.strip() for c in help_commands}
43
44 def get_commands_data(root_dir: Path) -> T.Dict[str, T.Any]:
45 usage_start_pattern = re.compile(r'^usage: ', re.MULTILINE)
46 positional_start_pattern = re.compile(r'^positional arguments:[\t ]*[\r\n]+', re.MULTILINE)
47 options_start_pattern = re.compile(r'^(optional arguments|options):[\t ]*[\r\n]+', re.MULTILINE)
48 commands_start_pattern = re.compile(r'^[A-Za-z ]*[Cc]ommands:[\t ]*[\r\n]+', re.MULTILINE)
49
50 def get_next_start(iterators: T.Sequence[T.Any], end: T.Optional[int]) -> int:
51 return next((i.start() for i in iterators if i), end)
52
53 def normalize_text(text: str) -> str:
54 # clean up formatting
55 out = text
56 out = re.sub(r'\r\n', r'\r', out, flags=re.MULTILINE) # replace newlines with a linux EOL
57 out = re.sub(r'^ +$', '', out, flags=re.MULTILINE) # remove trailing whitespace
58 out = re.sub(r'(?:^\n+|\n+$)', '', out) # remove trailing empty lines
59 return out
60
61 def parse_cmd(cmd: str) -> T.Dict[str, str]:
62 cmd_len = len(cmd)
63 usage = usage_start_pattern.search(cmd)
64 positionals = positional_start_pattern.search(cmd)
65 options = options_start_pattern.search(cmd)
66 commands = commands_start_pattern.search(cmd)
67
68 arguments_start = get_next_start([positionals, options, commands], None)
69 assert arguments_start
70
71 # replace `usage:` with `$` and dedent
72 dedent_size = (usage.end() - usage.start()) - len('$ ')
73 usage_text = textwrap.dedent(f'{dedent_size * " "}$ {normalize_text(cmd[usage.end():arguments_start])}')
74
75 return {
76 'usage': usage_text,
77 'arguments': normalize_text(cmd[arguments_start:cmd_len]),
78 }
79
80 def clean_dir_arguments(text: str) -> str:
81 # Remove platform specific defaults
82 args = [
83 'prefix',
84 'bindir',
85 'datadir',
86 'includedir',
87 'infodir',
88 'libdir',
89 'libexecdir',
90 'localedir',
91 'localstatedir',
92 'mandir',
93 'sbindir',
94 'sharedstatedir',
95 'sysconfdir'
96 ]
97 out = text
98 for a in args:
99 out = re.sub(r'(--' + a + r' .+?)\s+\(default:.+?\)(\.)?', r'\1\2', out, flags=re.MULTILINE|re.DOTALL)
100 return out
101
102 output = _get_meson_output(root_dir, ['--help'])
103 commands = get_commands(output)
104 commands.remove('help')
105
106 cmd_data = dict()
107
108 for cmd in commands:
109 cmd_output = _get_meson_output(root_dir, [cmd, '--help'])
110 cmd_data[cmd] = parse_cmd(cmd_output)
111 if cmd in ['setup', 'configure']:
112 cmd_data[cmd]['arguments'] = clean_dir_arguments(cmd_data[cmd]['arguments'])
113
114 return cmd_data
115
116 def generate_hotdoc_includes(root_dir: Path, output_dir: Path) -> None:
117 cmd_data = get_commands_data(root_dir)
118
119 for cmd, parsed in cmd_data.items():
120 for typ in parsed.keys():
121 with open(output_dir / (cmd+'_'+typ+'.inc'), 'w', encoding='utf-8') as f:
122 f.write(parsed[typ])
123
124 def generate_wrapdb_table(output_dir: Path) -> None:
125 url = urlopen('https://wrapdb.mesonbuild.com/v2/releases.json')
126 releases = json.loads(url.read().decode())
127 with open(output_dir / 'wrapdb-table.md', 'w', encoding='utf-8') as f:
128 f.write('| Project | Versions | Provided dependencies | Provided programs |\n')
129 f.write('| ------- | -------- | --------------------- | ----------------- |\n')
130 for name, info in releases.items():
131 versions = []
132 added_tags = set()
133 for v in info['versions']:
134 tag, build = v.rsplit('-', 1)
135 if tag not in added_tags:
136 added_tags.add(tag)
137 versions.append(f'[{v}](https://wrapdb.mesonbuild.com/v2/{name}_{v}/{name}.wrap)')
138 # Highlight latest version.
139 versions_str = f'<big>**{versions[0]}**</big><br/>' + ', '.join(versions[1:])
140 dependency_names = info.get('dependency_names', [])
141 dependency_names_str = ', '.join(dependency_names)
142 program_names = info.get('program_names', [])
143 program_names_str = ', '.join(program_names)
144 f.write(f'| {name} | {versions_str} | {dependency_names_str} | {program_names_str} |\n')
145
146 def regenerate_docs(output_dir: PathLike,
147 dummy_output_file: T.Optional[PathLike]) -> None:
148 if not output_dir:
149 raise ValueError(f'Output directory value is not set')
150
151 output_dir = Path(output_dir).resolve()
152 output_dir.mkdir(parents=True, exist_ok=True)
153
154 root_dir = Path(__file__).resolve().parent.parent
155
156 generate_hotdoc_includes(root_dir, output_dir)
157 generate_wrapdb_table(output_dir)
158
159 if dummy_output_file:
160 with open(output_dir/dummy_output_file, 'w', encoding='utf-8') as f:
161 f.write('dummy file for custom_target output')
162
163 if __name__ == '__main__':
164 parser = argparse.ArgumentParser(description='Generate meson docs')
165 parser.add_argument('--output-dir', required=True)
166 parser.add_argument('--dummy-output-file', type=str)
167
168 args = parser.parse_args()
169
170 regenerate_docs(output_dir=args.output_dir,
171 dummy_output_file=args.dummy_output_file)