contree-cli 0.9.0__tar.gz → 0.9.3__tar.gz
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.
- {contree_cli-0.9.0 → contree_cli-0.9.3}/PKG-INFO +2 -2
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/__main__.py +20 -5
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/agent.md +10 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/arguments.py +5 -1
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/auth.py +9 -6
- contree_cli-0.9.3/contree_cli/cli/grep.py +287 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/operation.py +63 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/run.py +353 -203
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/session.py +3 -3
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/show.py +24 -15
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/skill.py +7 -4
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/config.py +7 -1
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/manual.md +9 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/output.py +109 -33
- contree_cli-0.9.3/contree_cli/pty_utils.py +202 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/shell/argmap.py +2 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/skill.py +3 -2
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/skill_body.md +15 -2
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/types.py +55 -0
- contree_cli-0.9.3/pyproject.toml +93 -0
- contree_cli-0.9.0/pyproject.toml → contree_cli-0.9.3/pyproject.toml.orig +2 -2
- {contree_cli-0.9.0 → contree_cli-0.9.3}/LICENSE +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/README.md +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/__init__.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/__init__.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/agent.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/build.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/cat.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/cd.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/cp.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/env.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/export.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/file.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/images.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/ls.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/tag.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/cli/use.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/client.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/__init__.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/context.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/dockerignore.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/keyword.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/kw_add.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/kw_arg.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/kw_copy.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/kw_env.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/kw_from.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/kw_run.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/kw_skipped.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/kw_user.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/kw_workdir.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/local_context.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/parser.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/docker/url_fetch.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/log.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/man.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/mapped_file.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/migrations.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/py.typed +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/refs.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/session.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/shell/__init__.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/shell/argspec.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/shell/cache.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/shell/completer.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/shell/history.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/shell/parser.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/shell/repl.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/shell/sources.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/shell/trie.py +0 -0
- {contree_cli-0.9.0 → contree_cli-0.9.3}/contree_cli/update_check.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.3
|
|
2
2
|
Name: contree-cli
|
|
3
|
-
Version: 0.9.
|
|
3
|
+
Version: 0.9.3
|
|
4
4
|
Summary: CLI client for the ConTree sandbox platform
|
|
5
5
|
Keywords: sandbox,cli,vm,ai-agent,contree
|
|
6
6
|
Author: Dmitry Orlov
|
|
@@ -197,7 +197,7 @@ Classifier: Programming Language :: Python :: 3.14
|
|
|
197
197
|
Classifier: Topic :: Software Development :: Build Tools
|
|
198
198
|
Classifier: Topic :: System :: Shells
|
|
199
199
|
Classifier: Typing :: Typed
|
|
200
|
-
Requires-Dist: contree-client>=0.1
|
|
200
|
+
Requires-Dist: contree-client>=0.2.1
|
|
201
201
|
Requires-Python: >=3.10
|
|
202
202
|
Project-URL: Homepage, https://contree.dev
|
|
203
203
|
Project-URL: Documentation, https://docs.contree.dev/cli/
|
|
@@ -26,17 +26,17 @@ log = logging.getLogger(__name__)
|
|
|
26
26
|
# the backend instead of `requests` (whose exceptions do subclass
|
|
27
27
|
# OSError). Both imports are optional, mirroring how
|
|
28
28
|
# contree_client.sync.detect_backend() itself probes for them.
|
|
29
|
-
|
|
29
|
+
NETWORK_ERRORS: tuple[type[BaseException], ...] = (OSError, http.client.HTTPException)
|
|
30
30
|
try:
|
|
31
31
|
import urllib3.exceptions # type: ignore[import-not-found]
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
NETWORK_ERRORS = (*NETWORK_ERRORS, urllib3.exceptions.HTTPError)
|
|
34
34
|
except ModuleNotFoundError:
|
|
35
35
|
pass
|
|
36
36
|
try:
|
|
37
37
|
import httpx # type: ignore[import-not-found]
|
|
38
38
|
|
|
39
|
-
|
|
39
|
+
NETWORK_ERRORS = (*NETWORK_ERRORS, httpx.HTTPError)
|
|
40
40
|
except ModuleNotFoundError:
|
|
41
41
|
pass
|
|
42
42
|
|
|
@@ -108,7 +108,17 @@ def main() -> None:
|
|
|
108
108
|
CLIENT.set(stack.enter_context(client))
|
|
109
109
|
|
|
110
110
|
formatter = FORMATTERS[args.output_format]()
|
|
111
|
-
|
|
111
|
+
|
|
112
|
+
def close_formatter() -> None:
|
|
113
|
+
# A closed stdout (e.g. piping into `less` and quitting
|
|
114
|
+
# early) can make this final flush itself raise
|
|
115
|
+
# BrokenPipeError -- the handler's own _NETWORK_ERRORS catch
|
|
116
|
+
# already reported and exited by the time this callback
|
|
117
|
+
# runs, so a second traceback here would just be noise.
|
|
118
|
+
with suppress(BrokenPipeError):
|
|
119
|
+
formatter.close()
|
|
120
|
+
|
|
121
|
+
stack.callback(close_formatter)
|
|
112
122
|
|
|
113
123
|
session_key = get_session_key(profile.name, override=args.session_key)
|
|
114
124
|
db_path = config_mod.session_db_path(profile.name)
|
|
@@ -132,7 +142,12 @@ def main() -> None:
|
|
|
132
142
|
# (invalid UUIDs, etc.); the message is already user-facing.
|
|
133
143
|
log.error("%s", exc)
|
|
134
144
|
exit(1)
|
|
135
|
-
except
|
|
145
|
+
except BrokenPipeError:
|
|
146
|
+
# Reader closed its end of the pipe (e.g. `| head`, `| less`
|
|
147
|
+
# and quit) -- not a network error, exit with the SIGPIPE
|
|
148
|
+
# convention instead of logging a misleading message.
|
|
149
|
+
exit(141)
|
|
150
|
+
except NETWORK_ERRORS as exc:
|
|
136
151
|
log.error("Network error: %s", exc)
|
|
137
152
|
exit(1)
|
|
138
153
|
except KeyboardInterrupt:
|
|
@@ -18,6 +18,7 @@ Agent protocol — follow this sequence for every task:
|
|
|
18
18
|
4. Inspect first (read-only):
|
|
19
19
|
contree ls /path
|
|
20
20
|
contree cat /path/file
|
|
21
|
+
contree grep PATTERN /path
|
|
21
22
|
contree export /path -F subtree.tar.gz
|
|
22
23
|
contree images --prefix=...
|
|
23
24
|
contree session show
|
|
@@ -236,6 +237,15 @@ Piped stdin:
|
|
|
236
237
|
echo 'uname -a' | contree run /bin/sh
|
|
237
238
|
cat deploy.sh | contree run /bin/sh
|
|
238
239
|
|
|
240
|
+
Stdin (including a large piped file) is read and forwarded in the
|
|
241
|
+
background in chunks, not buffered in full before sending. A detached
|
|
242
|
+
run's -d doesn't return until all of local stdin has been sent.
|
|
243
|
+
|
|
244
|
+
Signal handling:
|
|
245
|
+
Ctrl-C during a foreground run sends SIGINT to the sandboxed process
|
|
246
|
+
first and keeps streaming its remaining output. A second Ctrl-C, or a
|
|
247
|
+
failure to deliver the first signal, cancels the whole operation.
|
|
248
|
+
|
|
239
249
|
Detached mode (-d):
|
|
240
250
|
contree run -d -- long-running-task
|
|
241
251
|
contree ps check status
|
|
@@ -13,6 +13,7 @@ from contree_cli.cli import (
|
|
|
13
13
|
env,
|
|
14
14
|
export,
|
|
15
15
|
file,
|
|
16
|
+
grep,
|
|
16
17
|
images,
|
|
17
18
|
ls,
|
|
18
19
|
operation,
|
|
@@ -51,6 +52,7 @@ examples:
|
|
|
51
52
|
contree tag IMAGE_UUID latest
|
|
52
53
|
contree ls /etc list files in session image
|
|
53
54
|
contree cat /etc/os-release show file from session image
|
|
55
|
+
contree grep TODO /app search file contents in session image
|
|
54
56
|
contree auth save token (secure prompt)
|
|
55
57
|
contree auth switch staging
|
|
56
58
|
contree man user manual
|
|
@@ -68,7 +70,8 @@ before running tasks:
|
|
|
68
70
|
ensure auth exists; if missing/invalid, ask user to run `contree auth`
|
|
69
71
|
|
|
70
72
|
high-signal read-only commands:
|
|
71
|
-
contree images | ps | show UUID | ls [PATH] | cat PATH
|
|
73
|
+
contree images | ps | show UUID | ls [PATH] | cat PATH
|
|
74
|
+
contree grep PATTERN [PATH] | session | session show
|
|
72
75
|
|
|
73
76
|
mutating commands (change remote or local session state):
|
|
74
77
|
contree use IMAGE | run -- CMD | file edit PATH | file cp SRC DEST
|
|
@@ -235,6 +238,7 @@ register(
|
|
|
235
238
|
)
|
|
236
239
|
register("ls", "List files in image", ls.setup_parser)
|
|
237
240
|
register("cat", "Show file content from image", cat.setup_parser)
|
|
241
|
+
register("grep", "Search file contents in image", grep.setup_parser)
|
|
238
242
|
register("cp", "Copy file from image to local path", cp.setup_parser)
|
|
239
243
|
register("export", "Export image rootfs or a subtree as tar.gz", export.setup_parser)
|
|
240
244
|
register("file", "Manage files in session image", file.setup_parser, aliases=["f"])
|
|
@@ -43,7 +43,7 @@ from contree_cli.config import (
|
|
|
43
43
|
Config,
|
|
44
44
|
Profile,
|
|
45
45
|
)
|
|
46
|
-
from contree_cli.types import FLAGS
|
|
46
|
+
from contree_cli.types import FLAGS, ask
|
|
47
47
|
|
|
48
48
|
logger = logging.getLogger(__name__)
|
|
49
49
|
PROFILE_CHECK_TIMEOUT = 2.0
|
|
@@ -208,10 +208,13 @@ def cmd_auth(args: AuthArgs) -> int | None:
|
|
|
208
208
|
)
|
|
209
209
|
|
|
210
210
|
if exists and not args.force:
|
|
211
|
-
answer =
|
|
212
|
-
f"Profile {args.profile!r} already exists. Overwrite?
|
|
211
|
+
answer = ask(
|
|
212
|
+
f"Profile {args.profile!r} already exists. Overwrite?",
|
|
213
|
+
"y",
|
|
214
|
+
"n",
|
|
215
|
+
default="n",
|
|
213
216
|
)
|
|
214
|
-
if answer
|
|
217
|
+
if answer != "y":
|
|
215
218
|
print("Aborted.")
|
|
216
219
|
return 1
|
|
217
220
|
|
|
@@ -363,8 +366,8 @@ def cmd_remove(args: RemoveArgs) -> int | None:
|
|
|
363
366
|
logger.error("Profile %r does not exist", args.profile_name)
|
|
364
367
|
return 1
|
|
365
368
|
if not args.force:
|
|
366
|
-
answer =
|
|
367
|
-
if answer
|
|
369
|
+
answer = ask(f"Remove profile {args.profile_name!r}?", "y", "n", default="n")
|
|
370
|
+
if answer != "y":
|
|
368
371
|
print("Aborted.")
|
|
369
372
|
return 1
|
|
370
373
|
del cfg[args.profile_name]
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Search file contents in the session image.
|
|
2
|
+
|
|
3
|
+
Uses the /inspect/ API (server-side ripgrep) to search file contents
|
|
4
|
+
without spawning an instance. Defaults to the session working directory
|
|
5
|
+
(set via `cd`) when PATH is omitted -- pass `/` explicitly to search the
|
|
6
|
+
whole image. PATH may be repeated to search multiple roots in one call.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import sys
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any, Literal
|
|
17
|
+
|
|
18
|
+
from contree_cli import CLIENT, FORMATTER, SESSION_STORE, ArgumentsProtocol, SetupResult
|
|
19
|
+
from contree_cli.output import DefaultFormatter
|
|
20
|
+
from contree_cli.types import (
|
|
21
|
+
FLAGS,
|
|
22
|
+
STDOUT_IS_A_TTY,
|
|
23
|
+
Colors,
|
|
24
|
+
context_lines,
|
|
25
|
+
positive_int,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
EPILOG = """\
|
|
31
|
+
for coding agents:
|
|
32
|
+
read-only command (inspect API, no instance spawn)
|
|
33
|
+
defaults to session cwd when PATH is omitted; pass / to search whole image
|
|
34
|
+
exit code 1 means zero matches (like POSIX grep), not an error
|
|
35
|
+
exit code 2 means the search was truncated before finding anything --
|
|
36
|
+
inconclusive, not confirmed zero matches
|
|
37
|
+
default format prints classic PATH:LINE:TEXT; use -o json/csv/... for rows
|
|
38
|
+
use --raw to preserve submatches/patterns/truncated as JSON
|
|
39
|
+
-A/-B/--context add ripgrep-side context lines (server-computed, not local)
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
CaseLiteral = Literal["sensitive", "insensitive", "smart"]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class GrepArgs(ArgumentsProtocol):
|
|
47
|
+
pattern: str
|
|
48
|
+
path: tuple[str, ...]
|
|
49
|
+
glob: str | None = None
|
|
50
|
+
max_count: int | None = None
|
|
51
|
+
max_total: int | None = None
|
|
52
|
+
case: CaseLiteral | None = None
|
|
53
|
+
raw: bool = False
|
|
54
|
+
before_context: int | None = None
|
|
55
|
+
after_context: int | None = None
|
|
56
|
+
context: int | None = None
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def from_args(cls, ns: argparse.Namespace) -> GrepArgs:
|
|
60
|
+
return cls(
|
|
61
|
+
pattern=ns.pattern,
|
|
62
|
+
path=tuple(ns.path),
|
|
63
|
+
glob=ns.glob,
|
|
64
|
+
max_count=ns.max_count,
|
|
65
|
+
max_total=ns.max_total,
|
|
66
|
+
case=ns.case,
|
|
67
|
+
raw=ns.raw,
|
|
68
|
+
before_context=ns.before_context,
|
|
69
|
+
after_context=ns.after_context,
|
|
70
|
+
context=ns.context,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def before(self) -> int | None:
|
|
74
|
+
return self.before_context if self.before_context is not None else self.context
|
|
75
|
+
|
|
76
|
+
def after(self) -> int | None:
|
|
77
|
+
return self.after_context if self.after_context is not None else self.context
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def setup_parser(p: argparse.ArgumentParser) -> SetupResult:
|
|
81
|
+
p.add_argument("pattern", help="Regex pattern to search for (Rust regex syntax)")
|
|
82
|
+
p.add_argument(
|
|
83
|
+
"path",
|
|
84
|
+
nargs="*",
|
|
85
|
+
help=(
|
|
86
|
+
"File(s)/directory(ies) inside image (defaults to session cwd);"
|
|
87
|
+
" may be repeated to search multiple roots"
|
|
88
|
+
),
|
|
89
|
+
)
|
|
90
|
+
p.add_argument(
|
|
91
|
+
*FLAGS["glob"],
|
|
92
|
+
default=None,
|
|
93
|
+
help="Restrict search to files matching this glob (e.g. '*.py')",
|
|
94
|
+
)
|
|
95
|
+
p.add_argument(
|
|
96
|
+
*FLAGS["max_count"],
|
|
97
|
+
type=positive_int,
|
|
98
|
+
default=None,
|
|
99
|
+
help="Stop after this many matches per file",
|
|
100
|
+
)
|
|
101
|
+
p.add_argument(
|
|
102
|
+
*FLAGS["max_total"],
|
|
103
|
+
type=positive_int,
|
|
104
|
+
default=None,
|
|
105
|
+
help="Stop after this many matches total (server default: 1000)",
|
|
106
|
+
)
|
|
107
|
+
p.add_argument(
|
|
108
|
+
*FLAGS["case"],
|
|
109
|
+
choices=("sensitive", "insensitive", "smart"),
|
|
110
|
+
default=None,
|
|
111
|
+
help="Case sensitivity (default: sensitive)",
|
|
112
|
+
)
|
|
113
|
+
p.add_argument(
|
|
114
|
+
*FLAGS["before_context"],
|
|
115
|
+
type=context_lines,
|
|
116
|
+
default=None,
|
|
117
|
+
metavar="NUM",
|
|
118
|
+
help="Show NUM lines of context before each match (max 50)",
|
|
119
|
+
)
|
|
120
|
+
p.add_argument(
|
|
121
|
+
*FLAGS["after_context"],
|
|
122
|
+
type=context_lines,
|
|
123
|
+
default=None,
|
|
124
|
+
metavar="NUM",
|
|
125
|
+
help="Show NUM lines of context after each match (max 50)",
|
|
126
|
+
)
|
|
127
|
+
p.add_argument(
|
|
128
|
+
# -C is grep's own long-standing flag for this; registering it
|
|
129
|
+
# in the shared FLAGS map would collide with run's --cwd, so
|
|
130
|
+
# it's added here directly as a one-off exception for grep/
|
|
131
|
+
# POSIX compatibility instead of going through FLAGS.
|
|
132
|
+
"-C",
|
|
133
|
+
*FLAGS["context"],
|
|
134
|
+
type=context_lines,
|
|
135
|
+
default=None,
|
|
136
|
+
metavar="NUM",
|
|
137
|
+
help="Show NUM lines of context before and after (overridden by -A/-B)",
|
|
138
|
+
)
|
|
139
|
+
p.add_argument(
|
|
140
|
+
*FLAGS["raw"],
|
|
141
|
+
action="store_true",
|
|
142
|
+
help="Print raw JSON (preserves submatches/patterns/truncated)",
|
|
143
|
+
)
|
|
144
|
+
return cmd_grep, GrepArgs
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def colorize(color: Colors, text: str) -> str:
|
|
148
|
+
"""Wrap *text* in *color*'s raw ANSI codes, unconditionally.
|
|
149
|
+
|
|
150
|
+
``Colors.__call__`` gates on ``contree_cli.types.IS_A_TTY``, which
|
|
151
|
+
is derived from *stderr*'s TTY-ness -- the wrong signal for content
|
|
152
|
+
written to stdout (e.g. stderr redirected but stdout still a
|
|
153
|
+
terminal). Callers here already gate on ``STDOUT_IS_A_TTY``
|
|
154
|
+
themselves, so this bypasses that stderr-based check entirely.
|
|
155
|
+
"""
|
|
156
|
+
return f"{color.value}{text}{Colors.DEFAULT.value}"
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def highlight_match(line_text: str, submatches: list[dict[str, Any]]) -> str:
|
|
160
|
+
"""Wrap each submatch span in bold red, like `grep --color`.
|
|
161
|
+
|
|
162
|
+
Submatch offsets are byte offsets (ripgrep operates on raw bytes),
|
|
163
|
+
so slicing happens on the UTF-8 encoded line to stay correctly
|
|
164
|
+
aligned with multi-byte characters. When the source file had
|
|
165
|
+
invalid UTF-8, the server lossily decodes it and ``line_text``
|
|
166
|
+
contains U+FFFD replacement characters -- those don't round-trip
|
|
167
|
+
to the same byte length as the original input the offsets refer
|
|
168
|
+
to, so re-encoding here would slice at the wrong points. Skip
|
|
169
|
+
highlighting entirely in that case; the caller still prints the
|
|
170
|
+
line as-is.
|
|
171
|
+
"""
|
|
172
|
+
if "\ufffd" in line_text:
|
|
173
|
+
return line_text
|
|
174
|
+
data = line_text.encode("utf-8", errors="surrogateescape")
|
|
175
|
+
parts: list[str] = []
|
|
176
|
+
pos = 0
|
|
177
|
+
for sub in sorted(submatches, key=lambda s: int(s["start"])):
|
|
178
|
+
start, end = int(sub["start"]), int(sub["end"])
|
|
179
|
+
if start < pos or start >= len(data):
|
|
180
|
+
continue # out-of-order/out-of-range offsets -- skip defensively
|
|
181
|
+
end = min(end, len(data))
|
|
182
|
+
parts.append(data[pos:start].decode("utf-8", errors="replace"))
|
|
183
|
+
parts.append(
|
|
184
|
+
colorize(Colors.BOLD_RED, data[start:end].decode("utf-8", errors="replace"))
|
|
185
|
+
)
|
|
186
|
+
pos = end
|
|
187
|
+
parts.append(data[pos:].decode("utf-8", errors="replace"))
|
|
188
|
+
return "".join(parts)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def write_grep_lines(matches: list[dict[str, Any]], *, with_context: bool) -> None:
|
|
192
|
+
"""Print matches in classic grep format: `path:line:text` for an
|
|
193
|
+
actual match, `path-line-text` for a `-A`/`-B`/`--context` line.
|
|
194
|
+
|
|
195
|
+
A `--` separator is inserted between output groups whenever
|
|
196
|
+
`with_context` is set and the next row isn't the immediate
|
|
197
|
+
successor (same path, consecutive line number) of the previous
|
|
198
|
+
one -- exactly like GNU grep/ripgrep only ever show `--` when
|
|
199
|
+
context lines are in play.
|
|
200
|
+
"""
|
|
201
|
+
prev_path: str | None = None
|
|
202
|
+
prev_line: int | None = None
|
|
203
|
+
for match in matches:
|
|
204
|
+
row_path, row_line = match["path"], match["line_number"]
|
|
205
|
+
contiguous = (
|
|
206
|
+
prev_path == row_path
|
|
207
|
+
and prev_line is not None
|
|
208
|
+
and (row_line == prev_line + 1)
|
|
209
|
+
)
|
|
210
|
+
if with_context and prev_path is not None and not contiguous:
|
|
211
|
+
sys.stdout.write("--\n")
|
|
212
|
+
|
|
213
|
+
sep = ":" if match["type"] == "match" else "-"
|
|
214
|
+
line_text = match["line_text"].rstrip("\r\n")
|
|
215
|
+
path_field, line_field = row_path, str(row_line)
|
|
216
|
+
if STDOUT_IS_A_TTY:
|
|
217
|
+
line_text = highlight_match(line_text, match["submatches"])
|
|
218
|
+
path_field = colorize(Colors.MAGENTA, row_path)
|
|
219
|
+
line_field = colorize(Colors.GREEN, line_field)
|
|
220
|
+
sys.stdout.write(f"{path_field}{sep}{line_field}{sep}{line_text}\n")
|
|
221
|
+
|
|
222
|
+
prev_path, prev_line = row_path, row_line
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def cmd_grep(args: GrepArgs) -> int | None:
|
|
226
|
+
client = CLIENT.get()
|
|
227
|
+
formatter = FORMATTER.get()
|
|
228
|
+
formatter.configure(tail=("line_text",))
|
|
229
|
+
store = SESSION_STORE.get()
|
|
230
|
+
uuid = client.resolve_image(store.current_image)
|
|
231
|
+
|
|
232
|
+
paths = (
|
|
233
|
+
[store.resolve_path(p) for p in args.path]
|
|
234
|
+
if args.path
|
|
235
|
+
else [store.get_cwd() or "/"]
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
before, after = args.before(), args.after()
|
|
239
|
+
result = client.inspect_image_grep(
|
|
240
|
+
uuid,
|
|
241
|
+
args.pattern,
|
|
242
|
+
path=paths,
|
|
243
|
+
glob=args.glob,
|
|
244
|
+
max_count=args.max_count,
|
|
245
|
+
max_total=args.max_total,
|
|
246
|
+
case=args.case,
|
|
247
|
+
before=before,
|
|
248
|
+
after=after,
|
|
249
|
+
)
|
|
250
|
+
data = result.to_dict()
|
|
251
|
+
|
|
252
|
+
if args.raw:
|
|
253
|
+
# Bypasses formatter routing to preserve submatches/patterns/
|
|
254
|
+
# truncated verbatim -- see show.py's --raw for the same idea.
|
|
255
|
+
json.dump(data, sys.stdout)
|
|
256
|
+
sys.stdout.write("\n")
|
|
257
|
+
elif isinstance(formatter, DefaultFormatter):
|
|
258
|
+
# Classic grep output, matching ripgrep's own default rendering
|
|
259
|
+
# (path/line colored, match highlighted, when stdout is a
|
|
260
|
+
# terminal). Structured formats (json/csv/table/...) still get
|
|
261
|
+
# one row per match/context line via the normal pipeline below.
|
|
262
|
+
write_grep_lines(data["matches"], with_context=bool(before or after))
|
|
263
|
+
else:
|
|
264
|
+
for match in data["matches"]:
|
|
265
|
+
# `submatches` (byte-offset highlight positions) is only
|
|
266
|
+
# useful for --raw or the DefaultFormatter highlighting
|
|
267
|
+
# above -- drop it explicitly rather than relying on
|
|
268
|
+
# ListSorter, which now lets JSON-like formatters keep
|
|
269
|
+
# nested fields (see show.py's "result").
|
|
270
|
+
row = {k: v for k, v in match.items() if k != "submatches"}
|
|
271
|
+
row["line_text"] = row["line_text"].rstrip("\r\n")
|
|
272
|
+
formatter(**row)
|
|
273
|
+
formatter.flush()
|
|
274
|
+
|
|
275
|
+
if data["truncated"]:
|
|
276
|
+
logger.warning(
|
|
277
|
+
"Results truncated (max_total or search deadline reached);"
|
|
278
|
+
" narrow the search with --glob or a more specific PATH.",
|
|
279
|
+
)
|
|
280
|
+
if not data["matches"]:
|
|
281
|
+
# Zero matches here is inconclusive, not confirmed: the
|
|
282
|
+
# deadline/max_total was hit before the search could even
|
|
283
|
+
# finish, unlike a normal exit 1 (search completed, found
|
|
284
|
+
# nothing).
|
|
285
|
+
return 2
|
|
286
|
+
|
|
287
|
+
return 1 if not data["matches"] else None
|
|
@@ -128,6 +128,15 @@ class WaitArgs(ArgumentsProtocol):
|
|
|
128
128
|
)
|
|
129
129
|
|
|
130
130
|
|
|
131
|
+
@dataclass(frozen=True)
|
|
132
|
+
class EventsArgs(ArgumentsProtocol):
|
|
133
|
+
uuids: list[str] = field(default_factory=list)
|
|
134
|
+
|
|
135
|
+
@classmethod
|
|
136
|
+
def from_args(cls, ns: argparse.Namespace) -> EventsArgs:
|
|
137
|
+
return cls(uuids=resolve_operation_uuids(list(ns.uuids or [])))
|
|
138
|
+
|
|
139
|
+
|
|
131
140
|
def setup_cancel_parser(p: argparse.ArgumentParser) -> SetupResult:
|
|
132
141
|
"""Configure the cancel parser used by both `operation cancel` and `kill`."""
|
|
133
142
|
p.add_argument(
|
|
@@ -203,6 +212,20 @@ def setup_wait_parser(p: argparse.ArgumentParser) -> SetupResult:
|
|
|
203
212
|
return cmd_wait, WaitArgs
|
|
204
213
|
|
|
205
214
|
|
|
215
|
+
def setup_events_parser(p: argparse.ArgumentParser) -> SetupResult:
|
|
216
|
+
"""Configure the parser for `operation events`."""
|
|
217
|
+
p.add_argument(
|
|
218
|
+
"uuids",
|
|
219
|
+
nargs="+",
|
|
220
|
+
metavar="UUID_OR_REF",
|
|
221
|
+
help=(
|
|
222
|
+
"Operations whose event log to print. Accepts UUIDs and "
|
|
223
|
+
"session-history references (HEAD, HEAD~N, @, @N, @-N, @+N, :N, bare N)."
|
|
224
|
+
),
|
|
225
|
+
)
|
|
226
|
+
return cmd_events, EventsArgs
|
|
227
|
+
|
|
228
|
+
|
|
206
229
|
def setup_list_parser(p: argparse.ArgumentParser) -> SetupResult:
|
|
207
230
|
"""Configure the listing parser used by both `operation ls` and `ps`."""
|
|
208
231
|
p.add_argument(
|
|
@@ -316,6 +339,29 @@ def setup_parser(p: argparse.ArgumentParser) -> SetupResult:
|
|
|
316
339
|
wait_handler, wait_loader = setup_wait_parser(wait_p)
|
|
317
340
|
wait_p.set_defaults(handler=wait_handler, load_args=wait_loader)
|
|
318
341
|
|
|
342
|
+
events_p = sub.add_parser(
|
|
343
|
+
"events",
|
|
344
|
+
aliases=["ev"],
|
|
345
|
+
help="Print an operation's full raw event log",
|
|
346
|
+
description=(
|
|
347
|
+
"Fetch and print every recorded event for each given operation, "
|
|
348
|
+
"one row per event via the active formatter (a table by "
|
|
349
|
+
"default; JSONL with -o json). Events are stored independently "
|
|
350
|
+
"of the operation's summarized result and are available "
|
|
351
|
+
"whether the operation is still running, finished in the "
|
|
352
|
+
"foreground, or ran detached."
|
|
353
|
+
),
|
|
354
|
+
epilog=(
|
|
355
|
+
"for coding agents:\n"
|
|
356
|
+
" read-only command\n"
|
|
357
|
+
" use -o json for JSONL, one full OperationEvent per line"
|
|
358
|
+
" (id, ts, type, spid, data)\n"
|
|
359
|
+
" useful when `show`'s result snapshot looks truncated/incomplete"
|
|
360
|
+
),
|
|
361
|
+
)
|
|
362
|
+
events_handler, events_loader = setup_events_parser(events_p)
|
|
363
|
+
events_p.set_defaults(handler=events_handler, load_args=events_loader)
|
|
364
|
+
|
|
319
365
|
return cmd_show_multi, ShowMultiArgs
|
|
320
366
|
|
|
321
367
|
|
|
@@ -450,6 +496,23 @@ def cmd_cancel(args: CancelArgs) -> int | None:
|
|
|
450
496
|
return 1 if failed else None
|
|
451
497
|
|
|
452
498
|
|
|
499
|
+
def cmd_events(args: EventsArgs) -> int | None:
|
|
500
|
+
client = CLIENT.get()
|
|
501
|
+
formatter = FORMATTER.get()
|
|
502
|
+
formatter.configure(head=("uuid", "id", "ts", "type", "spid"), tail=("data",))
|
|
503
|
+
|
|
504
|
+
exit_code = 0
|
|
505
|
+
for uuid in args.uuids:
|
|
506
|
+
try:
|
|
507
|
+
for ev in client.iter_operation_events(uuid, follow=False):
|
|
508
|
+
formatter(uuid=uuid, **ev.to_dict())
|
|
509
|
+
except ContreeAPIError as exc:
|
|
510
|
+
logger.error("Failed to fetch events for %s: %s", uuid, exc)
|
|
511
|
+
exit_code = 1
|
|
512
|
+
formatter.flush()
|
|
513
|
+
return exit_code or None
|
|
514
|
+
|
|
515
|
+
|
|
453
516
|
def cmd_wait(args: WaitArgs) -> int | None:
|
|
454
517
|
client = CLIENT.get()
|
|
455
518
|
formatter = FORMATTER.get()
|