contree-cli 0.9.3__tar.gz → 0.10.0__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.3 → contree_cli-0.10.0}/PKG-INFO +2 -2
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/agent.md +1 -1
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/auth.py +4 -3
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/build.py +8 -21
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/cd.py +2 -2
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/images.py +2 -2
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/ls.py +1 -1
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/operation.py +5 -5
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/run.py +5 -11
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/session.py +3 -1
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/client.py +42 -1
- contree_cli-0.10.0/contree_cli/docker/archive.py +309 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/context.py +22 -3
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/dockerignore.py +35 -2
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/kw_add.py +3 -1
- contree_cli-0.10.0/contree_cli/docker/kw_copy.py +322 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/kw_from.py +17 -22
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/kw_run.py +34 -14
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/kw_workdir.py +1 -1
- contree_cli-0.10.0/contree_cli/docker/metadata.py +142 -0
- contree_cli-0.10.0/contree_cli/docker/transfer.py +398 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/shell/repl.py +3 -3
- {contree_cli-0.9.3 → contree_cli-0.10.0}/pyproject.toml +2 -2
- {contree_cli-0.9.3 → contree_cli-0.10.0}/pyproject.toml.orig +2 -2
- contree_cli-0.9.3/contree_cli/docker/kw_copy.py +0 -350
- {contree_cli-0.9.3 → contree_cli-0.10.0}/LICENSE +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/README.md +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/__init__.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/__main__.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/arguments.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/__init__.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/agent.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/cat.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/cp.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/env.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/export.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/file.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/grep.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/show.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/skill.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/tag.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/cli/use.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/config.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/__init__.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/keyword.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/kw_arg.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/kw_env.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/kw_skipped.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/kw_user.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/local_context.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/parser.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/docker/url_fetch.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/log.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/man.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/manual.md +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/mapped_file.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/migrations.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/output.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/pty_utils.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/py.typed +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/refs.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/session.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/shell/__init__.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/shell/argmap.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/shell/argspec.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/shell/cache.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/shell/completer.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/shell/history.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/shell/parser.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/shell/sources.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/shell/trie.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/skill.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/skill_body.md +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/contree_cli/types.py +0 -0
- {contree_cli-0.9.3 → contree_cli-0.10.0}/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.
|
|
3
|
+
Version: 0.10.0
|
|
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
|
|
200
|
+
Requires-Dist: contree-client~=0.6.0
|
|
201
201
|
Requires-Python: >=3.10
|
|
202
202
|
Project-URL: Homepage, https://contree.dev
|
|
203
203
|
Project-URL: Documentation, https://docs.contree.dev/cli/
|
|
@@ -143,7 +143,7 @@ Building from a Dockerfile:
|
|
|
143
143
|
contree build . --build-arg VERSION=1.2
|
|
144
144
|
contree build . --no-cache force rebuild
|
|
145
145
|
|
|
146
|
-
Supported directives: FROM, RUN, COPY, ADD (local files/dirs and http(s) URLs; no tar auto-extract), WORKDIR, ENV, ARG, USER. CMD/ENTRYPOINT/LABEL/EXPOSE/VOLUME/etc. are parsed but skipped with a warning. Multi-stage (AS / --from) is
|
|
146
|
+
Supported directives: FROM, RUN, COPY, ADD (local files/dirs and http(s) URLs; no tar auto-extract), WORKDIR, ENV, ARG, USER. CMD/ENTRYPOINT/LABEL/EXPOSE/VOLUME/etc. are parsed but skipped with a warning. Multi-stage (AS / --from) is supported. COPY transfers archives through the API without a guest shell. ENV and WORKDIR persist in the result image. Explicit ownership and special mode bits require guest chown/chmod.
|
|
147
147
|
|
|
148
148
|
.dockerignore is applied to every COPY/ADD walk on top of the default exclude list (.git, __pycache__, node_modules, etc.).
|
|
149
149
|
|
|
@@ -31,7 +31,7 @@ import os
|
|
|
31
31
|
from dataclasses import dataclass
|
|
32
32
|
from multiprocessing.pool import ThreadPool
|
|
33
33
|
|
|
34
|
-
from contree_client.exceptions import
|
|
34
|
+
from contree_client.exceptions import APIStatusError
|
|
35
35
|
from contree_client.models import WhoAmIResponse
|
|
36
36
|
|
|
37
37
|
from contree_cli import FORMATTER, ArgumentsProtocol, SetupResult
|
|
@@ -263,12 +263,13 @@ def cmd_auth(args: AuthArgs) -> int | None:
|
|
|
263
263
|
try:
|
|
264
264
|
with client:
|
|
265
265
|
whoami = client.whoami()
|
|
266
|
-
except
|
|
266
|
+
except (APIStatusError, ValueError) as exc:
|
|
267
|
+
# ValueError covers parse_whoami's own non-2xx status check.
|
|
267
268
|
# Logs the API error message, not the token itself.
|
|
268
269
|
# nosemgrep: python-logger-credential-disclosure
|
|
269
270
|
logger.error("Token verification failed: %s. Profile not changed.", exc)
|
|
270
271
|
return 1
|
|
271
|
-
except (KeyError, TypeError
|
|
272
|
+
except (KeyError, TypeError) as exc:
|
|
272
273
|
# Strict contree-client models raise TypeError (missing required
|
|
273
274
|
# field) or KeyError (parse_fields lookup) on incomplete payloads.
|
|
274
275
|
logger.error("Could not parse /v1/whoami response: %s", exc)
|
|
@@ -13,15 +13,10 @@ WORKDIR, ENV, ARG, USER. Other Dockerfile directives parse cleanly but
|
|
|
13
13
|
are skipped with a warning (CMD, ENTRYPOINT, LABEL, EXPOSE, VOLUME,
|
|
14
14
|
STOPSIGNAL, MAINTAINER, HEALTHCHECK, ONBUILD, SHELL).
|
|
15
15
|
|
|
16
|
-
Multistage
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
``tar``, ``cp`` and ``mv`` (busybox suffices; ``FROM scratch`` targets
|
|
21
|
-
cannot receive ``COPY --from``). This is a temporary limitation of the
|
|
22
|
-
client-side extraction and will be lifted in a future release once the
|
|
23
|
-
backend unpacks archives itself. Unlike docker, ARG/ENV live in one
|
|
24
|
-
global namespace across stages.
|
|
16
|
+
Multistage COPY transfers archives through the API without a guest shell.
|
|
17
|
+
Ownership changes and special mode bits require guest chown/chmod executables.
|
|
18
|
+
ARG values use one global namespace across stages. ENV and WORKDIR are saved
|
|
19
|
+
in image metadata, including directives after the final RUN.
|
|
25
20
|
"""
|
|
26
21
|
|
|
27
22
|
from __future__ import annotations
|
|
@@ -47,10 +42,10 @@ from contree_cli.docker import (
|
|
|
47
42
|
DockerKeyword,
|
|
48
43
|
FromKeyword,
|
|
49
44
|
LocalContext,
|
|
50
|
-
RunKeyword,
|
|
51
45
|
parse_dockerfile,
|
|
52
46
|
)
|
|
53
47
|
from contree_cli.docker.context import BUILD_TIMEOUT_DEFAULT
|
|
48
|
+
from contree_cli.docker.kw_run import finalize_pending
|
|
54
49
|
from contree_cli.session import SessionStore
|
|
55
50
|
from contree_cli.types import FLAGS
|
|
56
51
|
|
|
@@ -69,8 +64,8 @@ for coding agents:
|
|
|
69
64
|
layer cache is per-context (session keyed by abspath(context))
|
|
70
65
|
use --no-cache to bypass cached layers and rebuild from scratch
|
|
71
66
|
multistage supported: FROM ... AS name + COPY --from=<name|index|image>
|
|
72
|
-
COPY
|
|
73
|
-
|
|
67
|
+
COPY transfers directories through the API without a guest shell
|
|
68
|
+
non-default ownership and special mode bits need guest chown/chmod
|
|
74
69
|
"""
|
|
75
70
|
|
|
76
71
|
|
|
@@ -130,7 +125,7 @@ def setup_parser(p: argparse.ArgumentParser) -> SetupResult:
|
|
|
130
125
|
*FLAGS["timeout"],
|
|
131
126
|
type=int,
|
|
132
127
|
default=BUILD_TIMEOUT_DEFAULT,
|
|
133
|
-
help="Timeout in seconds for each
|
|
128
|
+
help="Timeout in seconds for each build instance",
|
|
134
129
|
)
|
|
135
130
|
return cmd_build, BuildArgs
|
|
136
131
|
|
|
@@ -229,11 +224,3 @@ def parse_build_args(items: tuple[str, ...]) -> dict[str, str]:
|
|
|
229
224
|
def make_session_key(context_dir: Path) -> str:
|
|
230
225
|
digest = hashlib.sha256(str(context_dir).encode()).hexdigest()
|
|
231
226
|
return f"build:{digest[:16]}"
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
def finalize_pending(ctx: BuildContext) -> None:
|
|
235
|
-
"""If COPY/ADD left files pending, commit them via a trivial RUN."""
|
|
236
|
-
if not ctx.pending:
|
|
237
|
-
return
|
|
238
|
-
closer = RunKeyword(parts=(":",), shell_form=True)
|
|
239
|
-
closer.execute(ctx)
|
|
@@ -14,7 +14,7 @@ import logging
|
|
|
14
14
|
import posixpath
|
|
15
15
|
from dataclasses import dataclass
|
|
16
16
|
|
|
17
|
-
from contree_client.exceptions import
|
|
17
|
+
from contree_client.exceptions import APIStatusError
|
|
18
18
|
|
|
19
19
|
from contree_cli import CLIENT, SESSION_STORE, ArgumentsProtocol, SetupResult
|
|
20
20
|
|
|
@@ -64,7 +64,7 @@ def cmd_cd(args: CdArgs) -> int | None:
|
|
|
64
64
|
client = CLIENT.get()
|
|
65
65
|
uuid = client.resolve_image(session.current_image)
|
|
66
66
|
client.inspect_image_list(uuid, new_cwd)
|
|
67
|
-
except
|
|
67
|
+
except APIStatusError as exc:
|
|
68
68
|
if exc.status == 404:
|
|
69
69
|
logger.error("cd: %s: no such directory", new_cwd)
|
|
70
70
|
return 1
|
|
@@ -16,7 +16,7 @@ import time
|
|
|
16
16
|
from dataclasses import dataclass, field
|
|
17
17
|
from datetime import datetime
|
|
18
18
|
|
|
19
|
-
from contree_client.exceptions import
|
|
19
|
+
from contree_client.exceptions import APIStatusError
|
|
20
20
|
from contree_client.models import (
|
|
21
21
|
TERMINAL_STATUSES,
|
|
22
22
|
ImageImportRegistry,
|
|
@@ -393,7 +393,7 @@ def cmd_import(args: ImportArgs) -> int | None:
|
|
|
393
393
|
try:
|
|
394
394
|
client.cancel_operation(op_uuid)
|
|
395
395
|
logger.info("Cancelled operation %s", op_uuid)
|
|
396
|
-
except (
|
|
396
|
+
except (APIStatusError, KeyboardInterrupt, OSError):
|
|
397
397
|
pass
|
|
398
398
|
raise
|
|
399
399
|
|
|
@@ -21,7 +21,7 @@ from dataclasses import dataclass, field
|
|
|
21
21
|
from datetime import datetime
|
|
22
22
|
from typing import Any
|
|
23
23
|
|
|
24
|
-
from contree_client.exceptions import
|
|
24
|
+
from contree_client.exceptions import APIStatusError
|
|
25
25
|
from contree_client.models import ACTIVE_STATUSES, TERMINAL_STATUSES
|
|
26
26
|
|
|
27
27
|
from contree_cli import CLIENT, FORMATTER, SESSION_STORE, ArgumentsProtocol, SetupResult
|
|
@@ -460,7 +460,7 @@ def cmd_show_multi(args: ShowMultiArgs) -> int | None:
|
|
|
460
460
|
for uuid in args.uuids:
|
|
461
461
|
try:
|
|
462
462
|
result = cmd_show(ShowArgs(uuid=uuid, raw=args.raw))
|
|
463
|
-
except
|
|
463
|
+
except APIStatusError as exc:
|
|
464
464
|
logger.error("Failed to fetch %s: %s", uuid, exc)
|
|
465
465
|
exit_code = max(exit_code, 1)
|
|
466
466
|
continue
|
|
@@ -490,7 +490,7 @@ def cmd_cancel(args: CancelArgs) -> int | None:
|
|
|
490
490
|
try:
|
|
491
491
|
client.cancel_operation(uuid)
|
|
492
492
|
logger.info("Cancelled operation %s", uuid)
|
|
493
|
-
except
|
|
493
|
+
except APIStatusError as exc:
|
|
494
494
|
logger.error("Failed to cancel %s: %s", uuid, exc)
|
|
495
495
|
failed += 1
|
|
496
496
|
return 1 if failed else None
|
|
@@ -506,7 +506,7 @@ def cmd_events(args: EventsArgs) -> int | None:
|
|
|
506
506
|
try:
|
|
507
507
|
for ev in client.iter_operation_events(uuid, follow=False):
|
|
508
508
|
formatter(uuid=uuid, **ev.to_dict())
|
|
509
|
-
except
|
|
509
|
+
except APIStatusError as exc:
|
|
510
510
|
logger.error("Failed to fetch events for %s: %s", uuid, exc)
|
|
511
511
|
exit_code = 1
|
|
512
512
|
formatter.flush()
|
|
@@ -592,7 +592,7 @@ def cmd_wait(args: WaitArgs) -> int | None:
|
|
|
592
592
|
for uuid in sorted(pending):
|
|
593
593
|
try:
|
|
594
594
|
op = client.get_operation_status(uuid).to_dict()
|
|
595
|
-
except
|
|
595
|
+
except APIStatusError as exc:
|
|
596
596
|
logger.error("Failed to fetch %s: %s", uuid, exc)
|
|
597
597
|
continue
|
|
598
598
|
formatter(**{**op, "timed_out": True})
|
|
@@ -65,7 +65,7 @@ from dataclasses import dataclass, field
|
|
|
65
65
|
from multiprocessing.pool import ThreadPool
|
|
66
66
|
from typing import Any
|
|
67
67
|
|
|
68
|
-
from contree_client.exceptions import
|
|
68
|
+
from contree_client.exceptions import APIStatusError, ContreeError
|
|
69
69
|
from contree_client.models import (
|
|
70
70
|
TERMINAL_STATUSES,
|
|
71
71
|
ClosableStreamRepr,
|
|
@@ -94,14 +94,8 @@ from contree_cli.types import FLAGS
|
|
|
94
94
|
|
|
95
95
|
logger = logging.getLogger(__name__)
|
|
96
96
|
|
|
97
|
-
#
|
|
98
|
-
|
|
99
|
-
SIGNAL_ERRORS: tuple[type[BaseException], ...] = (
|
|
100
|
-
ContreeAPIError,
|
|
101
|
-
OSError,
|
|
102
|
-
*CliClient.retryable_errors,
|
|
103
|
-
*CliClient.nonretryable_errors,
|
|
104
|
-
)
|
|
97
|
+
# ContreeError covers APIConnectionError from any transport backend.
|
|
98
|
+
SIGNAL_ERRORS: tuple[type[BaseException], ...] = (ContreeError, OSError)
|
|
105
99
|
|
|
106
100
|
EPILOG = """\
|
|
107
101
|
examples:
|
|
@@ -688,7 +682,7 @@ def stream_events_until_close(
|
|
|
688
682
|
# payload the caller would otherwise build from `completion`.
|
|
689
683
|
try:
|
|
690
684
|
op = client.get_operation_status(op_uuid).to_dict()
|
|
691
|
-
except
|
|
685
|
+
except APIStatusError as exc:
|
|
692
686
|
logger.debug("terminal op fetch failed: %s", exc)
|
|
693
687
|
return summary
|
|
694
688
|
if op.get("status") in TERMINAL_STATUSES:
|
|
@@ -1027,7 +1021,7 @@ def cmd_run(args: RunArgs) -> int | None:
|
|
|
1027
1021
|
# so callers see the SIGPIPE convention (128 + 13).
|
|
1028
1022
|
if forwarder is not None:
|
|
1029
1023
|
forwarder.abandon()
|
|
1030
|
-
with contextlib.suppress(
|
|
1024
|
+
with contextlib.suppress(APIStatusError, OSError):
|
|
1031
1025
|
client.cancel_operation(op_uuid)
|
|
1032
1026
|
with contextlib.suppress(OSError):
|
|
1033
1027
|
devnull = os.open(os.devnull, os.O_WRONLY)
|
|
@@ -664,7 +664,9 @@ def cmd_wait(args: WaitArgs) -> int | None:
|
|
|
664
664
|
RequestSpec(method="GET", path="/operations", idempotent=True)
|
|
665
665
|
)
|
|
666
666
|
if response.status != 200:
|
|
667
|
-
raise error_for_response(
|
|
667
|
+
raise error_for_response(
|
|
668
|
+
response.status, response.headers, response.body
|
|
669
|
+
)
|
|
668
670
|
operations = json.loads(response.body)
|
|
669
671
|
api_op_ids: list[str] = []
|
|
670
672
|
for op in operations:
|
|
@@ -19,11 +19,14 @@ import json
|
|
|
19
19
|
import logging
|
|
20
20
|
import platform
|
|
21
21
|
import sys
|
|
22
|
+
from collections.abc import Iterator
|
|
23
|
+
from copy import copy
|
|
24
|
+
from dataclasses import replace
|
|
22
25
|
from importlib.metadata import PackageNotFoundError, distribution
|
|
23
26
|
from typing import TYPE_CHECKING, Any
|
|
24
27
|
|
|
25
28
|
from contree_client.profiles import AUTH_TYPE_IAM, Profile
|
|
26
|
-
from contree_client.runtime import RetryPolicy
|
|
29
|
+
from contree_client.runtime import RequestSpec, ResponseData, RetryPolicy
|
|
27
30
|
|
|
28
31
|
if TYPE_CHECKING:
|
|
29
32
|
# The auto-detected backend class is a runtime variable, invalid
|
|
@@ -71,10 +74,48 @@ class CliClient(ClientBase):
|
|
|
71
74
|
and transport tokens.
|
|
72
75
|
"""
|
|
73
76
|
|
|
77
|
+
request_deadline: float | None = None
|
|
78
|
+
|
|
74
79
|
def __init__(self, token: str, **kwargs: Any) -> None:
|
|
75
80
|
kwargs.setdefault("identity", CLI_IDENTITY)
|
|
76
81
|
super().__init__(token, **kwargs)
|
|
77
82
|
|
|
83
|
+
def bounded(self, deadline: float) -> CliClient:
|
|
84
|
+
"""Share the transport with an independent deadline and finite retry policy."""
|
|
85
|
+
client = copy(self)
|
|
86
|
+
client.request_deadline = deadline
|
|
87
|
+
if client.retry is not None:
|
|
88
|
+
client.retry = replace(
|
|
89
|
+
client.retry,
|
|
90
|
+
statuses=tuple(
|
|
91
|
+
status for status in client.retry.statuses if status != 410
|
|
92
|
+
),
|
|
93
|
+
max_attempts=min(client.retry.max_attempts or 10, 10),
|
|
94
|
+
)
|
|
95
|
+
return client
|
|
96
|
+
|
|
97
|
+
def bound_request(self, spec: RequestSpec) -> RequestSpec:
|
|
98
|
+
"""Keep the earliest request or lifecycle deadline."""
|
|
99
|
+
if self.request_deadline is None:
|
|
100
|
+
return spec
|
|
101
|
+
deadline = self.request_deadline
|
|
102
|
+
if spec.deadline is not None:
|
|
103
|
+
deadline = min(deadline, spec.deadline)
|
|
104
|
+
return replace(spec, deadline=deadline)
|
|
105
|
+
|
|
106
|
+
def call(self, spec: RequestSpec) -> ResponseData:
|
|
107
|
+
return super().call(self.bound_request(spec))
|
|
108
|
+
|
|
109
|
+
def request(self, spec: RequestSpec) -> ResponseData:
|
|
110
|
+
return super().request(self.bound_request(spec)) # type: ignore[safe-super]
|
|
111
|
+
|
|
112
|
+
def stream(
|
|
113
|
+
self, spec: RequestSpec, auto_decompress: bool = True
|
|
114
|
+
) -> Iterator[bytes]:
|
|
115
|
+
yield from super().stream( # type: ignore[safe-super]
|
|
116
|
+
self.bound_request(spec), auto_decompress=auto_decompress
|
|
117
|
+
)
|
|
118
|
+
|
|
78
119
|
|
|
79
120
|
def client_from_profile(
|
|
80
121
|
profile: Profile,
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"""Prepare deterministic COPY archives without executing guest commands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import os
|
|
7
|
+
import posixpath
|
|
8
|
+
import stat
|
|
9
|
+
import tarfile
|
|
10
|
+
import tempfile
|
|
11
|
+
from collections.abc import Iterator
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from itertools import chain
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import IO
|
|
16
|
+
|
|
17
|
+
from .dockerignore import may_include_descendants
|
|
18
|
+
from .local_context import LocalContext, matches_default_excludes
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ArchiveBuffer(tempfile.SpooledTemporaryFile[bytes]):
|
|
22
|
+
"""Provide tarfile seekability for memory and disk spools on Python 3.10."""
|
|
23
|
+
|
|
24
|
+
def seekable(self) -> bool:
|
|
25
|
+
self.tell()
|
|
26
|
+
return True
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class ArchiveEntry:
|
|
31
|
+
path: str
|
|
32
|
+
uid: int
|
|
33
|
+
gid: int
|
|
34
|
+
mode: int
|
|
35
|
+
is_symlink: bool
|
|
36
|
+
is_directory: bool = False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class ArchiveInfo:
|
|
41
|
+
is_directory: bool
|
|
42
|
+
entries: tuple[ArchiveEntry, ...]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def canonical_member(
|
|
46
|
+
member: tarfile.TarInfo, mode_override: int | None
|
|
47
|
+
) -> tuple[tarfile.TarInfo, ArchiveEntry]:
|
|
48
|
+
"""Keep restoration metadata separately from the runtime archive format."""
|
|
49
|
+
member = copy.copy(member)
|
|
50
|
+
mode = member.mode if mode_override is None or member.issym() else mode_override
|
|
51
|
+
entry = ArchiveEntry(
|
|
52
|
+
member.name, member.uid, member.gid, mode, member.issym(), member.isdir()
|
|
53
|
+
)
|
|
54
|
+
member.mode = mode & 0o777
|
|
55
|
+
if member.isreg():
|
|
56
|
+
member.type = tarfile.REGTYPE
|
|
57
|
+
member.sparse = None
|
|
58
|
+
member.uid = member.gid = 0
|
|
59
|
+
member.uname = member.gname = ""
|
|
60
|
+
member.mtime = 0
|
|
61
|
+
member.pax_headers = {}
|
|
62
|
+
return member, entry
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def local_source(local: LocalContext, source: str) -> Path:
|
|
66
|
+
"""Validate an explicit source's target and retain its requested basename."""
|
|
67
|
+
path = Path(os.path.abspath(local.root / source))
|
|
68
|
+
try:
|
|
69
|
+
path.relative_to(local.root)
|
|
70
|
+
path.resolve().relative_to(local.root)
|
|
71
|
+
except ValueError:
|
|
72
|
+
raise ValueError(f"COPY/ADD source escapes context: {source!r}") from None
|
|
73
|
+
return path
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def local_archive_paths(
|
|
77
|
+
local: LocalContext, path: Path, *, follow_symlink: bool = False
|
|
78
|
+
) -> Iterator[Path]:
|
|
79
|
+
"""Retain excluded parents only when an included descendant needs them."""
|
|
80
|
+
resolved = path.resolve() if follow_symlink else path.parent.resolve() / path.name
|
|
81
|
+
relative_paths = tuple(
|
|
82
|
+
candidate.relative_to(local.root).as_posix()
|
|
83
|
+
for candidate in (path, resolved)
|
|
84
|
+
if candidate != local.root
|
|
85
|
+
)
|
|
86
|
+
if any(matches_default_excludes(relative) for relative in relative_paths):
|
|
87
|
+
return
|
|
88
|
+
ignored = any(local.is_ignored(relative) for relative in relative_paths)
|
|
89
|
+
if ignored and any(
|
|
90
|
+
not may_include_descendants(relative, local.dockerignore)
|
|
91
|
+
for relative in relative_paths
|
|
92
|
+
):
|
|
93
|
+
return
|
|
94
|
+
status = path.stat() if follow_symlink else path.lstat()
|
|
95
|
+
if not stat.S_ISDIR(status.st_mode):
|
|
96
|
+
if not ignored:
|
|
97
|
+
yield path
|
|
98
|
+
return
|
|
99
|
+
children = (
|
|
100
|
+
included
|
|
101
|
+
for child in sorted(path.iterdir())
|
|
102
|
+
for included in local_archive_paths(local, child)
|
|
103
|
+
)
|
|
104
|
+
if ignored:
|
|
105
|
+
first = next(children, None)
|
|
106
|
+
if first is None:
|
|
107
|
+
return
|
|
108
|
+
yield path
|
|
109
|
+
yield first
|
|
110
|
+
else:
|
|
111
|
+
yield path
|
|
112
|
+
yield from children
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def write_local_archive(
|
|
116
|
+
local: LocalContext,
|
|
117
|
+
source: str,
|
|
118
|
+
output: IO[bytes],
|
|
119
|
+
*,
|
|
120
|
+
mode_override: int | None = None,
|
|
121
|
+
name_override: str | None = None,
|
|
122
|
+
) -> ArchiveInfo | None:
|
|
123
|
+
"""Dereference an explicit source and preserve symlinks inside directories."""
|
|
124
|
+
path = local_source(local, source)
|
|
125
|
+
selected = local_archive_paths(local, path, follow_symlink=True)
|
|
126
|
+
first = next(selected, None)
|
|
127
|
+
if first is None:
|
|
128
|
+
return None
|
|
129
|
+
source_stat = path.stat()
|
|
130
|
+
is_directory = stat.S_ISDIR(source_stat.st_mode)
|
|
131
|
+
name = archive_leaf_name(path.name, is_directory, name_override)
|
|
132
|
+
entries: list[ArchiveEntry] = []
|
|
133
|
+
hardlinks: dict[tuple[int, int], str] = {}
|
|
134
|
+
output.seek(0)
|
|
135
|
+
output.truncate()
|
|
136
|
+
with tarfile.open(fileobj=output, mode="w", format=tarfile.PAX_FORMAT) as archive:
|
|
137
|
+
for selected_path in chain((first,), selected):
|
|
138
|
+
write_local_entry(
|
|
139
|
+
archive,
|
|
140
|
+
selected_path,
|
|
141
|
+
selected_path.relative_to(path).as_posix() if is_directory else name,
|
|
142
|
+
mode_override,
|
|
143
|
+
entries,
|
|
144
|
+
hardlinks,
|
|
145
|
+
follow_symlink=selected_path == path,
|
|
146
|
+
)
|
|
147
|
+
output.seek(0)
|
|
148
|
+
return ArchiveInfo(is_directory, tuple(entries))
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def write_local_entry(
|
|
152
|
+
archive: tarfile.TarFile,
|
|
153
|
+
path: Path,
|
|
154
|
+
name: str,
|
|
155
|
+
mode_override: int | None,
|
|
156
|
+
entries: list[ArchiveEntry],
|
|
157
|
+
hardlinks: dict[tuple[int, int], str],
|
|
158
|
+
*,
|
|
159
|
+
follow_symlink: bool = False,
|
|
160
|
+
) -> None:
|
|
161
|
+
status = path.stat() if follow_symlink else path.lstat()
|
|
162
|
+
member = tarfile.TarInfo(name)
|
|
163
|
+
member.mode = stat.S_IMODE(status.st_mode)
|
|
164
|
+
if stat.S_ISDIR(status.st_mode):
|
|
165
|
+
member.type = tarfile.DIRTYPE
|
|
166
|
+
elif stat.S_ISLNK(status.st_mode):
|
|
167
|
+
member.type = tarfile.SYMTYPE
|
|
168
|
+
member.linkname = os.readlink(path)
|
|
169
|
+
elif stat.S_ISREG(status.st_mode):
|
|
170
|
+
key = (status.st_dev, status.st_ino)
|
|
171
|
+
if status.st_nlink > 1 and key in hardlinks:
|
|
172
|
+
member.type = tarfile.LNKTYPE
|
|
173
|
+
member.linkname = hardlinks[key]
|
|
174
|
+
else:
|
|
175
|
+
member.size = status.st_size
|
|
176
|
+
hardlinks[key] = name
|
|
177
|
+
else:
|
|
178
|
+
raise ValueError(f"COPY/ADD source has unsupported file type: {path}")
|
|
179
|
+
member, entry = canonical_member(member, mode_override)
|
|
180
|
+
entries.append(entry)
|
|
181
|
+
if member.isreg():
|
|
182
|
+
with path.open("rb") as content:
|
|
183
|
+
archive.addfile(member, content)
|
|
184
|
+
else:
|
|
185
|
+
archive.addfile(member)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def archive_path(name: str) -> str:
|
|
189
|
+
"""Validate an archive path before removing redundant dot components."""
|
|
190
|
+
if name.startswith("/") or ".." in name.split("/") or "\x00" in name:
|
|
191
|
+
raise ValueError(f"COPY archive contains an unsafe path: {name!r}")
|
|
192
|
+
return posixpath.normpath(name)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def archive_leaf_name(name: str, is_directory: bool, name_override: str | None) -> str:
|
|
196
|
+
if name_override is None:
|
|
197
|
+
return name
|
|
198
|
+
if is_directory:
|
|
199
|
+
raise ValueError("Directory archives cannot rename their root")
|
|
200
|
+
if (
|
|
201
|
+
not name_override
|
|
202
|
+
or name_override in {".", ".."}
|
|
203
|
+
or "/" in name_override
|
|
204
|
+
or "\x00" in name_override
|
|
205
|
+
):
|
|
206
|
+
raise ValueError(f"Invalid COPY destination filename: {name_override!r}")
|
|
207
|
+
return name_override
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def archive_is_directory(source: IO[bytes]) -> bool:
|
|
211
|
+
"""Identify a directory archive without consuming the input stream."""
|
|
212
|
+
source.seek(0)
|
|
213
|
+
try:
|
|
214
|
+
with tarfile.open(fileobj=source, mode="r:*") as archive:
|
|
215
|
+
first = next(iter(archive), None)
|
|
216
|
+
if first is None:
|
|
217
|
+
raise ValueError("COPY --from: source archive is empty")
|
|
218
|
+
name = archive_path(first.name)
|
|
219
|
+
return first.isdir() or "/" in name
|
|
220
|
+
finally:
|
|
221
|
+
source.seek(0)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def rewrite_image_archive(
|
|
225
|
+
source: IO[bytes],
|
|
226
|
+
output: IO[bytes],
|
|
227
|
+
*,
|
|
228
|
+
mode_override: int | None = None,
|
|
229
|
+
name_override: str | None = None,
|
|
230
|
+
) -> ArchiveInfo:
|
|
231
|
+
"""Remove a directory archive's root prefix and rewrite internal hardlinks."""
|
|
232
|
+
source.seek(0)
|
|
233
|
+
output.seek(0)
|
|
234
|
+
output.truncate()
|
|
235
|
+
entries: list[ArchiveEntry] = []
|
|
236
|
+
regular_paths: set[str] = set()
|
|
237
|
+
symlink_paths: set[str] = set()
|
|
238
|
+
with (
|
|
239
|
+
tarfile.open(fileobj=source, mode="r:*") as original,
|
|
240
|
+
tarfile.open(fileobj=output, mode="w", format=tarfile.PAX_FORMAT) as result,
|
|
241
|
+
):
|
|
242
|
+
first = next(iter(original), None)
|
|
243
|
+
if first is None:
|
|
244
|
+
raise ValueError("COPY --from: source archive is empty")
|
|
245
|
+
first_name = archive_path(first.name)
|
|
246
|
+
root = first_name.split("/", 1)[0]
|
|
247
|
+
is_directory = first.isdir() or "/" in first_name
|
|
248
|
+
leaf = archive_leaf_name(root, is_directory, name_override)
|
|
249
|
+
for member in original:
|
|
250
|
+
source_name = archive_path(member.name)
|
|
251
|
+
if (
|
|
252
|
+
root != "."
|
|
253
|
+
and source_name != root
|
|
254
|
+
and not source_name.startswith(root + "/")
|
|
255
|
+
):
|
|
256
|
+
raise ValueError("COPY --from: archive contains multiple roots")
|
|
257
|
+
if not is_directory and source_name != root:
|
|
258
|
+
raise ValueError("COPY --from: file archive contains extra entries")
|
|
259
|
+
name = strip_archive_root(source_name, root) if is_directory else leaf
|
|
260
|
+
parents = name.split("/")[:-1]
|
|
261
|
+
if any(
|
|
262
|
+
"/".join(parents[:i]) in symlink_paths
|
|
263
|
+
for i in range(1, len(parents) + 1)
|
|
264
|
+
):
|
|
265
|
+
raise ValueError(f"COPY archive traverses a symlink: {source_name!r}")
|
|
266
|
+
rewritten = copy.copy(member)
|
|
267
|
+
rewritten.name = name
|
|
268
|
+
if member.islnk():
|
|
269
|
+
target = archive_path(member.linkname)
|
|
270
|
+
rewritten.linkname = strip_archive_root(target, root)
|
|
271
|
+
if rewritten.linkname not in regular_paths:
|
|
272
|
+
raise ValueError(
|
|
273
|
+
"COPY archive hardlink target is not an earlier file: "
|
|
274
|
+
f"{target!r}"
|
|
275
|
+
)
|
|
276
|
+
regular_paths.add(name)
|
|
277
|
+
elif member.issym():
|
|
278
|
+
symlink_paths.add(name)
|
|
279
|
+
elif member.isreg():
|
|
280
|
+
regular_paths.add(name)
|
|
281
|
+
elif not member.isdir():
|
|
282
|
+
raise ValueError(
|
|
283
|
+
f"COPY archive has unsupported file type: {source_name!r}"
|
|
284
|
+
)
|
|
285
|
+
rewritten, entry = canonical_member(rewritten, mode_override)
|
|
286
|
+
entries.append(entry)
|
|
287
|
+
if member.isreg():
|
|
288
|
+
content = original.extractfile(member)
|
|
289
|
+
if content is None:
|
|
290
|
+
raise ValueError(
|
|
291
|
+
f"COPY archive has no file content: {source_name!r}"
|
|
292
|
+
)
|
|
293
|
+
with content:
|
|
294
|
+
result.addfile(rewritten, content)
|
|
295
|
+
else:
|
|
296
|
+
result.addfile(rewritten)
|
|
297
|
+
source.seek(0)
|
|
298
|
+
output.seek(0)
|
|
299
|
+
return ArchiveInfo(is_directory, tuple(entries))
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def strip_archive_root(name: str, root: str) -> str:
|
|
303
|
+
if root == ".":
|
|
304
|
+
return name
|
|
305
|
+
if name == root:
|
|
306
|
+
return "."
|
|
307
|
+
if not name.startswith(root + "/"):
|
|
308
|
+
raise ValueError(f"COPY archive path is outside its root: {name!r}")
|
|
309
|
+
return name[len(root) + 1 :]
|