Debian Codegraph @

scripts/write_cli_reference.py

raw
1 """Write the CLI reference for hsql into `docs/generated/hsql-reference.md`.
2
3 The command already describes itself twice -- `--help` for a person, `--spec`
4 for a machine -- and neither is a page. This renders the third view from the
5 same source: every option with its type, the values it takes, its default, its
6 environment variable and its help, plus the arguments, the output formats and
7 the exit codes.
8
9 Usage:
10 uv run python scripts/write_cli_reference.py
11
12 Built from `bare_command()`, with no adapter loaded, exactly as
13 `write_config_schema.py` is: the artifact describes the command rather than the
14 machine it was generated on, so it is publishable and reproducible.
15
16 `tests/unit_tests/test_cli_reference.py` is what fails when the file and the
17 generator disagree, which is any change to hsql's options, to what they take,
18 or to the formats and exit codes below.
19 """
20
21 from __future__ import annotations
22
23 import inspect
24 from pathlib import Path
25 from typing import Any, Sequence
26
27 import click
28
29 from harlequin.hsql import output
30 from harlequin.hsql.cli import bare_command
31 from harlequin.hsql.diagnostics import ExitCode
32 from harlequin.hsql.modes.spec import command_document
33
34 REFERENCE_PATH = (
35 Path(__file__).resolve().parents[1] / "docs" / "generated" / "hsql-reference.md"
36 )
37
38 BANNER = "<!-- Generated by scripts/write_cli_reference.py. Do not edit by hand. -->"
39
40 PREAMBLE = """\
41 Generated from the bare `hsql` command, with no adapters loaded. An adapter
42 contributes its own options on top of these: `hsql --help -a NAME` shows one
43 adapter's, and `hsql --spec` reports every installed adapter's as JSON.\
44 """
45
46 OPTIONS_NOTE = "Alphabetical by name. Flags are off by default."
47
48 ADAPTER_NOTE = """\
49 `-a`/`--adapter` names an installed adapter plug-in. `hsql --info` reports
50 adapters installed in your environment.\
51 """
52
53 FORMATS_NOTE = """\
54 `--format` takes one of these names, which affect the layout of data in stdout.
55 Modify output further with options above (e.g., `-t`, `-A`, `--display-rows`).
56 `none` runs the SQL but generates no output. The suffix is what `-o DIRECTORY`
57 names a file with.\
58 """
59
60 INSTALLATION_DEPENDENT = {"adapter"}
61 """Options whose choices are the plug-ins one machine happens to have. The
62 document describes the command, so it names the option and not the answer --
63 the same call the packaged base config schema makes about `adapter`."""
64
65 EXIT_CODES = {
66 ExitCode.OK: "Success.",
67 ExitCode.QUERY: "The database rejected the SQL.",
68 ExitCode.USAGE: "A bad flag, a bad profile, or a config file hsql could not read.",
69 ExitCode.CONNECTION: "hsql could not connect.",
70 ExitCode.TIMEOUT: "`--timeout` ran out, and hsql stopped the run.",
71 ExitCode.CRASH: "hsql hit a bug in itself and wrote a crash report.",
72 ExitCode.INTERRUPT: "Interrupted.",
73 }
74 """What each code means, in a sentence. A copy of what the enum's own docstrings
75 say, because a docstring on an enum member is not there at run time; the test
76 is what fails when a new code arrives without one."""
77
78
79 def build_reference() -> str:
80 """The whole page, as the bytes the file holds."""
81 command = bare_command()
82 document = command_document(command)
83 blocks = [
84 BANNER,
85 f"# {command.name}",
86 inspect.cleandoc(command.help or ""),
87 PREAMBLE,
88 "## Usage",
89 _usage(command),
90 "## Arguments",
91 _arguments_table(document["arguments"]),
92 "## Options",
93 OPTIONS_NOTE,
94 _options_table(document["options"]),
95 ADAPTER_NOTE,
96 "## Formats",
97 FORMATS_NOTE,
98 _formats_table(),
99 "## Exit codes",
100 _exit_codes_table(),
101 ]
102 return "\n\n".join(blocks) + "\n"
103
104
105 def _usage(command: click.Command) -> str:
106 context = click.Context(command, info_name=command.name)
107 pieces = command.collect_usage_pieces(context)
108 return _fence(" ".join([str(command.name), *pieces]))
109
110
111 def _arguments_table(arguments: Sequence[dict[str, Any]]) -> str:
112 return _table(
113 ["Argument", "Type", "Accepts"],
114 [
115 [
116 _code(str(argument["metavar"])),
117 str(argument["type"]),
118 _accepts(int(argument["nargs"]), bool(argument["required"])),
119 ]
120 for argument in arguments
121 ],
122 )
123
124
125 def _options_table(options: Sequence[dict[str, Any]]) -> str:
126 return _table(
127 ["Option", "Type", "Values", "Default", "Env var", "Description"],
128 [
129 [
130 ", ".join(_code(decl) for decl in option["decls"]),
131 str(option["type"]),
132 _values(option),
133 _default(option),
134 _envvar(option),
135 _cell(option["help"] or ""),
136 ]
137 for option in options
138 ],
139 )
140
141
142 def _values(option: dict[str, Any]) -> str:
143 """What may be written after the option: its choices, or its placeholder."""
144 choices = None if option["name"] in INSTALLATION_DEPENDENT else option["choices"]
145 if choices:
146 return ", ".join(_code(str(choice)) for choice in choices)
147 return _code(str(option["metavar"])) if option["metavar"] else ""
148
149
150 def _default(option: dict[str, Any]) -> str:
151 """What the command uses when the option is absent.
152
153 Empty for a flag, which the note above the table covers once rather than
154 20 times.
155 """
156 default = option["default"]
157 if option["is_flag"] or default is None:
158 return ""
159 return _code(str(default))
160
161
162 def _envvar(option: dict[str, Any]) -> str:
163 envvar = option["envvar"]
164 if envvar is None:
165 return ""
166 names = [envvar] if isinstance(envvar, str) else envvar
167 return ", ".join(_code(str(name)) for name in names)
168
169
170 def _accepts(nargs: int, required: bool) -> str:
171 if nargs == -1:
172 return "one or more" if required else "zero or more"
173 return "one" if nargs == 1 else str(nargs)
174
175
176 def _formats_table() -> str:
177 return _table(
178 ["Format", "Kind", "Suffix", "Holds several result sets"],
179 [
180 [
181 _code(name),
182 _kind(name),
183 _code(output.suffix(name)) if output.suffix(name) else "",
184 "yes" if output.holds_many(name) else "no",
185 ]
186 for name in output.format_names()
187 ],
188 )
189
190
191 def _kind(format_name: str) -> str:
192 if format_name == output.NONE:
193 return "writes nothing"
194 return "text layout" if output.is_layout(format_name) else "file"
195
196
197 def _exit_codes_table() -> str:
198 missing = [code for code in ExitCode if code not in EXIT_CODES]
199 if missing:
200 raise ValueError(
201 f"EXIT_CODES does not describe: {', '.join(code.name for code in missing)}"
202 )
203 return _table(
204 ["Code", "Meaning"],
205 [[_code(str(code.value)), EXIT_CODES[code]] for code in ExitCode],
206 )
207
208
209 def _table(headers: Sequence[str], rows: Sequence[Sequence[str]]) -> str:
210 lines = [
211 "| " + " | ".join(headers) + " |",
212 "| " + " | ".join("---" for _ in headers) + " |",
213 *("| " + " | ".join(row) + " |" for row in rows),
214 ]
215 return "\n".join(lines)
216
217
218 def _fence(text: str) -> str:
219 return f"```\n{text}\n```"
220
221
222 def _code(text: str) -> str:
223 """A code span in a table cell, so the pipe in `all|last|N` is escaped."""
224 escaped = text.replace("|", r"\|")
225 return f"`{escaped}`"
226
227
228 def _cell(text: str) -> str:
229 """One paragraph of help, as a table cell: no newlines, no stray pipes."""
230 return " ".join(text.split()).replace("|", r"\|")
231
232
233 def main() -> None:
234 REFERENCE_PATH.parent.mkdir(parents=True, exist_ok=True)
235 REFERENCE_PATH.write_text(build_reference(), encoding="utf-8", newline="\n")
236 print(f"wrote {REFERENCE_PATH}")
237
238
239 if __name__ == "__main__":
240 main()