-
-
Notifications
You must be signed in to change notification settings - Fork 972
Expand file tree
/
Copy pathcli.py
More file actions
336 lines (298 loc) · 11 KB
/
Copy pathcli.py
File metadata and controls
336 lines (298 loc) · 11 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import importlib.util
import re
import sys
from pathlib import Path
from typing import Any
import click
import typer
import typer.core
from click import Command, Group, Option
from . import __version__
from .core import HAS_RICH, MARKUP_MODE_KEY
default_app_names = ("app", "cli", "main")
default_func_names = ("main", "cli", "app")
app = typer.Typer()
utils_app = typer.Typer(help="Extra utility commands for Typer apps.")
app.add_typer(utils_app, name="utils")
class State:
def __init__(self) -> None:
self.app: str | None = None
self.func: str | None = None
self.file: Path | None = None
self.module: str | None = None
state = State()
def maybe_update_state(ctx: click.Context) -> None:
path_or_module = ctx.params.get("path_or_module")
if path_or_module:
file_path = Path(path_or_module)
if file_path.exists() and file_path.is_file():
state.file = file_path
else:
if not re.fullmatch(r"[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*", path_or_module):
typer.echo(
f"Not a valid file or Python module: {path_or_module}", err=True
)
sys.exit(1)
state.module = path_or_module
app_name = ctx.params.get("app")
if app_name:
state.app = app_name
func_name = ctx.params.get("func")
if func_name:
state.func = func_name
class TyperCLIGroup(typer.core.TyperGroup):
def list_commands(self, ctx: click.Context) -> list[str]:
self.maybe_add_run(ctx)
return super().list_commands(ctx)
def get_command(self, ctx: click.Context, name: str) -> Command | None: # ty: ignore[invalid-method-override]
self.maybe_add_run(ctx)
return super().get_command(ctx, name)
def invoke(self, ctx: click.Context) -> Any:
self.maybe_add_run(ctx)
return super().invoke(ctx)
def maybe_add_run(self, ctx: click.Context) -> None:
maybe_update_state(ctx)
maybe_add_run_to_cli(self)
def get_typer_from_module(module: Any) -> typer.Typer | None:
# Try to get defined app
if state.app:
obj = getattr(module, state.app, None)
if not isinstance(obj, typer.Typer):
typer.echo(f"Not a Typer object: --app {state.app}", err=True)
sys.exit(1)
return obj
# Try to get defined function
if state.func:
func_obj = getattr(module, state.func, None)
if not callable(func_obj):
typer.echo(f"Not a function: --func {state.func}", err=True)
raise typer.Exit(1)
sub_app = typer.Typer()
sub_app.command()(func_obj)
return sub_app
# Iterate and get a default object to use as CLI
local_names = dir(module)
local_names_set = set(local_names)
# Try to get a default Typer app
for name in default_app_names:
if name in local_names_set:
obj = getattr(module, name, None)
if isinstance(obj, typer.Typer):
return obj
# Try to get any Typer app
for name in local_names_set - set(default_app_names):
obj = getattr(module, name)
if isinstance(obj, typer.Typer):
return obj
# Try to get a default function
for func_name in default_func_names:
func_obj = getattr(module, func_name, None)
if callable(func_obj):
sub_app = typer.Typer()
sub_app.command()(func_obj)
return sub_app
# Try to get any func app
for func_name in local_names_set - set(default_func_names):
func_obj = getattr(module, func_name)
if callable(func_obj):
sub_app = typer.Typer()
sub_app.command()(func_obj)
return sub_app
return None
def get_typer_from_state() -> typer.Typer | None:
spec = None
if state.file:
module_name = state.file.name
spec = importlib.util.spec_from_file_location(module_name, str(state.file))
elif state.module:
spec = importlib.util.find_spec(state.module)
if spec is None:
if state.file:
typer.echo(f"Could not import as Python file: {state.file}", err=True)
else:
typer.echo(f"Could not import as Python module: {state.module}", err=True)
sys.exit(1)
assert spec is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module) # type: ignore
obj = get_typer_from_module(module)
return obj
def maybe_add_run_to_cli(cli: click.Group) -> None:
if "run" not in cli.commands:
if state.file or state.module:
obj = get_typer_from_state()
if obj:
obj._add_completion = False
click_obj = typer.main.get_command(obj)
click_obj.name = "run"
if not click_obj.help:
click_obj.help = "Run the provided Typer app."
cli.add_command(click_obj)
def print_version(ctx: click.Context, param: Option, value: bool) -> None:
if not value or ctx.resilient_parsing:
return
typer.echo(f"Typer version: {__version__}")
raise typer.Exit()
@app.callback(cls=TyperCLIGroup, no_args_is_help=True)
def callback(
ctx: typer.Context,
*,
path_or_module: str = typer.Argument(None),
app: str = typer.Option(None, help="The typer app object/variable to use."),
func: str = typer.Option(None, help="The function to convert to Typer."),
version: bool = typer.Option(
False,
"--version",
help="Print version and exit.",
callback=print_version,
),
) -> None:
"""
Run Typer scripts with completion, without having to create a package.
You probably want to install completion for the typer command:
$ typer --install-completion
https://typer.tiangolo.com/
"""
maybe_update_state(ctx)
def get_docs_for_click(
*,
obj: Command,
ctx: typer.Context,
indent: int = 0,
name: str = "",
call_prefix: str = "",
title: str | None = None,
) -> str:
docs = "#" * (1 + indent)
command_name = name or obj.name
if call_prefix:
command_name = f"{call_prefix} {command_name}"
if not title:
title = f"`{command_name}`" if command_name else "CLI"
docs += f" {title}\n\n"
rich_markup_mode = None
if hasattr(ctx, "obj") and isinstance(ctx.obj, dict):
rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None)
to_parse: bool = bool(HAS_RICH and (rich_markup_mode == "rich"))
if obj.help:
docs += f"{_parse_html(to_parse, obj.help)}\n\n"
usage_pieces = obj.collect_usage_pieces(ctx)
if usage_pieces:
docs += "**Usage**:\n\n"
docs += "```console\n"
docs += "$ "
if command_name:
docs += f"{command_name} "
docs += f"{' '.join(usage_pieces)}\n"
docs += "```\n\n"
# Parameters marked with hidden=True are intentionally omitted from the live CLI
# help rendered by Rich (see rich_format_help in rich_utils.py). Generated Markdown
# from `typer ... utils docs` should follow the same rules so published docs do not
# leak internal or experimental flags/commands that authors hid from --help.
args = []
opts = []
for param in obj.get_params(ctx):
if getattr(param, "hidden", False):
continue
rv = param.get_help_record(ctx)
if rv is not None:
if param.param_type_name == "argument":
args.append(rv)
elif param.param_type_name == "option":
opts.append(rv)
if args:
docs += "**Arguments**:\n\n"
for arg_name, arg_help in args:
docs += f"* `{arg_name}`"
if arg_help:
docs += f": {_parse_html(to_parse, arg_help)}"
docs += "\n"
docs += "\n"
if opts:
docs += "**Options**:\n\n"
for opt_name, opt_help in opts:
docs += f"* `{opt_name}`"
if opt_help:
docs += f": {_parse_html(to_parse, opt_help)}"
docs += "\n"
docs += "\n"
if obj.epilog:
docs += f"{obj.epilog}\n\n"
if isinstance(obj, Group):
group = obj
# Subcommands registered with hidden=True still appear in list_commands() but
# are excluded from the command panels in rich_format_help. Mirror that here so
# the Markdown outline and nested sections match what users see when they run
# --help on each group.
visible_commands: list[str] = []
for cmd_name in group.list_commands(ctx):
command_obj = group.get_command(ctx, cmd_name)
if command_obj is None:
continue
if getattr(command_obj, "hidden", False):
continue
visible_commands.append(cmd_name)
if visible_commands:
docs += "**Commands**:\n\n"
for cmd_name in visible_commands:
command_obj = group.get_command(ctx, cmd_name)
assert command_obj is not None
docs += f"* `{command_obj.name}`"
command_help = command_obj.get_short_help_str()
if command_help:
docs += f": {_parse_html(to_parse, command_help)}"
docs += "\n"
docs += "\n"
for cmd_name in visible_commands:
command_obj = group.get_command(ctx, cmd_name)
assert command_obj is not None
use_prefix = ""
if command_name:
use_prefix += f"{command_name}"
docs += get_docs_for_click(
obj=command_obj, ctx=ctx, indent=indent + 1, call_prefix=use_prefix
)
return docs
def _parse_html(to_parse: bool, input_text: str) -> str:
if not to_parse:
return input_text
from . import rich_utils
return rich_utils.rich_to_html(input_text)
@utils_app.command()
def docs(
ctx: typer.Context,
name: str = typer.Option("", help="The name of the CLI program to use in docs."),
output: Path | None = typer.Option(
None,
help="An output file to write docs to, like README.md.",
file_okay=True,
dir_okay=False,
),
title: str | None = typer.Option(
None,
help="The title for the documentation page. If not provided, the name of "
"the program is used.",
),
) -> None:
"""
Generate Markdown docs for a Typer app.
"""
typer_obj = get_typer_from_state()
if not typer_obj:
typer.echo("No Typer app found", err=True)
raise typer.Abort()
if hasattr(typer_obj, "rich_markup_mode"):
if not hasattr(ctx, "obj") or ctx.obj is None:
ctx.ensure_object(dict)
if isinstance(ctx.obj, dict):
ctx.obj[MARKUP_MODE_KEY] = typer_obj.rich_markup_mode
click_obj = typer.main.get_command(typer_obj)
docs = get_docs_for_click(obj=click_obj, ctx=ctx, name=name, title=title)
clean_docs = f"{docs.strip()}\n"
if output:
output.write_text(clean_docs)
typer.echo(f"Docs saved to: {output}")
else:
typer.echo(clean_docs)
def main() -> Any:
return app()