cliha 1.0.0rc1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cliha/__init__.py +57 -0
- cliha/__main__.py +212 -0
- cliha/_markers.py +51 -0
- cliha/_sample_app.py +22 -0
- cliha/api.py +163 -0
- cliha/config.py +23 -0
- cliha/emit/__init__.py +43 -0
- cliha/emit/_render.py +91 -0
- cliha/emit/_tables.py +213 -0
- cliha/emit/bash.py +66 -0
- cliha/emit/fish.py +57 -0
- cliha/emit/zsh.py +76 -0
- cliha/entry_points.py +88 -0
- cliha/extract.py +236 -0
- cliha/loader.py +36 -0
- cliha/model.py +251 -0
- cliha/paths.py +22 -0
- cliha/py.typed +1 -0
- cliha/resolve.py +329 -0
- cliha/shell/__init__.py +1 -0
- cliha/shell/runtime.bash +310 -0
- cliha/shell/runtime.fish +347 -0
- cliha/shell/runtime.zsh +344 -0
- cliha-1.0.0rc1.dist-info/METADATA +225 -0
- cliha-1.0.0rc1.dist-info/RECORD +29 -0
- cliha-1.0.0rc1.dist-info/WHEEL +5 -0
- cliha-1.0.0rc1.dist-info/entry_points.txt +2 -0
- cliha-1.0.0rc1.dist-info/licenses/LICENSE +21 -0
- cliha-1.0.0rc1.dist-info/top_level.txt +1 -0
cliha/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Public package interface for cliha."""
|
|
2
|
+
|
|
3
|
+
from cliha.api import (
|
|
4
|
+
dynamic_commands,
|
|
5
|
+
dynamic_completion,
|
|
6
|
+
get_parameter_shell_complete,
|
|
7
|
+
hybrid_completion,
|
|
8
|
+
is_dynamic_completion,
|
|
9
|
+
is_dynamic_parameter,
|
|
10
|
+
resolve_hybrid_config,
|
|
11
|
+
)
|
|
12
|
+
from cliha.config import DynamicCompletionConfig, HybridConfig
|
|
13
|
+
from cliha.emit import emit_completion_script
|
|
14
|
+
from cliha.extract import extract_model
|
|
15
|
+
from cliha.model import CommandNode, CompletionModel, ModelError, Param, ValueSource
|
|
16
|
+
from cliha.resolve import (
|
|
17
|
+
Answer,
|
|
18
|
+
Candidate,
|
|
19
|
+
Candidates,
|
|
20
|
+
Defer,
|
|
21
|
+
Dirs,
|
|
22
|
+
Files,
|
|
23
|
+
Nothing,
|
|
24
|
+
Resolution,
|
|
25
|
+
explain,
|
|
26
|
+
resolve,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"Answer",
|
|
32
|
+
"Candidate",
|
|
33
|
+
"Candidates",
|
|
34
|
+
"CommandNode",
|
|
35
|
+
"CompletionModel",
|
|
36
|
+
"Defer",
|
|
37
|
+
"Dirs",
|
|
38
|
+
"DynamicCompletionConfig",
|
|
39
|
+
"Files",
|
|
40
|
+
"HybridConfig",
|
|
41
|
+
"ModelError",
|
|
42
|
+
"Nothing",
|
|
43
|
+
"Param",
|
|
44
|
+
"Resolution",
|
|
45
|
+
"ValueSource",
|
|
46
|
+
"dynamic_commands",
|
|
47
|
+
"dynamic_completion",
|
|
48
|
+
"emit_completion_script",
|
|
49
|
+
"explain",
|
|
50
|
+
"extract_model",
|
|
51
|
+
"get_parameter_shell_complete",
|
|
52
|
+
"hybrid_completion",
|
|
53
|
+
"is_dynamic_completion",
|
|
54
|
+
"is_dynamic_parameter",
|
|
55
|
+
"resolve",
|
|
56
|
+
"resolve_hybrid_config",
|
|
57
|
+
]
|
cliha/__main__.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""CLI entrypoint for cliha utility."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib.metadata import version
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import cast
|
|
8
|
+
|
|
9
|
+
import click
|
|
10
|
+
|
|
11
|
+
from cliha.api import resolve_hybrid_config
|
|
12
|
+
from cliha.emit import ShellTarget, emit_completion_script
|
|
13
|
+
from cliha.entry_points import resolve_prog_name
|
|
14
|
+
from cliha.extract import extract_model
|
|
15
|
+
from cliha.loader import load_click
|
|
16
|
+
from cliha.model import CompletionModel
|
|
17
|
+
from cliha.paths import script_path
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _load_model(factory: str, prog_name: str | None) -> CompletionModel:
|
|
21
|
+
app = load_click(factory)
|
|
22
|
+
resolved_prog_name = resolve_prog_name(
|
|
23
|
+
factory,
|
|
24
|
+
app.name,
|
|
25
|
+
explicit=prog_name,
|
|
26
|
+
from_config=resolve_hybrid_config(app).prog_name,
|
|
27
|
+
)
|
|
28
|
+
return extract_model(app, prog_name=resolved_prog_name)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@click.group(help="CLIck Hybrid Autocompletion utility.")
|
|
32
|
+
def cli() -> None:
|
|
33
|
+
"""Main CLI group."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@cli.command("version", help="Print cliha version.")
|
|
37
|
+
def version_cmd() -> None:
|
|
38
|
+
"""Print package version."""
|
|
39
|
+
|
|
40
|
+
click.echo(version("cliha"))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@cli.command(
|
|
44
|
+
"generate",
|
|
45
|
+
help="Generate a hybrid shell completion script (static hot path + runtime fallback).",
|
|
46
|
+
)
|
|
47
|
+
@click.option(
|
|
48
|
+
"--factory",
|
|
49
|
+
required=True,
|
|
50
|
+
metavar="MODULE:ATTR",
|
|
51
|
+
help="Python object providing a Click Command/Group (e.g. 'mypkg.cli:cli').",
|
|
52
|
+
)
|
|
53
|
+
@click.option(
|
|
54
|
+
"--shell",
|
|
55
|
+
type=click.Choice(["bash", "zsh", "fish"], case_sensitive=False),
|
|
56
|
+
required=True,
|
|
57
|
+
help="Target shell.",
|
|
58
|
+
)
|
|
59
|
+
@click.option(
|
|
60
|
+
"--output",
|
|
61
|
+
default="-",
|
|
62
|
+
show_default=True,
|
|
63
|
+
metavar="PATH|-",
|
|
64
|
+
help="Output path. Use '-' for stdout.",
|
|
65
|
+
)
|
|
66
|
+
@click.option(
|
|
67
|
+
"--prog-name",
|
|
68
|
+
default=None,
|
|
69
|
+
metavar="NAME",
|
|
70
|
+
help="Override the executable name used inside completion scripts.",
|
|
71
|
+
)
|
|
72
|
+
def generate_cmd(
|
|
73
|
+
factory: str,
|
|
74
|
+
shell: str,
|
|
75
|
+
output: str,
|
|
76
|
+
prog_name: str | None,
|
|
77
|
+
) -> None:
|
|
78
|
+
"""Generate a hybrid completion script for the Click app."""
|
|
79
|
+
|
|
80
|
+
model = _load_model(factory, prog_name)
|
|
81
|
+
script = emit_completion_script(model, cast(ShellTarget, shell.lower()))
|
|
82
|
+
|
|
83
|
+
if output == "-":
|
|
84
|
+
click.echo(script, nl=False)
|
|
85
|
+
return
|
|
86
|
+
|
|
87
|
+
output_path = Path(output)
|
|
88
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
output_path.write_text(script, encoding="utf-8")
|
|
90
|
+
click.echo(f"Wrote completion script to {output_path}")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@cli.command("dump", help="Print the completion model of a Click app as JSON.")
|
|
94
|
+
@click.option(
|
|
95
|
+
"--factory",
|
|
96
|
+
required=True,
|
|
97
|
+
metavar="MODULE:ATTR",
|
|
98
|
+
help="Python object providing a Click Command/Group (e.g. 'mypkg.cli:cli').",
|
|
99
|
+
)
|
|
100
|
+
@click.option(
|
|
101
|
+
"--prog-name",
|
|
102
|
+
default=None,
|
|
103
|
+
metavar="NAME",
|
|
104
|
+
help="Override the executable name used inside completion scripts.",
|
|
105
|
+
)
|
|
106
|
+
def dump_cmd(factory: str, prog_name: str | None) -> None:
|
|
107
|
+
"""Print the model that completion scripts are generated from."""
|
|
108
|
+
|
|
109
|
+
click.echo(_load_model(factory, prog_name).to_json())
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@cli.command("doctor", help="Validate local environment basics.")
|
|
113
|
+
def doctor_cmd() -> None:
|
|
114
|
+
"""Run basic environment checks."""
|
|
115
|
+
|
|
116
|
+
click.echo("cliha doctor: ok")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@cli.command("path", help="Print where a completion script would be installed.")
|
|
120
|
+
@click.option(
|
|
121
|
+
"--factory",
|
|
122
|
+
required=True,
|
|
123
|
+
metavar="MODULE:ATTR",
|
|
124
|
+
help="Python object providing a Click Command/Group (e.g. 'mypkg.cli:cli').",
|
|
125
|
+
)
|
|
126
|
+
@click.option(
|
|
127
|
+
"--shell",
|
|
128
|
+
type=click.Choice(["bash", "zsh", "fish"], case_sensitive=False),
|
|
129
|
+
required=True,
|
|
130
|
+
help="Target shell.",
|
|
131
|
+
)
|
|
132
|
+
@click.option(
|
|
133
|
+
"--prog-name",
|
|
134
|
+
default=None,
|
|
135
|
+
metavar="NAME",
|
|
136
|
+
help="Override the executable name used inside completion scripts.",
|
|
137
|
+
)
|
|
138
|
+
def path_cmd(factory: str, shell: str, prog_name: str | None) -> None:
|
|
139
|
+
"""Print computed completion script path."""
|
|
140
|
+
|
|
141
|
+
model = _load_model(factory, prog_name)
|
|
142
|
+
out_path = script_path(shell, model.prog_name)
|
|
143
|
+
click.echo(str(out_path))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@cli.command("install", help="Write completion scripts into cliha's data dir.")
|
|
147
|
+
@click.option(
|
|
148
|
+
"--factory",
|
|
149
|
+
required=True,
|
|
150
|
+
metavar="MODULE:ATTR",
|
|
151
|
+
help="Python object providing a Click Command/Group (e.g. 'mypkg.cli:cli').",
|
|
152
|
+
)
|
|
153
|
+
@click.option(
|
|
154
|
+
"--shell",
|
|
155
|
+
type=click.Choice(["bash", "zsh", "fish"], case_sensitive=False),
|
|
156
|
+
required=True,
|
|
157
|
+
help="Target shell.",
|
|
158
|
+
)
|
|
159
|
+
@click.option(
|
|
160
|
+
"--prog-name",
|
|
161
|
+
default=None,
|
|
162
|
+
metavar="NAME",
|
|
163
|
+
help="Override the executable name used inside completion scripts.",
|
|
164
|
+
)
|
|
165
|
+
def install_cmd(factory: str, shell: str, prog_name: str | None) -> None:
|
|
166
|
+
"""Generate and install a completion script for one shell."""
|
|
167
|
+
|
|
168
|
+
model = _load_model(factory, prog_name)
|
|
169
|
+
script = emit_completion_script(model, cast(ShellTarget, shell.lower()))
|
|
170
|
+
|
|
171
|
+
out_path = script_path(shell, model.prog_name)
|
|
172
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
173
|
+
out_path.write_text(script, encoding="utf-8")
|
|
174
|
+
|
|
175
|
+
click.echo(str(out_path))
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@cli.command("uninstall", help="Remove installed completion scripts (best-effort).")
|
|
179
|
+
@click.option(
|
|
180
|
+
"--factory",
|
|
181
|
+
required=True,
|
|
182
|
+
metavar="MODULE:ATTR",
|
|
183
|
+
help="Python object providing a Click Command/Group (e.g. 'mypkg.cli:cli').",
|
|
184
|
+
)
|
|
185
|
+
@click.option(
|
|
186
|
+
"--shell",
|
|
187
|
+
type=click.Choice(["bash", "zsh", "fish"], case_sensitive=False),
|
|
188
|
+
required=True,
|
|
189
|
+
help="Target shell.",
|
|
190
|
+
)
|
|
191
|
+
@click.option(
|
|
192
|
+
"--prog-name",
|
|
193
|
+
default=None,
|
|
194
|
+
metavar="NAME",
|
|
195
|
+
help="Override the executable name used inside completion scripts.",
|
|
196
|
+
)
|
|
197
|
+
def uninstall_cmd(factory: str, shell: str, prog_name: str | None) -> None:
|
|
198
|
+
"""Remove installed completion script if it exists."""
|
|
199
|
+
|
|
200
|
+
model = _load_model(factory, prog_name)
|
|
201
|
+
out_path = script_path(shell, model.prog_name)
|
|
202
|
+
|
|
203
|
+
try:
|
|
204
|
+
out_path.unlink(missing_ok=True)
|
|
205
|
+
except OSError:
|
|
206
|
+
pass
|
|
207
|
+
|
|
208
|
+
click.echo(str(out_path))
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
if __name__ == "__main__":
|
|
212
|
+
cli()
|
cliha/_markers.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Internal marker attribute names and accessors."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
6
|
+
|
|
7
|
+
from cliha.config import DynamicCompletionConfig, HybridConfig
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
import click
|
|
12
|
+
|
|
13
|
+
HYBRID_CONFIG_ATTR = "__cliha_hybrid_config__"
|
|
14
|
+
DYNAMIC_CONFIG_ATTR = "__cliha_dynamic_config__"
|
|
15
|
+
DYNAMIC_COMMANDS_ATTR = "__cliha_dynamic_commands__"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def set_hybrid_config(command: click.Command, config: HybridConfig) -> None:
|
|
19
|
+
cast(Any, command).__cliha_hybrid_config__ = config
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def get_hybrid_config(command: click.Command) -> HybridConfig | None:
|
|
23
|
+
marker = getattr(command, HYBRID_CONFIG_ATTR, None)
|
|
24
|
+
if marker is None:
|
|
25
|
+
return None
|
|
26
|
+
if not isinstance(marker, HybridConfig):
|
|
27
|
+
msg = f"Invalid hybrid config marker on {command.name!r}"
|
|
28
|
+
raise TypeError(msg)
|
|
29
|
+
return marker
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def set_dynamic_config(target: object, config: DynamicCompletionConfig) -> None:
|
|
33
|
+
cast(Any, target).__cliha_dynamic_config__ = config
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def get_dynamic_config(target: object) -> DynamicCompletionConfig | None:
|
|
37
|
+
marker = getattr(target, DYNAMIC_CONFIG_ATTR, None)
|
|
38
|
+
if marker is None:
|
|
39
|
+
return None
|
|
40
|
+
if not isinstance(marker, DynamicCompletionConfig):
|
|
41
|
+
msg = f"Invalid dynamic config marker on {target!r}"
|
|
42
|
+
raise TypeError(msg)
|
|
43
|
+
return marker
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def mark_dynamic_commands(group: click.Command) -> None:
|
|
47
|
+
cast(Any, group).__cliha_dynamic_commands__ = True
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def has_dynamic_commands(group: click.Command) -> bool:
|
|
51
|
+
return getattr(group, DYNAMIC_COMMANDS_ATTR, False) is True
|
cliha/_sample_app.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Internal sample Click app used by cliha CLI tests."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@click.group()
|
|
9
|
+
def cli() -> None:
|
|
10
|
+
"""Sample app for cliha tests."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@cli.command("run")
|
|
14
|
+
@click.option("--format", type=click.Choice(["json", "yaml"]))
|
|
15
|
+
@click.option("--verbose", is_flag=True)
|
|
16
|
+
def run(format: str, verbose: bool) -> None: # noqa: A002
|
|
17
|
+
del format, verbose
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@cli.command("list-items")
|
|
21
|
+
def list_items() -> None:
|
|
22
|
+
pass
|
cliha/api.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Public API surface for hybrid completion integration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Iterable
|
|
6
|
+
from typing import TYPE_CHECKING, Any, TypeVar, cast
|
|
7
|
+
|
|
8
|
+
from cliha._markers import (
|
|
9
|
+
get_dynamic_config,
|
|
10
|
+
get_hybrid_config,
|
|
11
|
+
mark_dynamic_commands,
|
|
12
|
+
set_dynamic_config,
|
|
13
|
+
set_hybrid_config,
|
|
14
|
+
)
|
|
15
|
+
from cliha.config import DynamicCompletionConfig, HybridConfig
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
import click
|
|
20
|
+
from click.shell_completion import CompletionItem
|
|
21
|
+
|
|
22
|
+
Decorated = TypeVar("Decorated")
|
|
23
|
+
|
|
24
|
+
ShellCompleteCallback = Callable[
|
|
25
|
+
["click.Context", "click.Parameter", str],
|
|
26
|
+
Iterable["CompletionItem | str"],
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def hybrid_completion(
|
|
31
|
+
config: HybridConfig | None = None,
|
|
32
|
+
/,
|
|
33
|
+
*,
|
|
34
|
+
prog_name: str | None = None,
|
|
35
|
+
fallback_command: str | None = None,
|
|
36
|
+
) -> Callable[[Decorated], Decorated]:
|
|
37
|
+
"""Configure hybrid completion for a Click command or group.
|
|
38
|
+
|
|
39
|
+
Apply above ``@click.command`` / ``@click.group`` so the decorator receives
|
|
40
|
+
the final ``click.Command`` instance::
|
|
41
|
+
|
|
42
|
+
@hybrid_completion(prog_name="mycli")
|
|
43
|
+
@click.group()
|
|
44
|
+
def cli() -> None:
|
|
45
|
+
...
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
base = config or HybridConfig()
|
|
49
|
+
resolved = HybridConfig(
|
|
50
|
+
prog_name=prog_name if prog_name is not None else base.prog_name,
|
|
51
|
+
fallback_command=(
|
|
52
|
+
fallback_command if fallback_command is not None else base.fallback_command
|
|
53
|
+
),
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
def decorator(command: Decorated) -> Decorated:
|
|
57
|
+
set_hybrid_config(cast(Any, command), resolved)
|
|
58
|
+
return command
|
|
59
|
+
|
|
60
|
+
return decorator
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def dynamic_commands(group: Decorated) -> Decorated:
|
|
64
|
+
"""Mark a Click group whose set of commands is not fixed.
|
|
65
|
+
|
|
66
|
+
Use it on groups that load commands at run time (plugins, lazy loading
|
|
67
|
+
from disk) or accept names they do not list (aliases, prefixes). The
|
|
68
|
+
completion script then asks the application for that group's command
|
|
69
|
+
names instead of trusting the list it was generated with::
|
|
70
|
+
|
|
71
|
+
@dynamic_commands
|
|
72
|
+
@click.group(cls=PluginGroup)
|
|
73
|
+
def cli() -> None:
|
|
74
|
+
...
|
|
75
|
+
|
|
76
|
+
It also works on a group defined elsewhere: ``dynamic_commands(their_cli)``.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
if not callable(getattr(group, "list_commands", None)):
|
|
80
|
+
msg = f"dynamic_commands expects a Click group, got {type(group).__name__}"
|
|
81
|
+
raise TypeError(msg)
|
|
82
|
+
mark_dynamic_commands(cast(Any, group))
|
|
83
|
+
return group
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def dynamic_completion(
|
|
87
|
+
callback: ShellCompleteCallback,
|
|
88
|
+
/,
|
|
89
|
+
*,
|
|
90
|
+
config: DynamicCompletionConfig | None = None,
|
|
91
|
+
name: str | None = None,
|
|
92
|
+
help: str | None = None,
|
|
93
|
+
) -> ShellCompleteCallback:
|
|
94
|
+
"""Wrap a Click ``shell_complete`` callback as an explicit dynamic resolver.
|
|
95
|
+
|
|
96
|
+
Use as the ``shell_complete`` value on options and arguments whose values
|
|
97
|
+
must be resolved at completion time::
|
|
98
|
+
|
|
99
|
+
@click.option("--user", shell_complete=dynamic_completion(list_users))
|
|
100
|
+
def cmd(user: str) -> None:
|
|
101
|
+
...
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
base = config or DynamicCompletionConfig()
|
|
105
|
+
resolved = DynamicCompletionConfig(
|
|
106
|
+
name=name if name is not None else base.name,
|
|
107
|
+
help=help if help is not None else base.help,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
def wrapped(
|
|
111
|
+
ctx: click.Context,
|
|
112
|
+
param: click.Parameter,
|
|
113
|
+
incomplete: str,
|
|
114
|
+
) -> list[CompletionItem | str]:
|
|
115
|
+
return list(callback(ctx, param, incomplete))
|
|
116
|
+
|
|
117
|
+
set_dynamic_config(wrapped, resolved)
|
|
118
|
+
return wrapped
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def resolve_hybrid_config(
|
|
122
|
+
command: click.Command,
|
|
123
|
+
*,
|
|
124
|
+
ctx: click.Context | None = None,
|
|
125
|
+
) -> HybridConfig:
|
|
126
|
+
"""Return the nearest hybrid config for a command, or library defaults.
|
|
127
|
+
|
|
128
|
+
When *ctx* is provided, walk the Click context parent chain so subcommands can
|
|
129
|
+
inherit configuration from ancestor groups.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
current: click.Context | None = ctx
|
|
133
|
+
while current is not None:
|
|
134
|
+
config = get_hybrid_config(current.command)
|
|
135
|
+
if config is not None:
|
|
136
|
+
return config
|
|
137
|
+
current = current.parent
|
|
138
|
+
|
|
139
|
+
return get_hybrid_config(command) or HybridConfig()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def is_dynamic_completion(target: object) -> bool:
|
|
143
|
+
"""Return whether *target* is marked as a dynamic completion resolver."""
|
|
144
|
+
|
|
145
|
+
return get_dynamic_config(target) is not None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def get_parameter_shell_complete(
|
|
149
|
+
param: click.Parameter,
|
|
150
|
+
) -> ShellCompleteCallback | None:
|
|
151
|
+
"""Return the custom ``shell_complete`` callback registered on a parameter."""
|
|
152
|
+
|
|
153
|
+
custom = getattr(param, "_custom_shell_complete", None)
|
|
154
|
+
if custom is None:
|
|
155
|
+
return None
|
|
156
|
+
return cast(ShellCompleteCallback, custom)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def is_dynamic_parameter(param: click.Parameter) -> bool:
|
|
160
|
+
"""Return whether a Click parameter uses an explicit dynamic resolver."""
|
|
161
|
+
|
|
162
|
+
custom = get_parameter_shell_complete(param)
|
|
163
|
+
return custom is not None and is_dynamic_completion(custom)
|
cliha/config.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Configuration models for hybrid completion."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True, slots=True)
|
|
9
|
+
class HybridConfig:
|
|
10
|
+
"""Configuration for hybrid completion on a Click command or group."""
|
|
11
|
+
|
|
12
|
+
#: Executable name the completion script is registered for.
|
|
13
|
+
prog_name: str | None = None
|
|
14
|
+
#: Executable called when the script defers to the application.
|
|
15
|
+
fallback_command: str | None = None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True)
|
|
19
|
+
class DynamicCompletionConfig:
|
|
20
|
+
"""Configuration for a parameter resolved at completion runtime."""
|
|
21
|
+
|
|
22
|
+
name: str | None = None
|
|
23
|
+
help: str | None = None
|
cliha/emit/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Completion script emitters.
|
|
2
|
+
|
|
3
|
+
A script is a set of lookup tables computed from the model, followed by the
|
|
4
|
+
fixed, hand-written runtime of the shell (``cliha/shell/runtime.*``) and one
|
|
5
|
+
registration line. No shell code is generated from the command tree.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Literal, get_args
|
|
11
|
+
|
|
12
|
+
from cliha.emit._tables import Tables, build_tables, function_prefix
|
|
13
|
+
from cliha.emit.bash import emit_bash
|
|
14
|
+
from cliha.emit.fish import emit_fish
|
|
15
|
+
from cliha.emit.zsh import emit_zsh
|
|
16
|
+
from cliha.model import CompletionModel
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
ShellTarget = Literal["bash", "zsh", "fish"]
|
|
20
|
+
|
|
21
|
+
SHELLS: tuple[ShellTarget, ...] = get_args(ShellTarget)
|
|
22
|
+
|
|
23
|
+
_EMITTERS = {"bash": emit_bash, "zsh": emit_zsh, "fish": emit_fish}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def emit_completion_script(model: CompletionModel, shell: ShellTarget) -> str:
|
|
27
|
+
"""Return the completion script of *model* for *shell*."""
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
emitter = _EMITTERS[shell]
|
|
31
|
+
except KeyError:
|
|
32
|
+
raise ValueError(f"Unsupported shell: {shell!r}") from None
|
|
33
|
+
return emitter(build_tables(model))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"SHELLS",
|
|
38
|
+
"ShellTarget",
|
|
39
|
+
"Tables",
|
|
40
|
+
"build_tables",
|
|
41
|
+
"emit_completion_script",
|
|
42
|
+
"function_prefix",
|
|
43
|
+
]
|
cliha/emit/_render.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Helpers shared by the per-shell emitters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable, Sequence
|
|
6
|
+
from importlib import resources
|
|
7
|
+
|
|
8
|
+
from cliha.emit._tables import PLACEHOLDER
|
|
9
|
+
from cliha.model import SCHEMA_VERSION
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
_WIDTH = 100
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def load_runtime(shell: str, prefix: str) -> str:
|
|
16
|
+
"""Return the runtime of *shell* with its names bound to *prefix*."""
|
|
17
|
+
|
|
18
|
+
text = resources.files("cliha.shell").joinpath(f"runtime.{shell}").read_text(encoding="utf-8")
|
|
19
|
+
return text.replace(PLACEHOLDER, prefix)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def header(prog_name: str, shell: str) -> list[str]:
|
|
23
|
+
return [
|
|
24
|
+
f"# {shell} completion for {_comment(prog_name)}, generated by cliha. Do not edit.",
|
|
25
|
+
f"# Layout: lookup tables, then cliha's {shell} runtime (model schema {SCHEMA_VERSION}).",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _comment(text: str) -> str:
|
|
30
|
+
return "".join(char if char.isprintable() else "?" for char in text)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def sh_quote(text: str) -> str:
|
|
34
|
+
"""Quote *text* as one word for bash and zsh, whatever their options."""
|
|
35
|
+
|
|
36
|
+
if "'" not in text and all(char.isprintable() or char == " " for char in text):
|
|
37
|
+
return f"'{text}'"
|
|
38
|
+
|
|
39
|
+
parts: list[str] = []
|
|
40
|
+
for char in text:
|
|
41
|
+
if char in "\\'":
|
|
42
|
+
parts.append("\\" + char)
|
|
43
|
+
elif char == "\n":
|
|
44
|
+
parts.append("\\n")
|
|
45
|
+
elif char == "\t":
|
|
46
|
+
parts.append("\\t")
|
|
47
|
+
elif ord(char) < 0x20 or ord(char) == 0x7F:
|
|
48
|
+
parts.append(f"\\x{ord(char):02x}")
|
|
49
|
+
else:
|
|
50
|
+
parts.append(char)
|
|
51
|
+
return "$'" + "".join(parts) + "'"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def fish_quote(text: str) -> str:
|
|
55
|
+
"""Quote *text* as one word for fish."""
|
|
56
|
+
|
|
57
|
+
return "'" + text.replace("\\", "\\\\").replace("'", "\\'") + "'"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def numbers(values: Iterable[int]) -> list[str]:
|
|
61
|
+
return [str(value) for value in values]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def wrap(
|
|
65
|
+
first: str,
|
|
66
|
+
words: Sequence[str],
|
|
67
|
+
last: str = "",
|
|
68
|
+
*,
|
|
69
|
+
tight: bool = False,
|
|
70
|
+
continuation: str = "",
|
|
71
|
+
) -> list[str]:
|
|
72
|
+
"""Lay *words* out after *first*, breaking lines at about 100 columns.
|
|
73
|
+
|
|
74
|
+
With *tight*, the first word follows *first* without a space, as in
|
|
75
|
+
``name=(word``. *continuation* ends every line that is followed by another.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
lines: list[str] = []
|
|
79
|
+
current = first
|
|
80
|
+
empty = True
|
|
81
|
+
for word in words:
|
|
82
|
+
if not empty and len(current) + 1 + len(word) + len(continuation) > _WIDTH:
|
|
83
|
+
lines.append(current + continuation)
|
|
84
|
+
current = " " + word
|
|
85
|
+
elif empty and tight:
|
|
86
|
+
current += word
|
|
87
|
+
else:
|
|
88
|
+
current += " " + word
|
|
89
|
+
empty = False
|
|
90
|
+
lines.append(current + last)
|
|
91
|
+
return lines
|