| 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.INTERRUPT: "Interrupted.", |
| 72 |
} |
| 73 |
"""What each code means, in a sentence. A copy of what the enum's own docstrings |
| 74 |
say, because a docstring on an enum member is not there at run time; the test |
| 75 |
is what fails when a new code arrives without one.""" |
| 76 |
|
| 77 |
|
| 78 |
def build_reference() -> str: |
| 79 |
"""The whole page, as the bytes the file holds.""" |
| 80 |
command = bare_command() |
| 81 |
document = command_document(command) |
| 82 |
blocks = [ |
| 83 |
BANNER, |
| 84 |
f"# {command.name}", |
| 85 |
inspect.cleandoc(command.help or ""), |
| 86 |
PREAMBLE, |
| 87 |
"## Usage", |
| 88 |
_usage(command), |
| 89 |
"## Arguments", |
| 90 |
_arguments_table(document["arguments"]), |
| 91 |
"## Options", |
| 92 |
OPTIONS_NOTE, |
| 93 |
_options_table(document["options"]), |
| 94 |
ADAPTER_NOTE, |
| 95 |
"## Formats", |
| 96 |
FORMATS_NOTE, |
| 97 |
_formats_table(), |
| 98 |
"## Exit codes", |
| 99 |
_exit_codes_table(), |
| 100 |
] |
| 101 |
return "\n\n".join(blocks) + "\n" |
| 102 |
|
| 103 |
|
| 104 |
def _usage(command: click.Command) -> str: |
| 105 |
context = click.Context(command, info_name=command.name) |
| 106 |
pieces = command.collect_usage_pieces(context) |
| 107 |
return _fence(" ".join([str(command.name), *pieces])) |
| 108 |
|
| 109 |
|
| 110 |
def _arguments_table(arguments: Sequence[dict[str, Any]]) -> str: |
| 111 |
return _table( |
| 112 |
["Argument", "Type", "Accepts"], |
| 113 |
[ |
| 114 |
[ |
| 115 |
_code(str(argument["metavar"])), |
| 116 |
str(argument["type"]), |
| 117 |
_accepts(int(argument["nargs"]), bool(argument["required"])), |
| 118 |
] |
| 119 |
for argument in arguments |
| 120 |
], |
| 121 |
) |
| 122 |
|
| 123 |
|
| 124 |
def _options_table(options: Sequence[dict[str, Any]]) -> str: |
| 125 |
return _table( |
| 126 |
["Option", "Type", "Values", "Default", "Env var", "Description"], |
| 127 |
[ |
| 128 |
[ |
| 129 |
", ".join(_code(decl) for decl in option["decls"]), |
| 130 |
str(option["type"]), |
| 131 |
_values(option), |
| 132 |
_default(option), |
| 133 |
_envvar(option), |
| 134 |
_cell(option["help"] or ""), |
| 135 |
] |
| 136 |
for option in options |
| 137 |
], |
| 138 |
) |
| 139 |
|
| 140 |
|
| 141 |
def _values(option: dict[str, Any]) -> str: |
| 142 |
"""What may be written after the option: its choices, or its placeholder.""" |
| 143 |
choices = None if option["name"] in INSTALLATION_DEPENDENT else option["choices"] |
| 144 |
if choices: |
| 145 |
return ", ".join(_code(str(choice)) for choice in choices) |
| 146 |
return _code(str(option["metavar"])) if option["metavar"] else "" |
| 147 |
|
| 148 |
|
| 149 |
def _default(option: dict[str, Any]) -> str: |
| 150 |
"""What the command uses when the option is absent. |
| 151 |
|
| 152 |
Empty for a flag, which the note above the table covers once rather than |
| 153 |
20 times. |
| 154 |
""" |
| 155 |
default = option["default"] |
| 156 |
if option["is_flag"] or default is None: |
| 157 |
return "" |
| 158 |
return _code(str(default)) |
| 159 |
|
| 160 |
|
| 161 |
def _envvar(option: dict[str, Any]) -> str: |
| 162 |
envvar = option["envvar"] |
| 163 |
if envvar is None: |
| 164 |
return "" |
| 165 |
names = [envvar] if isinstance(envvar, str) else envvar |
| 166 |
return ", ".join(_code(str(name)) for name in names) |
| 167 |
|
| 168 |
|
| 169 |
def _accepts(nargs: int, required: bool) -> str: |
| 170 |
if nargs == -1: |
| 171 |
return "one or more" if required else "zero or more" |
| 172 |
return "one" if nargs == 1 else str(nargs) |
| 173 |
|
| 174 |
|
| 175 |
def _formats_table() -> str: |
| 176 |
return _table( |
| 177 |
["Format", "Kind", "Suffix", "Holds several result sets"], |
| 178 |
[ |
| 179 |
[ |
| 180 |
_code(name), |
| 181 |
_kind(name), |
| 182 |
_code(output.suffix(name)) if output.suffix(name) else "", |
| 183 |
"yes" if output.holds_many(name) else "no", |
| 184 |
] |
| 185 |
for name in output.format_names() |
| 186 |
], |
| 187 |
) |
| 188 |
|
| 189 |
|
| 190 |
def _kind(format_name: str) -> str: |
| 191 |
if format_name == output.NONE: |
| 192 |
return "writes nothing" |
| 193 |
return "text layout" if output.is_layout(format_name) else "file" |
| 194 |
|
| 195 |
|
| 196 |
def _exit_codes_table() -> str: |
| 197 |
missing = [code for code in ExitCode if code not in EXIT_CODES] |
| 198 |
if missing: |
| 199 |
raise ValueError( |
| 200 |
f"EXIT_CODES does not describe: {', '.join(code.name for code in missing)}" |
| 201 |
) |
| 202 |
return _table( |
| 203 |
["Code", "Meaning"], |
| 204 |
[[_code(str(code.value)), EXIT_CODES[code]] for code in ExitCode], |
| 205 |
) |
| 206 |
|
| 207 |
|
| 208 |
def _table(headers: Sequence[str], rows: Sequence[Sequence[str]]) -> str: |
| 209 |
lines = [ |
| 210 |
"| " + " | ".join(headers) + " |", |
| 211 |
"| " + " | ".join("---" for _ in headers) + " |", |
| 212 |
*("| " + " | ".join(row) + " |" for row in rows), |
| 213 |
] |
| 214 |
return "\n".join(lines) |
| 215 |
|
| 216 |
|
| 217 |
def _fence(text: str) -> str: |
| 218 |
return f"```\n{text}\n```" |
| 219 |
|
| 220 |
|
| 221 |
def _code(text: str) -> str: |
| 222 |
"""A code span in a table cell, so the pipe in `all|last|N` is escaped.""" |
| 223 |
escaped = text.replace("|", r"\|") |
| 224 |
return f"`{escaped}`" |
| 225 |
|
| 226 |
|
| 227 |
def _cell(text: str) -> str: |
| 228 |
"""One paragraph of help, as a table cell: no newlines, no stray pipes.""" |
| 229 |
return " ".join(text.split()).replace("|", r"\|") |
| 230 |
|
| 231 |
|
| 232 |
def main() -> None: |
| 233 |
REFERENCE_PATH.parent.mkdir(parents=True, exist_ok=True) |
| 234 |
REFERENCE_PATH.write_text(build_reference(), encoding="utf-8", newline="\n") |
| 235 |
print(f"wrote {REFERENCE_PATH}") |
| 236 |
|
| 237 |
|
| 238 |
if __name__ == "__main__": |
| 239 |
main() |