Debian Codegraph @

cyclopts/cli/_complete.py

raw symbols SCIP
1 """Hidden completion helper command for dynamic shell completion."""
2
3 from pathlib import Path
4 from typing import TYPE_CHECKING, Annotated
5
6 from cyclopts.cli import app
7 from cyclopts.loader import load_app_from_script
8 from cyclopts.parameter import Parameter
9
10 if TYPE_CHECKING:
11 from cyclopts import App
12
13 MAX_DESCRIPTION_LENGTH = 60
14
15
16 def _extract_short_description(help_text: str | None) -> str:
17 """Extract first line of help text as a short description.
18
19 Parameters
20 ----------
21 help_text : str | None
22 Full help text to extract from.
23
24 Returns
25 -------
26 str
27 First line of help text, or empty string if parsing fails.
28 """
29 from cyclopts.help.help import docstring_parse
30
31 try:
32 parsed = docstring_parse(help_text, "plaintext")
33 return parsed.short_description or ""
34 except Exception:
35 return str(help_text or "").split("\n")[0]
36
37
38 def _print_subcommand_completions(app_obj: "App") -> None:
39 """Print completions for subcommands of the given app.
40
41 Parameters
42 ----------
43 app_obj : App
44 Application object to extract subcommands from.
45 """
46 from cyclopts.group_extractors import groups_from_app
47
48 for _, registered_commands in groups_from_app(app_obj):
49 for registered_command in registered_commands:
50 if registered_command.app.show:
51 for name in registered_command.names:
52 if not name.startswith("-"):
53 short_desc = _extract_short_description(registered_command.app.help)
54
55 if short_desc:
56 print(f"{name}:{short_desc}")
57 else:
58 print(name)
59
60
61 def _print_option_completions(app_obj: "App") -> None:
62 """Print completions for options of the given app's default command.
63
64 Parameters
65 ----------
66 app_obj : App
67 Application object to extract options from.
68 """
69 if not app_obj.default_command:
70 return
71
72 try:
73 arguments = app_obj.assemble_argument_collection(parse_docstring=True)
74 for argument in arguments:
75 if not argument.is_positional_only() and argument.show:
76 for name in argument.names:
77 if name.startswith("-"):
78 desc = argument.parameter.help or ""
79 desc = desc.split("\n")[0][:MAX_DESCRIPTION_LENGTH]
80 if desc:
81 print(f"{name}:{desc}")
82 else:
83 print(name)
84 except Exception:
85 pass
86
87
88 @app.command(name="_complete", show=False)
89 def complete(
90 subcommand: Annotated[str, Parameter(allow_leading_hyphen=True)],
91 script: Annotated[Path, Parameter(allow_leading_hyphen=True)],
92 *words: Annotated[str, Parameter(allow_leading_hyphen=True)],
93 ) -> None:
94 """Internal completion helper (hidden from users).
95
96 This command is called by the shell completion system to dynamically
97 generate completions for the 'run' command by loading the target script
98 and extracting its available commands and options.
99
100 Parameters
101 ----------
102 subcommand : str
103 The cyclopts subcommand being completed (e.g., "run").
104 script : Path
105 Python script path to load for completion extraction.
106 words : str
107 Current command line words for context-aware completion.
108 """
109 if subcommand != "run":
110 return
111
112 try:
113 app_obj, _ = load_app_from_script(script)
114 except (ImportError, SyntaxError, AttributeError, FileNotFoundError):
115 return
116
117 words_list = list(words) if words else []
118
119 # Complete from root app if no words or only empty string (initial completion)
120 if not words_list or (len(words_list) == 1 and not words_list[0]):
121 _print_subcommand_completions(app_obj)
122 _print_option_completions(app_obj)
123 else:
124 try:
125 _, execution_path, _ = app_obj.parse_commands(words_list)
126 current_app = execution_path[-1]
127 _print_subcommand_completions(current_app)
128 _print_option_completions(current_app)
129 except Exception:
130 pass