Debian Codegraph @

packaging/cli-doc/build.py

raw ◀ ▶
1 Debian patch touch this file
•1 #!/usr/bin/env python3
2 # PYTHON_ARGCOMPLETE_OK
3 """Build documentation for ansible-core CLI programs."""
4
5 from __future__ import annotations
6
7 import argparse
8 import dataclasses
9 import importlib
10 import inspect
11 import io
12 import itertools
13 import json
14 import pathlib
15 import sys
16 import typing as t
17 import warnings
18
19 import jinja2
20
21 if t.TYPE_CHECKING:
22 from ansible.cli import CLI # pragma: nocover
23
24 SCRIPT_DIR = pathlib.Path(__file__).resolve().parent
25 SOURCE_DIR = SCRIPT_DIR.parent.parent
26
27
28 def main() -> None:
29 """Main program entry point."""
30 parser = argparse.ArgumentParser(description=__doc__)
31 subparsers = parser.add_subparsers(required=True, metavar='command')
32
33 man_parser = subparsers.add_parser('man', description=build_man.__doc__, help=build_man.__doc__)
34 man_parser.add_argument('--output-dir', required=True, type=pathlib.Path, metavar='DIR', help='output directory')
35 man_parser.add_argument('--template-file', default=SCRIPT_DIR / 'man.j2', type=pathlib.Path, metavar='FILE', help='template file')
36 man_parser.set_defaults(func=build_man)
37
38 rst_parser = subparsers.add_parser('rst', description=build_rst.__doc__, help=build_rst.__doc__)
39 rst_parser.add_argument('--output-dir', required=True, type=pathlib.Path, metavar='DIR', help='output directory')
40 rst_parser.add_argument('--template-file', default=SCRIPT_DIR / 'rst.j2', type=pathlib.Path, metavar='FILE', help='template file')
41 rst_parser.set_defaults(func=build_rst)
42
43 json_parser = subparsers.add_parser('json', description=build_json.__doc__, help=build_json.__doc__)
44 json_parser.add_argument('--output-file', required=True, type=pathlib.Path, metavar='FILE', help='output file')
45 json_parser.set_defaults(func=build_json)
46
47 try:
48 # noinspection PyUnresolvedReferences
49 import argcomplete
50 except ImportError:
51 pass
52 else:
53 argcomplete.autocomplete(parser)
54
55 args = parser.parse_args()
56 kwargs = {name: getattr(args, name) for name in inspect.signature(args.func).parameters}
57
58 sys.path.insert(0, str(SOURCE_DIR / 'lib'))
59
60 args.func(**kwargs)
61
62
63 def build_man(output_dir: pathlib.Path, template_file: pathlib.Path) -> None:
64 """Build man pages for ansible-core CLI programs."""
65 if not template_file.resolve().is_relative_to(SCRIPT_DIR):
66 warnings.warn("Custom templates are intended for debugging purposes only. The data model may change in future releases without notice.")
67
68 import docutils.core
69 import docutils.writers.manpage
70
71 output_dir.mkdir(exist_ok=True, parents=True)
72
73 for cli_name, source in generate_rst(template_file).items():
74 with io.StringIO(source) as source_file:
75 docutils.core.publish_file(
76 source=source_file,
77 destination_path=output_dir / f'{cli_name}.1',
78 writer=docutils.writers.manpage.Writer(),
79 )
80
81
82 def build_rst(output_dir: pathlib.Path, template_file: pathlib.Path) -> None:
83 """Build RST documentation for ansible-core CLI programs."""
84 if not template_file.resolve().is_relative_to(SCRIPT_DIR):
85 warnings.warn("Custom templates are intended for debugging purposes only. The data model may change in future releases without notice.")
86
87 output_dir.mkdir(exist_ok=True, parents=True)
88
89 for cli_name, source in generate_rst(template_file).items():
90 (output_dir / f'{cli_name}.rst').write_text(source)
91
92
93 def build_json(output_file: pathlib.Path) -> None:
94 """Build JSON documentation for ansible-core CLI programs."""
95 warnings.warn("JSON output is intended for debugging purposes only. The data model may change in future releases without notice.")
96
97 output_file.parent.mkdir(exist_ok=True, parents=True)
98 output_file.write_text(json.dumps(collect_programs(), indent=4))
99
100
101 def generate_rst(template_file: pathlib.Path) -> dict[str, str]:
102 """Generate RST pages using the provided template."""
103 results: dict[str, str] = {}
104
105 for cli_name, template_vars in collect_programs().items():
106 env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_file.parent))
107 template = env.get_template(template_file.name)
108 results[cli_name] = template.render(template_vars)
109
110 return results
111
112
113 def collect_programs() -> dict[str, dict[str, t.Any]]:
114 """Return information about CLI programs."""
115 programs: list[tuple[str, dict[str, t.Any]]] = []
116 cli_bin_name_list: list[str] = []
117
118 for source_file in (SOURCE_DIR / 'lib/ansible/cli').glob('*.py'):
119 if not source_file.name.startswith('_'):
120 programs.append(generate_options_docs(source_file, cli_bin_name_list))
121
122 return dict(programs)
123
124
125 def generate_options_docs(source_file: pathlib.Path, cli_bin_name_list: list[str]) -> tuple[str, dict[str, t.Any]]:
126 """Generate doc structure from CLI module options."""
127 import ansible.release
128
129 if str(source_file).endswith('/lib/ansible/cli/adhoc.py'):
130 cli_name = 'ansible'
131 cli_class_name = 'AdHocCLI'
132 cli_module_fqn = 'ansible.cli.adhoc'
133 else:
134 cli_module_name = source_file.with_suffix('').name
135 cli_name = f'ansible-{cli_module_name}'
136 cli_class_name = f'{cli_module_name.capitalize()}CLI'
137 cli_module_fqn = f'ansible.cli.{cli_module_name}'
138
139 cli_bin_name_list.append(cli_name)
140
141 cli_module = importlib.import_module(cli_module_fqn)
142 cli_class: type[CLI] = getattr(cli_module, cli_class_name)
143
144 cli = cli_class([cli_name])
145 cli.init_parser()
146
147 parser: argparse.ArgumentParser = cli.parser
148 long_desc = cli.__doc__
149 arguments: dict[str, str] | None = getattr(cli, 'ARGUMENTS', None)
150
151 action_docs = get_action_docs(parser)
152 option_names: tuple[str, ...] = tuple(itertools.chain.from_iterable(opt.options for opt in action_docs))
153 actions: dict[str, dict[str, t.Any]] = {}
154
155 content_depth = populate_subparser_actions(parser, option_names, actions)
156
157 docs = dict(
158 version=ansible.release.__version__,
159 source=str(source_file.relative_to(SOURCE_DIR)),
160 cli_name=cli_name,
161 usage=parser.format_usage(),
162 short_desc=parser.description,
163 long_desc=trim_docstring(long_desc),
164 actions=actions,
165 options=[item.__dict__ for item in action_docs],
166 arguments=arguments,
167 option_names=option_names,
168 cli_bin_name_list=cli_bin_name_list,
169 content_depth=content_depth,
170 inventory='-i' in option_names,
171 library='-M' in option_names,
172 )
173
174 return cli_name, docs
175
176
177 def populate_subparser_actions(parser: argparse.ArgumentParser, shared_option_names: tuple[str, ...], actions: dict[str, dict[str, t.Any]]) -> int:
178 """Generate doc structure from CLI module subparser options."""
179 try:
180 # noinspection PyProtectedMember
181 subparsers: dict[str, argparse.ArgumentParser] = parser._subparsers._group_actions[0].choices # type: ignore
182 except AttributeError:
183 subparsers = {}
184
185 depth = 0
186
187 for subparser_action, subparser in subparsers.items():
188 subparser_option_names: set[str] = set()
189 subparser_action_docs: set[ActionDoc] = set()
190 subparser_actions: dict[str, dict[str, t.Any]] = {}
191
192 for action_doc in get_action_docs(subparser):
193 for option_alias in action_doc.options:
194 if option_alias in shared_option_names:
195 continue
196
197 subparser_option_names.add(option_alias)
198 subparser_action_docs.add(action_doc)
199
200 depth = populate_subparser_actions(subparser, shared_option_names, subparser_actions)
201
202 actions[subparser_action] = dict(
203 option_names=list(subparser_option_names),
204 options=[item.__dict__ for item in subparser_action_docs],
205 actions=subparser_actions,
206 name=subparser_action,
207 desc=trim_docstring(subparser.get_default("func").__doc__),
208 )
209
210 return depth + 1
211
212
213 @dataclasses.dataclass(frozen=True)
214 class ActionDoc:
215 """Documentation for an action."""
216
217 desc: str | None
218 options: tuple[str, ...]
219 arg: str | None
220
221
222 def get_action_docs(parser: argparse.ArgumentParser) -> list[ActionDoc]:
223 """Get action documentation from the given argument parser."""
224 action_docs = []
225
226 # noinspection PyProtectedMember
227 for action in parser._actions:
228 if action.help == argparse.SUPPRESS:
229 continue
230
231 # noinspection PyProtectedMember, PyUnresolvedReferences
232 args = action.dest.upper() if isinstance(action, argparse._StoreAction) else None
233
234 if args or action.option_strings:
235 action_docs.append(
236 ActionDoc(
237 desc=action.help,
238 options=tuple(action.option_strings),
239 arg=args,
240 )
241 )
242
243 return action_docs
244
245
246 def trim_docstring(docstring: str | None) -> str:
247 """Trim and return the given docstring using the implementation from https://peps.python.org/pep-0257/#handling-docstring-indentation."""
248 if not docstring:
249 return '' # pragma: nocover
250
251 # Convert tabs to spaces (following the normal Python rules) and split into a list of lines
252 lines = docstring.expandtabs().splitlines()
253
254 # Determine minimum indentation (first line doesn't count)
255 indent = sys.maxsize
256
257 for line in lines[1:]:
258 stripped = line.lstrip()
259
260 if stripped:
261 indent = min(indent, len(line) - len(stripped))
262
263 # Remove indentation (first line is special)
264 trimmed = [lines[0].strip()]
265
266 if indent < sys.maxsize:
267 for line in lines[1:]:
268 trimmed.append(line[indent:].rstrip())
269
270 # Strip off trailing and leading blank lines
271 while trimmed and not trimmed[-1]:
272 trimmed.pop()
273
274 while trimmed and not trimmed[0]:
275 trimmed.pop(0)
276
277 # Return a single string
278 return '\n'.join(trimmed)
279
280
281 if __name__ == '__main__':
282 main()