eosh 0.2.0__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.
- eosh/__init__.py +34 -0
- eosh/__main__.py +23 -0
- eosh/_config.py +367 -0
- eosh/colors.py +63 -0
- eosh/commands.py +785 -0
- eosh/completion.py +952 -0
- eosh/completion_cache.py +77 -0
- eosh/context.py +189 -0
- eosh/decorators/__init__.py +263 -0
- eosh/decorators/bg.py +39 -0
- eosh/decorators/quiet.py +39 -0
- eosh/decorators/retry.py +46 -0
- eosh/decorators/time.py +44 -0
- eosh/decorators/watch.py +660 -0
- eosh/history.py +36 -0
- eosh/lineedit.py +1442 -0
- eosh/notify.py +404 -0
- eosh/parsing.py +226 -0
- eosh/paths.py +18 -0
- eosh/pipeline.py +668 -0
- eosh/process.py +465 -0
- eosh/prompt.py +77 -0
- eosh/recipes/__init__.py +208 -0
- eosh/recipes/_awsut_agentcore/__init__.py +46 -0
- eosh/recipes/_awsut_agentcore/harness.py +721 -0
- eosh/recipes/_awsut_agentcore/memory.py +1209 -0
- eosh/recipes/_awsut_agentcore/render.py +337 -0
- eosh/recipes/_awsut_common.py +533 -0
- eosh/recipes/_awsut_sagemaker/__init__.py +36 -0
- eosh/recipes/_awsut_sagemaker/hub.py +866 -0
- eosh/recipes/_awsut_sagemaker/hyperpod.py +1948 -0
- eosh/recipes/_awsut_sagemaker/jobs.py +1041 -0
- eosh/recipes/_awsut_sagemaker/render.py +300 -0
- eosh/recipes/_awsut_sagemaker/studio.py +1584 -0
- eosh/recipes/_missing.py +168 -0
- eosh/recipes/aws.py +239 -0
- eosh/recipes/awsut.py +1649 -0
- eosh/recipes/chmod.py +58 -0
- eosh/recipes/chown.py +117 -0
- eosh/recipes/cp.py +80 -0
- eosh/recipes/curl.py +108 -0
- eosh/recipes/df.py +33 -0
- eosh/recipes/du.py +82 -0
- eosh/recipes/find.py +60 -0
- eosh/recipes/git.py +295 -0
- eosh/recipes/grep.py +54 -0
- eosh/recipes/kill.py +92 -0
- eosh/recipes/ls.py +44 -0
- eosh/recipes/lsof.py +56 -0
- eosh/recipes/make.py +219 -0
- eosh/recipes/mv.py +52 -0
- eosh/recipes/ps.py +73 -0
- eosh/recipes/rm.py +55 -0
- eosh/recipes/rsync.py +143 -0
- eosh/recipes/scp.py +97 -0
- eosh/recipes/ssh.py +92 -0
- eosh/recipes/tail.py +23 -0
- eosh/recipes/tar.py +170 -0
- eosh/recipes/terraform.py +374 -0
- eosh/recipes/top.py +84 -0
- eosh/recipes/unzip.py +96 -0
- eosh/recipes/zip.py +53 -0
- eosh/scrollbar.py +122 -0
- eosh/shell.py +4253 -0
- eosh/terminal.py +446 -0
- eosh/tui.py +1082 -0
- eosh/variables.py +253 -0
- eosh-0.2.0.dist-info/METADATA +637 -0
- eosh-0.2.0.dist-info/RECORD +73 -0
- eosh-0.2.0.dist-info/WHEEL +5 -0
- eosh-0.2.0.dist-info/entry_points.txt +2 -0
- eosh-0.2.0.dist-info/licenses/LICENSE +21 -0
- eosh-0.2.0.dist-info/top_level.txt +1 -0
eosh/completion.py
ADDED
|
@@ -0,0 +1,952 @@
|
|
|
1
|
+
"""Completion engine — Completer ABC, CompletionContext, built-in completers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
from abc import ABC, abstractmethod
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
from .context import Context
|
|
12
|
+
from .parsing import raw_token_start
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _to_slash(path: str) -> str:
|
|
16
|
+
"""Normalize OS path separators to ``/``.
|
|
17
|
+
|
|
18
|
+
The shell uses ``/`` as the canonical separator on every platform (Windows
|
|
19
|
+
file APIs accept it), keeping ``\\`` free for POSIX escaping. ``os.path``
|
|
20
|
+
helpers emit native ``\\`` on Windows, so completer output is run through
|
|
21
|
+
this. No-op on POSIX (``os.altsep`` is None there).
|
|
22
|
+
"""
|
|
23
|
+
return path.replace(os.sep, "/") if os.altsep else path
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class CompletionContext:
|
|
28
|
+
command: str | None
|
|
29
|
+
args: list[str]
|
|
30
|
+
arg_index: int
|
|
31
|
+
prefix: str
|
|
32
|
+
line: str
|
|
33
|
+
shell_context: Context | None = None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class Completion:
|
|
38
|
+
value: str
|
|
39
|
+
display: str = ""
|
|
40
|
+
description: str = ""
|
|
41
|
+
fields: tuple[str, ...] = () # description split into picker columns (aligned across rows)
|
|
42
|
+
multi_select: bool = False
|
|
43
|
+
combinable: bool = False # True for single-char flags that can be merged (-a -l → -al)
|
|
44
|
+
arg_hint: str = "" # non-empty when the flag requires a following argument (e.g. "N")
|
|
45
|
+
is_arg_hint: bool = False # True when this completion IS the hint for a preceding flag's value
|
|
46
|
+
verbatim: bool = False # True → value may span several tokens; inserted as-is at the anchor
|
|
47
|
+
|
|
48
|
+
def __post_init__(self):
|
|
49
|
+
if not self.display:
|
|
50
|
+
self.display = self.value
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def meta(self) -> str | tuple[str, ...]:
|
|
54
|
+
"""What the picker draws beside the value.
|
|
55
|
+
|
|
56
|
+
``fields`` when the completer split its metadata into columns — the
|
|
57
|
+
picker pads those so they line up across rows, which a separator baked
|
|
58
|
+
into one ``description`` string can't do — and the plain string
|
|
59
|
+
otherwise.
|
|
60
|
+
"""
|
|
61
|
+
return self.fields or self.description
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Completer(ABC):
|
|
65
|
+
@abstractmethod
|
|
66
|
+
def complete(self, ctx: CompletionContext) -> list[Completion]:
|
|
67
|
+
...
|
|
68
|
+
|
|
69
|
+
def should_activate(self, ctx: CompletionContext) -> bool:
|
|
70
|
+
return True
|
|
71
|
+
|
|
72
|
+
def describe_slot(self, args: list[str], pos_idx: int) -> str | None:
|
|
73
|
+
"""Return a status-bar label for the positional slot, or None to use the
|
|
74
|
+
static ``help=`` text from the ``arg()`` descriptor.
|
|
75
|
+
|
|
76
|
+
Override when the slot's role depends on preceding args (e.g. tar's
|
|
77
|
+
first positional is the archive unless ``-f ARCHIVE`` was given).
|
|
78
|
+
"""
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class DirCompleter(Completer):
|
|
83
|
+
"""Completes directory paths only (no files)."""
|
|
84
|
+
|
|
85
|
+
def complete(self, ctx: CompletionContext) -> list[Completion]:
|
|
86
|
+
prefix = ctx.prefix
|
|
87
|
+
if prefix:
|
|
88
|
+
expanded = os.path.expanduser(prefix)
|
|
89
|
+
directory = os.path.dirname(expanded) or "."
|
|
90
|
+
partial = os.path.basename(expanded)
|
|
91
|
+
else:
|
|
92
|
+
directory = "."
|
|
93
|
+
partial = ""
|
|
94
|
+
try:
|
|
95
|
+
entries = os.listdir(directory)
|
|
96
|
+
except OSError:
|
|
97
|
+
return []
|
|
98
|
+
result = []
|
|
99
|
+
for entry in sorted(entries):
|
|
100
|
+
if entry.startswith(".") and not partial.startswith("."):
|
|
101
|
+
continue
|
|
102
|
+
if entry.lower().startswith(partial.lower()):
|
|
103
|
+
full_path = os.path.join(directory, entry)
|
|
104
|
+
if os.path.isdir(full_path):
|
|
105
|
+
display_path = (
|
|
106
|
+
os.path.join(os.path.dirname(prefix), entry)
|
|
107
|
+
if prefix and os.path.dirname(prefix)
|
|
108
|
+
else entry
|
|
109
|
+
)
|
|
110
|
+
result.append(
|
|
111
|
+
Completion(value=_to_slash(display_path) + "/", display=entry + "/")
|
|
112
|
+
)
|
|
113
|
+
return result
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class FileCompleter(Completer):
|
|
117
|
+
def complete(self, ctx: CompletionContext) -> list[Completion]:
|
|
118
|
+
prefix = ctx.prefix
|
|
119
|
+
if prefix:
|
|
120
|
+
expanded_prefix = os.path.expanduser(prefix)
|
|
121
|
+
directory = os.path.dirname(expanded_prefix) or "."
|
|
122
|
+
partial = os.path.basename(expanded_prefix)
|
|
123
|
+
else:
|
|
124
|
+
directory = "."
|
|
125
|
+
partial = ""
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
entries = os.listdir(directory)
|
|
129
|
+
except OSError:
|
|
130
|
+
return []
|
|
131
|
+
|
|
132
|
+
dirs = []
|
|
133
|
+
files = []
|
|
134
|
+
for entry in sorted(entries):
|
|
135
|
+
if entry.startswith(".") and not partial.startswith("."):
|
|
136
|
+
continue
|
|
137
|
+
if entry.lower().startswith(partial.lower()):
|
|
138
|
+
full_path = os.path.join(directory, entry)
|
|
139
|
+
display_path = os.path.join(os.path.dirname(prefix), entry) if prefix and os.path.dirname(prefix) else entry
|
|
140
|
+
display_path = _to_slash(display_path)
|
|
141
|
+
if os.path.isdir(full_path):
|
|
142
|
+
dirs.append(Completion(value=display_path + "/", display=entry + "/"))
|
|
143
|
+
else:
|
|
144
|
+
files.append(Completion(value=display_path, display=entry))
|
|
145
|
+
return dirs + files
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class CommandNameCompleter(Completer):
|
|
149
|
+
def __init__(self, registry):
|
|
150
|
+
self._registry = registry
|
|
151
|
+
|
|
152
|
+
def complete(self, ctx: CompletionContext) -> list[Completion]:
|
|
153
|
+
prefix = ctx.prefix
|
|
154
|
+
results = []
|
|
155
|
+
seen: set[str] = set()
|
|
156
|
+
recipe_names: set[str] = set()
|
|
157
|
+
|
|
158
|
+
for name in sorted(self._registry.list_commands()):
|
|
159
|
+
if name.startswith(prefix):
|
|
160
|
+
cmd = self._registry.get(name)
|
|
161
|
+
if cmd is not None and not cmd.has_any_handler():
|
|
162
|
+
# Handler-less command — a completion recipe for an external
|
|
163
|
+
# system command. Classify as "system" rather than "command".
|
|
164
|
+
recipe_names.add(name)
|
|
165
|
+
continue
|
|
166
|
+
results.append(Completion(value=name, description="command"))
|
|
167
|
+
seen.add(name)
|
|
168
|
+
|
|
169
|
+
if hasattr(self._registry, "list_aliases"):
|
|
170
|
+
for name, expansion in sorted(self._registry.list_aliases().items()):
|
|
171
|
+
if name.startswith(prefix) and name not in seen:
|
|
172
|
+
results.append(Completion(
|
|
173
|
+
value=name, description=f"alias → {expansion}"
|
|
174
|
+
))
|
|
175
|
+
seen.add(name)
|
|
176
|
+
|
|
177
|
+
for cmd in self._find_system_commands(prefix):
|
|
178
|
+
if cmd in seen:
|
|
179
|
+
continue
|
|
180
|
+
results.append(Completion(value=cmd, description="system"))
|
|
181
|
+
seen.add(cmd)
|
|
182
|
+
|
|
183
|
+
# Recipes that don't shadow a real PATH entry still get listed as
|
|
184
|
+
# "system" so the user sees them — uncommon but possible (e.g. recipe
|
|
185
|
+
# for a tool not installed on this host).
|
|
186
|
+
for name in sorted(recipe_names):
|
|
187
|
+
if name not in seen:
|
|
188
|
+
results.append(Completion(value=name, description="system"))
|
|
189
|
+
seen.add(name)
|
|
190
|
+
|
|
191
|
+
for comp in self._find_local_commands(prefix):
|
|
192
|
+
if comp.value not in seen:
|
|
193
|
+
results.append(comp)
|
|
194
|
+
seen.add(comp.value)
|
|
195
|
+
|
|
196
|
+
return results
|
|
197
|
+
|
|
198
|
+
def _find_system_commands(self, prefix: str) -> list[str]:
|
|
199
|
+
if not prefix:
|
|
200
|
+
return []
|
|
201
|
+
seen = set()
|
|
202
|
+
path_dirs = os.environ.get("PATH", "").split(os.pathsep)
|
|
203
|
+
for d in path_dirs:
|
|
204
|
+
try:
|
|
205
|
+
entries = os.listdir(d)
|
|
206
|
+
except OSError:
|
|
207
|
+
continue
|
|
208
|
+
for entry in entries:
|
|
209
|
+
if entry.startswith(prefix) and entry not in seen:
|
|
210
|
+
full = os.path.join(d, entry)
|
|
211
|
+
if os.access(full, os.X_OK):
|
|
212
|
+
seen.add(entry)
|
|
213
|
+
return sorted(seen)
|
|
214
|
+
|
|
215
|
+
def _find_local_commands(self, prefix: str) -> list[Completion]:
|
|
216
|
+
"""Complete runnable paths under the current directory at the command position.
|
|
217
|
+
|
|
218
|
+
Offers two kinds of candidate so a script or tool that lives in the
|
|
219
|
+
working tree — not on ``PATH`` — can be launched by TAB:
|
|
220
|
+
|
|
221
|
+
* **Directories** matching the prefix (with a trailing ``/``), so the
|
|
222
|
+
user can drill toward a nested executable (``scripts/`` → ``scripts/deploy.sh``).
|
|
223
|
+
* **Executable files**, but only when *prefix* already names a path
|
|
224
|
+
(contains ``/`` or starts with ``.``/``~``). A bare executable in
|
|
225
|
+
``.`` must be run as ``./tool`` to actually invoke the local file
|
|
226
|
+
rather than a same-named binary on ``PATH``; offering a bare ``tool``
|
|
227
|
+
value here would insert something that doesn't run what it shows.
|
|
228
|
+
"""
|
|
229
|
+
# A bare TAB at an empty command prompt should list commands, not
|
|
230
|
+
# flood the menu with every directory in the working tree.
|
|
231
|
+
if not prefix:
|
|
232
|
+
return []
|
|
233
|
+
expanded = os.path.expanduser(prefix)
|
|
234
|
+
directory = os.path.dirname(expanded) or "."
|
|
235
|
+
partial = os.path.basename(expanded)
|
|
236
|
+
# Only surface bare executables in the current dir once the user has
|
|
237
|
+
# committed to a path-shaped prefix; otherwise stick to directories.
|
|
238
|
+
want_files = "/" in prefix or prefix.startswith((".", "~"))
|
|
239
|
+
try:
|
|
240
|
+
entries = os.listdir(directory)
|
|
241
|
+
except OSError:
|
|
242
|
+
return []
|
|
243
|
+
dirs: list[Completion] = []
|
|
244
|
+
files: list[Completion] = []
|
|
245
|
+
for entry in sorted(entries):
|
|
246
|
+
if entry.startswith(".") and not partial.startswith("."):
|
|
247
|
+
continue
|
|
248
|
+
if not entry.lower().startswith(partial.lower()):
|
|
249
|
+
continue
|
|
250
|
+
full_path = os.path.join(directory, entry)
|
|
251
|
+
display_dir = os.path.dirname(prefix) if prefix and os.path.dirname(prefix) else ""
|
|
252
|
+
display_path = _to_slash(os.path.join(display_dir, entry)) if display_dir else entry
|
|
253
|
+
if os.path.isdir(full_path):
|
|
254
|
+
dirs.append(Completion(value=display_path + "/", display=entry + "/", description="directory"))
|
|
255
|
+
elif want_files and os.access(full_path, os.X_OK):
|
|
256
|
+
files.append(Completion(value=display_path, display=entry, description="executable"))
|
|
257
|
+
return dirs + files
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class ChoiceCompleter(Completer):
|
|
261
|
+
def __init__(self, choices: list[str]):
|
|
262
|
+
self.choices = choices
|
|
263
|
+
|
|
264
|
+
def complete(self, ctx: CompletionContext) -> list[Completion]:
|
|
265
|
+
return [
|
|
266
|
+
Completion(value=c)
|
|
267
|
+
for c in self.choices
|
|
268
|
+
if c.startswith(ctx.prefix)
|
|
269
|
+
]
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
class CallbackCompleter(Completer):
|
|
273
|
+
"""Completer that calls a function to get the current list of choices."""
|
|
274
|
+
|
|
275
|
+
def __init__(self, func):
|
|
276
|
+
self.func = func
|
|
277
|
+
|
|
278
|
+
def complete(self, ctx: CompletionContext) -> list[Completion]:
|
|
279
|
+
return [
|
|
280
|
+
Completion(value=c)
|
|
281
|
+
for c in self.func()
|
|
282
|
+
if c.startswith(ctx.prefix)
|
|
283
|
+
]
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class HistoryCompleter(Completer):
|
|
287
|
+
"""Completes the typed line from past command lines.
|
|
288
|
+
|
|
289
|
+
Unlike every other completer this one *matches* in line space: an entry is a
|
|
290
|
+
candidate when it starts with ``ctx.line`` (everything before the cursor),
|
|
291
|
+
not merely with ``ctx.prefix``. So ``git commit <TAB>`` can offer the tail
|
|
292
|
+
of a past ``git commit -m "fix typo"`` — a candidate no per-argument
|
|
293
|
+
completer could produce, because it spans several arguments.
|
|
294
|
+
|
|
295
|
+
What it *returns* lives in the same space as every other candidate: the
|
|
296
|
+
value starts at the completion anchor (:func:`parsing.raw_token_start`), so
|
|
297
|
+
the picker shows ``-m "fix typo"`` under the caret rather than repeating the
|
|
298
|
+
``git commit `` the user can already see. Because the tail can span tokens
|
|
299
|
+
and is already shell syntax, candidates are flagged ``verbatim=True`` and the
|
|
300
|
+
editor inserts them without quoting.
|
|
301
|
+
|
|
302
|
+
Candidates are the most recent matches first, deduplicated, capped at
|
|
303
|
+
*limit* so they can never flood the picker. ``history_fn`` is called on
|
|
304
|
+
every keystroke while the picker is open, so it must be cheap — the shell
|
|
305
|
+
passes the current context's in-memory Up/Down list.
|
|
306
|
+
|
|
307
|
+
Candidates are also **scoped to the current directory** when
|
|
308
|
+
``ran_here_fn`` is supplied: it is asked, per entry, whether that line was
|
|
309
|
+
recorded as run in the cwd (the shell passes :meth:`history.History.ran_here`).
|
|
310
|
+
Only those entries are offered, with no fallback — ``make deploy`` from
|
|
311
|
+
another checkout is rarely what you want here, so a directory you have never
|
|
312
|
+
run a matching line in contributes no history rows at all. Up/Down and
|
|
313
|
+
``Ctrl+R`` are still unscoped when you do want to reach across directories.
|
|
314
|
+
"""
|
|
315
|
+
|
|
316
|
+
def __init__(self, history_fn, limit: int = 10, ran_here_fn=None):
|
|
317
|
+
self._history_fn = history_fn
|
|
318
|
+
self.limit = limit
|
|
319
|
+
self._ran_here_fn = ran_here_fn
|
|
320
|
+
|
|
321
|
+
def should_activate(self, ctx: CompletionContext) -> bool:
|
|
322
|
+
# A bare TAB on an empty prompt should list the commands available, not
|
|
323
|
+
# push the last 10 command lines above them. Up/Down and Ctrl+R already
|
|
324
|
+
# cover "show me what I ran" with nothing typed.
|
|
325
|
+
return bool(ctx.line.strip())
|
|
326
|
+
|
|
327
|
+
def complete(self, ctx: CompletionContext) -> list[Completion]:
|
|
328
|
+
if not self.should_activate(ctx):
|
|
329
|
+
return []
|
|
330
|
+
line = ctx.line
|
|
331
|
+
anchor = raw_token_start(line)
|
|
332
|
+
results: list[Completion] = []
|
|
333
|
+
seen: set[str] = set()
|
|
334
|
+
for entry in reversed(self._history_fn()):
|
|
335
|
+
if len(results) >= self.limit:
|
|
336
|
+
break
|
|
337
|
+
if entry in seen:
|
|
338
|
+
continue
|
|
339
|
+
seen.add(entry)
|
|
340
|
+
if not entry.startswith(line):
|
|
341
|
+
continue
|
|
342
|
+
# Nothing left to add (exact match, or the entry only differs by
|
|
343
|
+
# trailing whitespace) — the row would look identical to the line
|
|
344
|
+
# the user is already looking at.
|
|
345
|
+
if not entry[len(line):].strip():
|
|
346
|
+
continue
|
|
347
|
+
# The value is inserted verbatim, so an embedded newline would
|
|
348
|
+
# submit the line on insert. Can't happen today (continuation
|
|
349
|
+
# lines are joined before being stored), but the guard keeps
|
|
350
|
+
# "inserted verbatim" safe by construction.
|
|
351
|
+
if "\n" in entry or "\r" in entry:
|
|
352
|
+
continue
|
|
353
|
+
# Ran somewhere else — out of scope, and no fallback re-admits it.
|
|
354
|
+
if self._ran_here_fn is not None and not self._ran_here_fn(entry):
|
|
355
|
+
continue
|
|
356
|
+
results.append(
|
|
357
|
+
Completion(value=entry[anchor:], description="history", verbatim=True)
|
|
358
|
+
)
|
|
359
|
+
return results
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
class OptionsCompleter(Completer):
|
|
363
|
+
"""Completer for command-line flags with multi-select TUI support.
|
|
364
|
+
|
|
365
|
+
Auto-built from the flag (``-`` / ``+`` prefixed) entries of a command's
|
|
366
|
+
``params`` list, so recipes never construct one directly. An instance
|
|
367
|
+
can be passed via the ``options_completer=`` kwarg on
|
|
368
|
+
:meth:`registry.command` to override the auto-built completer when a
|
|
369
|
+
custom subclass is needed.
|
|
370
|
+
"""
|
|
371
|
+
|
|
372
|
+
def __init__(
|
|
373
|
+
self,
|
|
374
|
+
options: dict[str, str],
|
|
375
|
+
args: dict[str, str | tuple[str, Completer]] | None = None,
|
|
376
|
+
):
|
|
377
|
+
self.options = options
|
|
378
|
+
# args values may be a plain hint string ("N") or a (hint, value_completer)
|
|
379
|
+
# tuple when a specific completer should be used for that flag's value.
|
|
380
|
+
self.args: dict[str, str] = {}
|
|
381
|
+
self._value_completers: dict[str, Completer] = {}
|
|
382
|
+
for flag, spec in (args or {}).items():
|
|
383
|
+
if isinstance(spec, tuple):
|
|
384
|
+
hint, vc = spec
|
|
385
|
+
self.args[flag] = hint
|
|
386
|
+
self._value_completers[flag] = vc
|
|
387
|
+
else:
|
|
388
|
+
self.args[flag] = spec
|
|
389
|
+
|
|
390
|
+
def should_activate(self, ctx: CompletionContext) -> bool:
|
|
391
|
+
return ctx.prefix.startswith(("-", "+"))
|
|
392
|
+
|
|
393
|
+
def complete(self, ctx: CompletionContext) -> list[Completion]:
|
|
394
|
+
prefix = ctx.prefix
|
|
395
|
+
used = self._used_flags(ctx)
|
|
396
|
+
result = []
|
|
397
|
+
# Iterate the union of options and args so that value-taking flags
|
|
398
|
+
# registered only in `args` (without a description in `options`) are
|
|
399
|
+
# still shown as completions.
|
|
400
|
+
all_flags = sorted(set(self.options) | set(self.args))
|
|
401
|
+
for flag in all_flags:
|
|
402
|
+
if not flag.startswith(prefix):
|
|
403
|
+
continue
|
|
404
|
+
if flag in used:
|
|
405
|
+
continue
|
|
406
|
+
desc = self.options.get(flag, "")
|
|
407
|
+
arg_hint = self.args.get(flag, "")
|
|
408
|
+
result.append(Completion(
|
|
409
|
+
value=flag,
|
|
410
|
+
description=desc,
|
|
411
|
+
multi_select=True,
|
|
412
|
+
combinable=(len(flag) == 2 and flag.startswith("-") and not arg_hint),
|
|
413
|
+
arg_hint=arg_hint,
|
|
414
|
+
))
|
|
415
|
+
return result
|
|
416
|
+
|
|
417
|
+
def get_preceding_flag_hint(
|
|
418
|
+
self, ctx: CompletionContext
|
|
419
|
+
) -> tuple[str, str, str, Completer | None] | None:
|
|
420
|
+
"""Return (flag, hint, description, value_completer) if the last completed arg is a value-taking flag.
|
|
421
|
+
|
|
422
|
+
``value_completer`` is a :class:`Completer` when the flag has a registered
|
|
423
|
+
value completer (e.g. ``"-C": ("DIR", DirCompleter())``), otherwise ``None``.
|
|
424
|
+
Returns ``None`` entirely when the preceding arg is not a known value-taking flag.
|
|
425
|
+
"""
|
|
426
|
+
if not ctx.args:
|
|
427
|
+
return None
|
|
428
|
+
last_arg = ctx.args[-1]
|
|
429
|
+
if not last_arg.startswith("-"):
|
|
430
|
+
return None
|
|
431
|
+
hint = self.args.get(last_arg)
|
|
432
|
+
if not hint:
|
|
433
|
+
return None
|
|
434
|
+
description = self.options.get(last_arg, "")
|
|
435
|
+
value_completer = self._value_completers.get(last_arg)
|
|
436
|
+
return (last_arg, hint, description, value_completer)
|
|
437
|
+
|
|
438
|
+
def _used_flags(self, ctx: CompletionContext) -> set[str]:
|
|
439
|
+
"""Return the set of option flags already present in ctx.args."""
|
|
440
|
+
used: set[str] = set()
|
|
441
|
+
for arg in ctx.args:
|
|
442
|
+
if arg.startswith("--"):
|
|
443
|
+
used.add(arg)
|
|
444
|
+
elif arg.startswith("-"):
|
|
445
|
+
# Split short-flag clusters: -hs → {-h, -s}
|
|
446
|
+
for ch in arg[1:]:
|
|
447
|
+
used.add(f"-{ch}")
|
|
448
|
+
elif arg.startswith("+"):
|
|
449
|
+
# +-flags don't cluster — record verbatim.
|
|
450
|
+
used.add(arg)
|
|
451
|
+
return used
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
class ConditionalCompleter(Completer):
|
|
455
|
+
"""Picks a sub-completer based on preceding args."""
|
|
456
|
+
|
|
457
|
+
def __init__(self, mapping: dict[tuple, Completer]):
|
|
458
|
+
self.mapping = mapping
|
|
459
|
+
|
|
460
|
+
def complete(self, ctx: CompletionContext) -> list[Completion]:
|
|
461
|
+
key = tuple(ctx.args)
|
|
462
|
+
completer = self.mapping.get(key)
|
|
463
|
+
if completer:
|
|
464
|
+
return completer.complete(ctx)
|
|
465
|
+
for length in range(len(ctx.args), 0, -1):
|
|
466
|
+
partial_key = tuple(ctx.args[:length])
|
|
467
|
+
if partial_key in self.mapping:
|
|
468
|
+
return self.mapping[partial_key].complete(ctx)
|
|
469
|
+
return []
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
# ---------------------------------------------------------------------------
|
|
473
|
+
# Cobra-protocol fallback
|
|
474
|
+
# ---------------------------------------------------------------------------
|
|
475
|
+
#
|
|
476
|
+
# Most modern Go CLIs (kubectl, helm, gh, argocd, k9s, doctl, linkerd, …) are
|
|
477
|
+
# built on the spf13/cobra framework, which exposes a hidden ``__complete``
|
|
478
|
+
# subcommand. When a tool registers shell completions, cobra inserts a
|
|
479
|
+
# function that re-invokes the tool itself like::
|
|
480
|
+
#
|
|
481
|
+
# $ kubectl __complete get po ""
|
|
482
|
+
# pod retrieve a list of pods
|
|
483
|
+
# pods (alias)
|
|
484
|
+
# poddisruptionbudget
|
|
485
|
+
# poddisruptionbudgets
|
|
486
|
+
# :4 ← directive byte (4 = nospace, 2 = nofiles, …)
|
|
487
|
+
#
|
|
488
|
+
# Lines before the trailing ``:N`` are candidates; each line is
|
|
489
|
+
# ``name\tdescription`` (description optional). This module drives that
|
|
490
|
+
# protocol directly — no bash, no bash-completion script needed.
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
# Sentinel returned by the probe to indicate "not a cobra command".
|
|
494
|
+
_NOT_COBRA = object()
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
class CobraCompleter(Completer):
|
|
498
|
+
"""Fallback completer that calls a tool's hidden ``__complete`` subcommand.
|
|
499
|
+
|
|
500
|
+
Cobra-based CLIs (kubectl, helm, gh, argocd, k9s, doctl, …) ship a
|
|
501
|
+
completion function that's just a wrapper around ``<cmd> __complete``.
|
|
502
|
+
Calling that subcommand directly skips bash entirely, returns richer
|
|
503
|
+
data (descriptions per candidate), and works on any host that has the
|
|
504
|
+
tool itself installed.
|
|
505
|
+
|
|
506
|
+
Per-command detection: on first encounter of a command, we run
|
|
507
|
+
``<cmd> __complete --help`` once and check whether the response looks
|
|
508
|
+
like a cobra completion handler. Result is cached for the rest of the
|
|
509
|
+
shell session.
|
|
510
|
+
"""
|
|
511
|
+
|
|
512
|
+
def __init__(self, *, timeout: float = 1.5) -> None:
|
|
513
|
+
self._timeout = timeout
|
|
514
|
+
# Per-command probe cache: command name → bool.
|
|
515
|
+
# Missing entry means "not yet probed".
|
|
516
|
+
self._is_cobra: dict[str, bool] = {}
|
|
517
|
+
# Per-line completion cache: line → list[(value, description)].
|
|
518
|
+
self._results: dict[str, list[tuple[str, str]]] = {}
|
|
519
|
+
|
|
520
|
+
def should_activate(self, ctx: CompletionContext) -> bool:
|
|
521
|
+
if not ctx.command:
|
|
522
|
+
return False
|
|
523
|
+
# Only activate for commands resolvable on PATH — avoids spawning a
|
|
524
|
+
# subprocess for typos / unknown words.
|
|
525
|
+
if shutil.which(ctx.command) is None:
|
|
526
|
+
return False
|
|
527
|
+
return self._is_cobra_command(ctx.command)
|
|
528
|
+
|
|
529
|
+
def complete(self, ctx: CompletionContext) -> list[Completion]:
|
|
530
|
+
if not ctx.command or not self._is_cobra_command(ctx.command):
|
|
531
|
+
return []
|
|
532
|
+
line = ctx.line
|
|
533
|
+
if line in self._results:
|
|
534
|
+
results = self._results[line]
|
|
535
|
+
else:
|
|
536
|
+
results = self._invoke(ctx.command, ctx.args, ctx.prefix)
|
|
537
|
+
self._results[line] = results
|
|
538
|
+
prefix = ctx.prefix
|
|
539
|
+
return [
|
|
540
|
+
Completion(value=v, description=d)
|
|
541
|
+
for v, d in results
|
|
542
|
+
if v.startswith(prefix)
|
|
543
|
+
]
|
|
544
|
+
|
|
545
|
+
# ── detection ────────────────────────────────────────────────────────
|
|
546
|
+
|
|
547
|
+
def _is_cobra_command(self, command: str) -> bool:
|
|
548
|
+
"""Return True if *command* responds to ``__complete --help`` like cobra.
|
|
549
|
+
|
|
550
|
+
Probes once per command per shell session; result is cached.
|
|
551
|
+
"""
|
|
552
|
+
if command in self._is_cobra:
|
|
553
|
+
return self._is_cobra[command]
|
|
554
|
+
result = self._probe(command)
|
|
555
|
+
self._is_cobra[command] = result
|
|
556
|
+
return result
|
|
557
|
+
|
|
558
|
+
def _probe(self, command: str) -> bool:
|
|
559
|
+
"""One-shot probe: does *command* speak the cobra protocol?"""
|
|
560
|
+
try:
|
|
561
|
+
proc = subprocess.run(
|
|
562
|
+
[command, "__complete", "--help"],
|
|
563
|
+
capture_output=True,
|
|
564
|
+
text=True,
|
|
565
|
+
timeout=self._timeout,
|
|
566
|
+
)
|
|
567
|
+
except (subprocess.TimeoutExpired, OSError):
|
|
568
|
+
return False
|
|
569
|
+
# Cobra's __complete help text contains a recognizable phrase. Both
|
|
570
|
+
# stdout and stderr are checked because cobra writes to stdout but
|
|
571
|
+
# other tools may surface our probe via stderr.
|
|
572
|
+
blob = (proc.stdout or "") + (proc.stderr or "")
|
|
573
|
+
if "shell completion" in blob.lower() or "ShellCompDirective" in blob:
|
|
574
|
+
return True
|
|
575
|
+
# Heuristic fallback: cobra always exits 0 on `__complete --help` and
|
|
576
|
+
# mentions "__complete" itself in the usage line. Many non-cobra
|
|
577
|
+
# tools either error out or emit completely unrelated help text.
|
|
578
|
+
if proc.returncode == 0 and "__complete" in blob:
|
|
579
|
+
return True
|
|
580
|
+
return False
|
|
581
|
+
|
|
582
|
+
# ── invocation ───────────────────────────────────────────────────────
|
|
583
|
+
|
|
584
|
+
def _invoke(
|
|
585
|
+
self, command: str, args: list[str], prefix: str
|
|
586
|
+
) -> list[tuple[str, str]]:
|
|
587
|
+
"""Run ``<cmd> __complete <args> <prefix>``; return [(value, desc), …]."""
|
|
588
|
+
argv = [command, "__complete", *args, prefix]
|
|
589
|
+
try:
|
|
590
|
+
proc = subprocess.run(
|
|
591
|
+
argv,
|
|
592
|
+
capture_output=True,
|
|
593
|
+
text=True,
|
|
594
|
+
timeout=self._timeout,
|
|
595
|
+
)
|
|
596
|
+
except (subprocess.TimeoutExpired, OSError):
|
|
597
|
+
return []
|
|
598
|
+
# Cobra exits 0 on success; some tools may return non-zero when no
|
|
599
|
+
# candidates apply. Treat non-zero as empty.
|
|
600
|
+
if proc.returncode != 0:
|
|
601
|
+
return []
|
|
602
|
+
return _parse_cobra_output(proc.stdout)
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def _parse_cobra_output(stdout: str) -> list[tuple[str, str]]:
|
|
606
|
+
"""Parse cobra ``__complete`` stdout into (value, description) pairs.
|
|
607
|
+
|
|
608
|
+
Format::
|
|
609
|
+
|
|
610
|
+
name\tdescription
|
|
611
|
+
name (description optional)
|
|
612
|
+
:N ← trailing directive byte; ignored
|
|
613
|
+
Completion ended ← optional trailing trace line; ignored
|
|
614
|
+
|
|
615
|
+
Blank lines are dropped.
|
|
616
|
+
"""
|
|
617
|
+
results: list[tuple[str, str]] = []
|
|
618
|
+
for line in stdout.splitlines():
|
|
619
|
+
if not line:
|
|
620
|
+
continue
|
|
621
|
+
# Trailing directive byte — always last non-blank line.
|
|
622
|
+
if line.startswith(":") and line[1:].isdigit():
|
|
623
|
+
continue
|
|
624
|
+
# Some cobra builds append a "Completion ended with directive: …" line.
|
|
625
|
+
if line.startswith("Completion ended"):
|
|
626
|
+
continue
|
|
627
|
+
if "\t" in line:
|
|
628
|
+
value, _, desc = line.partition("\t")
|
|
629
|
+
else:
|
|
630
|
+
value, desc = line, ""
|
|
631
|
+
results.append((value, desc))
|
|
632
|
+
return results
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
# Module-level singleton + enable/disable API. Default: enabled.
|
|
636
|
+
|
|
637
|
+
_cobra_fallback: CobraCompleter | None = None
|
|
638
|
+
_cobra_enabled: bool = True
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def enable_cobra_fallback(*, timeout: float = 1.5) -> CobraCompleter:
|
|
642
|
+
"""Enable the cobra-protocol fallback.
|
|
643
|
+
|
|
644
|
+
Returns the configured :class:`CobraCompleter`. The default state is
|
|
645
|
+
*enabled* — call this only to override the timeout.
|
|
646
|
+
"""
|
|
647
|
+
global _cobra_fallback, _cobra_enabled
|
|
648
|
+
_cobra_fallback = CobraCompleter(timeout=timeout)
|
|
649
|
+
_cobra_enabled = True
|
|
650
|
+
return _cobra_fallback
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def disable_cobra_fallback() -> None:
|
|
654
|
+
"""Disable the cobra-protocol fallback for this session."""
|
|
655
|
+
global _cobra_enabled
|
|
656
|
+
_cobra_enabled = False
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def get_cobra_fallback() -> CobraCompleter | None:
|
|
660
|
+
"""Return the active cobra fallback, or ``None`` if disabled.
|
|
661
|
+
|
|
662
|
+
Lazily initialises on first call.
|
|
663
|
+
"""
|
|
664
|
+
global _cobra_fallback
|
|
665
|
+
if not _cobra_enabled:
|
|
666
|
+
return None
|
|
667
|
+
if _cobra_fallback is None:
|
|
668
|
+
_cobra_fallback = CobraCompleter()
|
|
669
|
+
return _cobra_fallback
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
# ---------------------------------------------------------------------------
|
|
673
|
+
# argcomplete fallback
|
|
674
|
+
# ---------------------------------------------------------------------------
|
|
675
|
+
#
|
|
676
|
+
# argcomplete (https://kislyuk.github.io/argcomplete/) is the de-facto
|
|
677
|
+
# completion library for Python CLIs. Tools that opt in include pipx, conda,
|
|
678
|
+
# pre-commit, tox, pdm, httpie, nox, virtualenv, plus many internal Amazon
|
|
679
|
+
# Python tools.
|
|
680
|
+
#
|
|
681
|
+
# Protocol::
|
|
682
|
+
#
|
|
683
|
+
# _ARGCOMPLETE=1 # enable completion mode
|
|
684
|
+
# _ARGCOMPLETE_IFS=$'\v' # candidate separator (vertical tab)
|
|
685
|
+
# COMP_LINE="<full line>"
|
|
686
|
+
# COMP_POINT="<cursor pos>"
|
|
687
|
+
# <tool> # write candidates to fd 8
|
|
688
|
+
#
|
|
689
|
+
# fd 8 receives the candidate list joined by ``_ARGCOMPLETE_IFS``.
|
|
690
|
+
#
|
|
691
|
+
# Detection MUST be done before invocation because non-argcomplete tools
|
|
692
|
+
# silently ignore the env vars and run normally — invoking ``rm`` or any
|
|
693
|
+
# other side-effecting binary in completion mode would actually run it.
|
|
694
|
+
# We detect by inspecting the executable: it must be a Python script (shim
|
|
695
|
+
# for a setuptools console_script, or a plain script with the marker), and
|
|
696
|
+
# the imported module's first 1024 bytes must contain ``PYTHON_ARGCOMPLETE_OK``.
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
# Script that runs the marker check using the target tool's own Python
|
|
700
|
+
# interpreter — which gives us the right sys.path for finding the imported
|
|
701
|
+
# module without executing the user's package code.
|
|
702
|
+
_ARGCOMPLETE_PROBE_SCRIPT = r"""
|
|
703
|
+
import importlib.util, sys
|
|
704
|
+
mod = sys.argv[1]
|
|
705
|
+
spec = importlib.util.find_spec(mod)
|
|
706
|
+
if spec is None or spec.origin is None:
|
|
707
|
+
sys.exit(2)
|
|
708
|
+
try:
|
|
709
|
+
with open(spec.origin) as f:
|
|
710
|
+
head = f.read(1024)
|
|
711
|
+
except OSError:
|
|
712
|
+
sys.exit(3)
|
|
713
|
+
sys.exit(0 if "PYTHON_ARGCOMPLETE_OK" in head else 1)
|
|
714
|
+
"""
|
|
715
|
+
|
|
716
|
+
import re as _re
|
|
717
|
+
|
|
718
|
+
# Setuptools console_script shim:
|
|
719
|
+
# #!/path/to/python
|
|
720
|
+
# ...
|
|
721
|
+
# from <module> import <func>
|
|
722
|
+
# ...
|
|
723
|
+
# sys.exit(<func>())
|
|
724
|
+
_SHIM_IMPORT_RE = _re.compile(r"^from\s+([\w\.]+)\s+import\s+\w+\s*$", _re.MULTILINE)
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
class ArgcompleteCompleter(Completer):
|
|
728
|
+
"""Fallback completer that drives argcomplete-aware Python CLIs.
|
|
729
|
+
|
|
730
|
+
Detection per command (cached):
|
|
731
|
+
1. The executable on PATH must be readable.
|
|
732
|
+
2. Either the file itself contains ``PYTHON_ARGCOMPLETE_OK`` in its
|
|
733
|
+
first 1024 bytes, OR it's a setuptools console_script shim and
|
|
734
|
+
the imported module's first 1024 bytes contain the marker.
|
|
735
|
+
|
|
736
|
+
On a hit, completion runs ``<tool>`` in argcomplete mode with fd 8
|
|
737
|
+
captured; candidates come back joined by ``_ARGCOMPLETE_IFS``.
|
|
738
|
+
|
|
739
|
+
Returns ``Completion(value=..., description="")`` — argcomplete does
|
|
740
|
+
support descriptions but only with a separate, less stable wire
|
|
741
|
+
format; we ignore those for now.
|
|
742
|
+
"""
|
|
743
|
+
|
|
744
|
+
_IFS = "\v"
|
|
745
|
+
|
|
746
|
+
def __init__(self, *, timeout: float = 2.0) -> None:
|
|
747
|
+
self._timeout = timeout
|
|
748
|
+
# Per-command probe cache: command name → bool.
|
|
749
|
+
self._is_argcomplete: dict[str, bool] = {}
|
|
750
|
+
# Per-line completion cache: line → list[str].
|
|
751
|
+
self._results: dict[str, list[str]] = {}
|
|
752
|
+
|
|
753
|
+
def should_activate(self, ctx: CompletionContext) -> bool:
|
|
754
|
+
if not ctx.command:
|
|
755
|
+
return False
|
|
756
|
+
if shutil.which(ctx.command) is None:
|
|
757
|
+
return False
|
|
758
|
+
return self._is_argcomplete_command(ctx.command)
|
|
759
|
+
|
|
760
|
+
def complete(self, ctx: CompletionContext) -> list[Completion]:
|
|
761
|
+
if not ctx.command or not self._is_argcomplete_command(ctx.command):
|
|
762
|
+
return []
|
|
763
|
+
line = ctx.line
|
|
764
|
+
if line in self._results:
|
|
765
|
+
words = self._results[line]
|
|
766
|
+
else:
|
|
767
|
+
words = self._invoke(ctx.command, line)
|
|
768
|
+
self._results[line] = words
|
|
769
|
+
prefix = ctx.prefix
|
|
770
|
+
return [Completion(value=w) for w in words if w.startswith(prefix)]
|
|
771
|
+
|
|
772
|
+
# ── detection ────────────────────────────────────────────────────────
|
|
773
|
+
|
|
774
|
+
def _is_argcomplete_command(self, command: str) -> bool:
|
|
775
|
+
if command in self._is_argcomplete:
|
|
776
|
+
return self._is_argcomplete[command]
|
|
777
|
+
result = self._probe(command)
|
|
778
|
+
self._is_argcomplete[command] = result
|
|
779
|
+
return result
|
|
780
|
+
|
|
781
|
+
def _probe(self, command: str) -> bool:
|
|
782
|
+
"""Inspect the executable for the argcomplete marker."""
|
|
783
|
+
path = shutil.which(command)
|
|
784
|
+
if path is None:
|
|
785
|
+
return False
|
|
786
|
+
try:
|
|
787
|
+
# Read as bytes — many executables on PATH are binaries (ls,
|
|
788
|
+
# grep, …) and decoding them as text would raise. We only need
|
|
789
|
+
# to find an ASCII marker so bytes-level scanning is fine.
|
|
790
|
+
with open(path, "rb") as f:
|
|
791
|
+
head_bytes = f.read(2048)
|
|
792
|
+
except OSError:
|
|
793
|
+
return False
|
|
794
|
+
# If the file isn't text-decodable as UTF-8, it can't be a Python
|
|
795
|
+
# script (or its shim) — it's a compiled binary.
|
|
796
|
+
try:
|
|
797
|
+
head = head_bytes.decode("utf-8")
|
|
798
|
+
except UnicodeDecodeError:
|
|
799
|
+
return False
|
|
800
|
+
|
|
801
|
+
# Marker present directly in the script (plain Python script that
|
|
802
|
+
# opted in via ``# PYTHON_ARGCOMPLETE_OK``).
|
|
803
|
+
if "PYTHON_ARGCOMPLETE_OK" in head:
|
|
804
|
+
return True
|
|
805
|
+
|
|
806
|
+
# Setuptools console_script shim — locate the imported module and
|
|
807
|
+
# check it. Bail if the shebang doesn't point at a python interpreter.
|
|
808
|
+
first_line = head.split("\n", 1)[0]
|
|
809
|
+
if not first_line.startswith("#!") or "py" not in first_line.lower():
|
|
810
|
+
return False
|
|
811
|
+
python_path = first_line[2:].strip().split()[0]
|
|
812
|
+
if not os.path.isfile(python_path):
|
|
813
|
+
return False
|
|
814
|
+
|
|
815
|
+
match = _SHIM_IMPORT_RE.search(head)
|
|
816
|
+
if not match:
|
|
817
|
+
return False
|
|
818
|
+
module = match.group(1)
|
|
819
|
+
|
|
820
|
+
try:
|
|
821
|
+
proc = subprocess.run(
|
|
822
|
+
[python_path, "-c", _ARGCOMPLETE_PROBE_SCRIPT, module],
|
|
823
|
+
capture_output=True,
|
|
824
|
+
text=True,
|
|
825
|
+
timeout=self._timeout,
|
|
826
|
+
)
|
|
827
|
+
except (subprocess.TimeoutExpired, OSError):
|
|
828
|
+
return False
|
|
829
|
+
return proc.returncode == 0
|
|
830
|
+
|
|
831
|
+
# ── invocation ───────────────────────────────────────────────────────
|
|
832
|
+
|
|
833
|
+
def _invoke(self, command: str, line: str) -> list[str]:
|
|
834
|
+
"""Run *command* in argcomplete mode, capture candidates from fd 8.
|
|
835
|
+
|
|
836
|
+
argcomplete writes candidates to fd 8 specifically (debug output
|
|
837
|
+
goes to fd 9). We allocate a pipe, move its write end onto parent
|
|
838
|
+
fd 8 via ``dup2``, then pass fd 8 to the child via ``pass_fds``.
|
|
839
|
+
The child inherits fd 8 pointing to the pipe; argcomplete writes
|
|
840
|
+
candidates there; we read them back from the pipe's read end.
|
|
841
|
+
"""
|
|
842
|
+
env = dict(os.environ)
|
|
843
|
+
env["_ARGCOMPLETE"] = "1"
|
|
844
|
+
env["_ARGCOMPLETE_IFS"] = self._IFS
|
|
845
|
+
env["_ARGCOMPLETE_SHELL"] = "bash"
|
|
846
|
+
env["_ARGCOMPLETE_SUPPRESS_SPACE"] = "1"
|
|
847
|
+
env["COMP_LINE"] = line
|
|
848
|
+
env["COMP_POINT"] = str(len(line.encode("utf-8")))
|
|
849
|
+
env["COMP_TYPE"] = "9" # 9 = TAB
|
|
850
|
+
|
|
851
|
+
try:
|
|
852
|
+
r_fd, w_fd = os.pipe()
|
|
853
|
+
except OSError:
|
|
854
|
+
return []
|
|
855
|
+
|
|
856
|
+
# Snapshot whatever was on parent fd 8 before we clobber it (rare
|
|
857
|
+
# but possible). We restore it after Popen returns.
|
|
858
|
+
saved_fd8 = -1
|
|
859
|
+
try:
|
|
860
|
+
saved_fd8 = os.dup(8)
|
|
861
|
+
except OSError:
|
|
862
|
+
saved_fd8 = -1 # fd 8 wasn't open; nothing to restore
|
|
863
|
+
|
|
864
|
+
try:
|
|
865
|
+
os.dup2(w_fd, 8)
|
|
866
|
+
os.close(w_fd)
|
|
867
|
+
w_fd = -1
|
|
868
|
+
try:
|
|
869
|
+
proc = subprocess.Popen(
|
|
870
|
+
[command],
|
|
871
|
+
env=env,
|
|
872
|
+
stdin=subprocess.DEVNULL,
|
|
873
|
+
stdout=subprocess.DEVNULL,
|
|
874
|
+
stderr=subprocess.DEVNULL,
|
|
875
|
+
pass_fds=(8,),
|
|
876
|
+
)
|
|
877
|
+
except (OSError, ValueError):
|
|
878
|
+
os.close(r_fd)
|
|
879
|
+
return []
|
|
880
|
+
finally:
|
|
881
|
+
# Restore parent fd 8 (or close it if it wasn't open before).
|
|
882
|
+
if saved_fd8 >= 0:
|
|
883
|
+
try:
|
|
884
|
+
os.dup2(saved_fd8, 8)
|
|
885
|
+
os.close(saved_fd8)
|
|
886
|
+
except OSError:
|
|
887
|
+
pass
|
|
888
|
+
else:
|
|
889
|
+
try:
|
|
890
|
+
os.close(8)
|
|
891
|
+
except OSError:
|
|
892
|
+
pass
|
|
893
|
+
|
|
894
|
+
chunks: list[bytes] = []
|
|
895
|
+
try:
|
|
896
|
+
proc.wait(timeout=self._timeout)
|
|
897
|
+
except subprocess.TimeoutExpired:
|
|
898
|
+
proc.kill()
|
|
899
|
+
proc.wait(timeout=1.0)
|
|
900
|
+
os.close(r_fd)
|
|
901
|
+
return []
|
|
902
|
+
|
|
903
|
+
while True:
|
|
904
|
+
try:
|
|
905
|
+
chunk = os.read(r_fd, 4096)
|
|
906
|
+
except OSError:
|
|
907
|
+
break
|
|
908
|
+
if not chunk:
|
|
909
|
+
break
|
|
910
|
+
chunks.append(chunk)
|
|
911
|
+
os.close(r_fd)
|
|
912
|
+
|
|
913
|
+
if proc.returncode != 0:
|
|
914
|
+
return []
|
|
915
|
+
raw = b"".join(chunks).decode("utf-8", errors="replace")
|
|
916
|
+
# argcomplete joins candidates with _IFS; trailing IFS is normal.
|
|
917
|
+
words = [w for w in raw.split(self._IFS) if w]
|
|
918
|
+
return words
|
|
919
|
+
|
|
920
|
+
|
|
921
|
+
# Module-level singleton + enable/disable API.
|
|
922
|
+
|
|
923
|
+
_argcomplete_fallback: ArgcompleteCompleter | None = None
|
|
924
|
+
_argcomplete_enabled: bool = True
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
def enable_argcomplete_fallback(*, timeout: float = 2.0) -> ArgcompleteCompleter:
|
|
928
|
+
"""Enable the argcomplete fallback.
|
|
929
|
+
|
|
930
|
+
Returns the configured :class:`ArgcompleteCompleter`. The default
|
|
931
|
+
state is *enabled* — call this only to override the timeout.
|
|
932
|
+
"""
|
|
933
|
+
global _argcomplete_fallback, _argcomplete_enabled
|
|
934
|
+
_argcomplete_fallback = ArgcompleteCompleter(timeout=timeout)
|
|
935
|
+
_argcomplete_enabled = True
|
|
936
|
+
return _argcomplete_fallback
|
|
937
|
+
|
|
938
|
+
|
|
939
|
+
def disable_argcomplete_fallback() -> None:
|
|
940
|
+
"""Disable the argcomplete fallback for this session."""
|
|
941
|
+
global _argcomplete_enabled
|
|
942
|
+
_argcomplete_enabled = False
|
|
943
|
+
|
|
944
|
+
|
|
945
|
+
def get_argcomplete_fallback() -> ArgcompleteCompleter | None:
|
|
946
|
+
"""Return the active argcomplete fallback, or ``None`` if disabled."""
|
|
947
|
+
global _argcomplete_fallback
|
|
948
|
+
if not _argcomplete_enabled:
|
|
949
|
+
return None
|
|
950
|
+
if _argcomplete_fallback is None:
|
|
951
|
+
_argcomplete_fallback = ArgcompleteCompleter()
|
|
952
|
+
return _argcomplete_fallback
|