-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_cli_docs.py
More file actions
283 lines (229 loc) · 8.91 KB
/
Copy pathgenerate_cli_docs.py
File metadata and controls
283 lines (229 loc) · 8.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#!/usr/bin/env python3
"""Generate CLI reference documentation from the Typer app.
Introspects the Click command tree and writes markdown files to site-docs/cli/.
Run from repo root: python scripts/generate_cli_docs.py
Output structure:
site-docs/cli/index.md — overview with global options and command list
site-docs/cli/<group>.md — one page per command group (draft, project, etc.)
site-docs/cli/root-commands.md — top-level commands (version, init, trigger, etc.)
"""
from __future__ import annotations
import sys
import textwrap
from pathlib import Path
# Ensure src/ is importable
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
import click
import typer.core
import typer.main
from social_hook.cli import app
from social_hook.constants import PROJECT_SLUG
# Typer >=0.26 uses its own param classes that don't inherit from click.*
_argument_types = (click.Argument, typer.core.TyperArgument)
_option_types = (click.Option, typer.core.TyperOption)
DOCS_DIR = Path(__file__).resolve().parent.parent / "site-docs" / "cli"
# Commands to exclude from docs (internal hooks)
HIDDEN_COMMANDS = {"commit-hook", "git-hook", "narrative-capture"}
def get_click_app() -> click.Group:
return typer.main.get_command(app)
def format_type(param: click.Parameter) -> str:
"""Human-readable type string."""
type_name = getattr(param.type, "name", str(param.type))
mapping = {
"TEXT": "string",
"INT": "integer",
"FLOAT": "number",
"BOOL": "boolean",
"PATH": "path",
"FILENAME": "path",
}
return mapping.get(type_name.upper(), type_name.lower())
def format_default(param: click.Parameter) -> str:
"""Format default value for display."""
if param.default is None:
return ""
if isinstance(param.default, bool):
return str(param.default).lower()
if param.default == ():
return ""
return str(param.default)
def option_flags(param: click.Option) -> str:
"""Format option flags like --name, -n."""
parts = []
for opt in param.opts:
parts.append(f"`{opt}`")
for opt in param.secondary_opts:
parts.append(f"`{opt}`")
return ", ".join(parts)
def render_params(cmd: click.Command) -> str:
"""Render arguments and options as markdown tables."""
lines = []
skip = {"install_completion", "show_completion", "help", "ctx"}
# Arguments
args = [p for p in cmd.params if isinstance(p, _argument_types)]
if args:
lines.append("**Arguments:**")
lines.append("")
lines.append("| Name | Required | Description |")
lines.append("|------|----------|-------------|")
for arg in args:
name = arg.name or ""
req = "yes" if arg.required else "no"
help_text = getattr(arg, "help", "") or ""
# Click arguments don't always have help; try type info
if not help_text:
help_text = f"({format_type(arg)})"
lines.append(f"| `{name}` | {req} | {help_text} |")
lines.append("")
# Options
opts = [p for p in cmd.params if isinstance(p, _option_types) and p.name not in skip]
if opts:
lines.append("**Options:**")
lines.append("")
lines.append("| Flag | Type | Default | Description |")
lines.append("|------|------|---------|-------------|")
for opt in opts:
flags = option_flags(opt)
typ = format_type(opt)
default = format_default(opt)
help_text = opt.help or ""
lines.append(f"| {flags} | {typ} | {default} | {help_text} |")
lines.append("")
return "\n".join(lines)
def render_command(cmd: click.Command, name: str, prefix: str) -> str:
"""Render a single command as markdown."""
lines = []
full_name = f"{prefix} {name}"
lines.append(f"### `{full_name}`")
lines.append("")
if cmd.help:
# First line is summary, rest is detail
help_lines = cmd.help.strip().split("\n")
summary = help_lines[0].strip()
lines.append(summary)
lines.append("")
if len(help_lines) > 1:
detail = textwrap.dedent("\n".join(help_lines[1:])).strip()
if detail:
lines.append(detail)
lines.append("")
params = render_params(cmd)
if params:
lines.append(params)
return "\n".join(lines)
def render_group_page(group: click.Group, group_name: str) -> str:
"""Render a command group as a full markdown page."""
lines = []
prefix = f"{PROJECT_SLUG} {group_name}"
lines.append(f"# {PROJECT_SLUG} {group_name}")
lines.append("")
if group.help:
lines.append(group.help.strip())
lines.append("")
# If the group itself is invokable (invoke_without_command)
group_params = render_params(group)
if group_params:
lines.append("**Group options:**")
lines.append("")
lines.append(group_params)
# Subcommands
if hasattr(group, "commands") and group.commands:
lines.append("---")
lines.append("")
for cmd_name in sorted(group.commands):
cmd = group.commands[cmd_name]
if getattr(cmd, "hidden", False):
continue
lines.append(render_command(cmd, cmd_name, prefix))
lines.append("---")
lines.append("")
return "\n".join(lines)
def render_root_commands(click_app: click.Group) -> str:
"""Render top-level (non-group) commands."""
lines = []
lines.append(f"# {PROJECT_SLUG} commands")
lines.append("")
lines.append("Top-level commands that are not part of a command group.")
lines.append("")
for cmd_name in sorted(click_app.commands):
cmd = click_app.commands[cmd_name]
if getattr(cmd, "hidden", False) or cmd_name in HIDDEN_COMMANDS:
continue
# Skip groups — they get their own pages
if hasattr(cmd, "commands") and cmd.commands:
continue
lines.append(render_command(cmd, cmd_name, PROJECT_SLUG))
lines.append("---")
lines.append("")
return "\n".join(lines)
def render_index(click_app: click.Group, groups: list[str]) -> str:
"""Render the index page with global options and navigation."""
lines = []
lines.append(f"# {PROJECT_SLUG} CLI Reference")
lines.append("")
lines.append(click_app.help or "")
lines.append("")
# Global options
lines.append("## Global Options")
lines.append("")
lines.append("These options can be placed before any command.")
lines.append("")
lines.append(render_params(click_app))
# Command groups
lines.append("## Command Groups")
lines.append("")
lines.append("| Group | Description |")
lines.append("|-------|-------------|")
for name in sorted(groups):
cmd = click_app.commands[name]
help_text = cmd.help.split("\n")[0].strip() if cmd.help else ""
lines.append(f"| [`{name}`]({name}.md) | {help_text} |")
lines.append("")
# Root commands
root_cmds = []
for cmd_name in sorted(click_app.commands):
cmd = click_app.commands[cmd_name]
if getattr(cmd, "hidden", False) or cmd_name in HIDDEN_COMMANDS:
continue
if hasattr(cmd, "commands") and cmd.commands:
continue
root_cmds.append((cmd_name, cmd))
if root_cmds:
lines.append("## Commands")
lines.append("")
lines.append("| Command | Description |")
lines.append("|---------|-------------|")
for cmd_name, cmd in root_cmds:
help_text = cmd.help.split("\n")[0].strip() if cmd.help else ""
lines.append(
f"| [`{cmd_name}`](root-commands.md#{PROJECT_SLUG}-{cmd_name}) | {help_text} |"
)
lines.append("")
return "\n".join(lines)
def main() -> None:
click_app = get_click_app()
DOCS_DIR.mkdir(parents=True, exist_ok=True)
groups = []
for cmd_name in sorted(click_app.commands):
cmd = click_app.commands[cmd_name]
if getattr(cmd, "hidden", False) or cmd_name in HIDDEN_COMMANDS:
continue
if hasattr(cmd, "commands") and cmd.commands:
groups.append(cmd_name)
page = render_group_page(cmd, cmd_name)
out_path = DOCS_DIR / f"{cmd_name}.md"
out_path.write_text(page)
print(f" wrote {out_path.relative_to(DOCS_DIR.parent.parent)}")
# Root commands page
root_page = render_root_commands(click_app)
root_path = DOCS_DIR / "root-commands.md"
root_path.write_text(root_page)
print(f" wrote {root_path.relative_to(DOCS_DIR.parent.parent)}")
# Index
index_page = render_index(click_app, groups)
index_path = DOCS_DIR / "index.md"
index_path.write_text(index_page)
print(f" wrote {index_path.relative_to(DOCS_DIR.parent.parent)}")
print(f"\nGenerated {len(groups) + 2} files in site-docs/cli/")
if __name__ == "__main__":
main()