contree-cli 0.9.4__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.
Files changed (75) hide show
  1. {contree_cli-0.9.4 → contree_cli-0.10.0}/PKG-INFO +2 -2
  2. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/agent.md +1 -1
  3. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/build.py +8 -21
  4. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/client.py +42 -1
  5. contree_cli-0.10.0/contree_cli/docker/archive.py +309 -0
  6. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/context.py +22 -3
  7. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/dockerignore.py +35 -2
  8. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/kw_add.py +3 -1
  9. contree_cli-0.10.0/contree_cli/docker/kw_copy.py +322 -0
  10. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/kw_from.py +14 -19
  11. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/kw_run.py +34 -14
  12. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/kw_workdir.py +1 -1
  13. contree_cli-0.10.0/contree_cli/docker/metadata.py +142 -0
  14. contree_cli-0.10.0/contree_cli/docker/transfer.py +398 -0
  15. {contree_cli-0.9.4 → contree_cli-0.10.0}/pyproject.toml +2 -2
  16. {contree_cli-0.9.4 → contree_cli-0.10.0}/pyproject.toml.orig +2 -2
  17. contree_cli-0.9.4/contree_cli/docker/kw_copy.py +0 -350
  18. {contree_cli-0.9.4 → contree_cli-0.10.0}/LICENSE +0 -0
  19. {contree_cli-0.9.4 → contree_cli-0.10.0}/README.md +0 -0
  20. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/__init__.py +0 -0
  21. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/__main__.py +0 -0
  22. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/arguments.py +0 -0
  23. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/__init__.py +0 -0
  24. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/agent.py +0 -0
  25. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/auth.py +0 -0
  26. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/cat.py +0 -0
  27. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/cd.py +0 -0
  28. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/cp.py +0 -0
  29. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/env.py +0 -0
  30. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/export.py +0 -0
  31. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/file.py +0 -0
  32. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/grep.py +0 -0
  33. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/images.py +0 -0
  34. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/ls.py +0 -0
  35. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/operation.py +0 -0
  36. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/run.py +0 -0
  37. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/session.py +0 -0
  38. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/show.py +0 -0
  39. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/skill.py +0 -0
  40. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/tag.py +0 -0
  41. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/cli/use.py +0 -0
  42. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/config.py +0 -0
  43. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/__init__.py +0 -0
  44. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/keyword.py +0 -0
  45. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/kw_arg.py +0 -0
  46. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/kw_env.py +0 -0
  47. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/kw_skipped.py +0 -0
  48. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/kw_user.py +0 -0
  49. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/local_context.py +0 -0
  50. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/parser.py +0 -0
  51. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/docker/url_fetch.py +0 -0
  52. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/log.py +0 -0
  53. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/man.py +0 -0
  54. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/manual.md +0 -0
  55. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/mapped_file.py +0 -0
  56. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/migrations.py +0 -0
  57. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/output.py +0 -0
  58. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/pty_utils.py +0 -0
  59. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/py.typed +0 -0
  60. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/refs.py +0 -0
  61. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/session.py +0 -0
  62. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/shell/__init__.py +0 -0
  63. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/shell/argmap.py +0 -0
  64. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/shell/argspec.py +0 -0
  65. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/shell/cache.py +0 -0
  66. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/shell/completer.py +0 -0
  67. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/shell/history.py +0 -0
  68. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/shell/parser.py +0 -0
  69. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/shell/repl.py +0 -0
  70. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/shell/sources.py +0 -0
  71. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/shell/trie.py +0 -0
  72. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/skill.py +0 -0
  73. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/skill_body.md +0 -0
  74. {contree_cli-0.9.4 → contree_cli-0.10.0}/contree_cli/types.py +0 -0
  75. {contree_cli-0.9.4 → 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.9.4
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~=0.4.0
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 not yet supported.
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
 
@@ -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 notes: ``COPY --from`` exports the source path from the
17
- referenced stage image as a tar archive, uploads it once (content
18
- deduplicated) and unpacks it with an extraction RUN inside the target
19
- sandbox. For now this means the target image must provide ``/bin/sh``,
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 --from unpacks a tar inside the target: needs sh/tar/cp/mv there
73
- (temporary limitation, to be lifted in a future release)
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 RUN step",
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)
@@ -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 :]
@@ -6,13 +6,16 @@ import hashlib
6
6
  import json
7
7
  import logging
8
8
  from dataclasses import dataclass, field
9
- from typing import Any
9
+ from typing import TYPE_CHECKING, Any
10
10
 
11
11
  from contree_cli.client import CliClient
12
12
  from contree_cli.session import SessionStore
13
13
 
14
14
  from .local_context import LocalContext
15
15
 
16
+ if TYPE_CHECKING:
17
+ from .transfer import StagedArchive, StagedLink
18
+
16
19
  logger = logging.getLogger(__name__)
17
20
 
18
21
  BUILD_TIMEOUT_DEFAULT = 600
@@ -26,6 +29,7 @@ class PendingFile:
26
29
  uid: int
27
30
  gid: int
28
31
  mode: str # octal like "0644"
32
+ replace_existing: bool = False
29
33
 
30
34
 
31
35
  @dataclass
@@ -37,7 +41,9 @@ class BuildContext:
37
41
  declared_args: set[str] = field(default_factory=set)
38
42
  arg_defaults: dict[str, str] = field(default_factory=dict)
39
43
  env: dict[str, str] = field(default_factory=dict)
40
- workdir: str = "/"
44
+ persisted_env: dict[str, str] = field(default_factory=dict)
45
+ workdir: str = ""
46
+ persisted_workdir: str = ""
41
47
  user: str = ""
42
48
  parent_hash: str = ""
43
49
  # Sealed build stages: every FROM past the first closes the stage
@@ -45,13 +51,24 @@ class BuildContext:
45
51
  # indexes the same images for numeric `COPY --from=N` references.
46
52
  stages: dict[str, str] = field(default_factory=dict)
47
53
  stage_images: list[str] = field(default_factory=list)
54
+ stage_settings: dict[str, tuple[str, dict[str, str]]] = field(default_factory=dict)
48
55
  current_stage_alias: str = ""
49
56
  pending: list[PendingFile] = field(default_factory=list)
57
+ archives: list[StagedArchive | StagedLink] = field(default_factory=list)
50
58
  no_cache: bool = False
51
59
  timeout: int = BUILD_TIMEOUT_DEFAULT
52
60
  last_image: str = ""
53
61
  last_op_uuid: str = ""
54
62
 
63
+ def resolve_workdir(self) -> str:
64
+ """Resolve an inherited working directory only when a path needs it."""
65
+ if not self.workdir:
66
+ from .transfer import read_image_workdir
67
+
68
+ self.workdir = read_image_workdir(self)
69
+ self.persisted_workdir = self.workdir
70
+ return self.workdir
71
+
55
72
  def arg_values(self) -> dict[str, str]:
56
73
  """Effective values for every declared ARG (build-arg overrides default)."""
57
74
  return {
@@ -85,9 +102,11 @@ class BuildContext:
85
102
  "uid": p.uid,
86
103
  "gid": p.gid,
87
104
  "mode": p.mode,
105
+ "replace_existing": p.replace_existing,
88
106
  }
89
107
  for p in self.pending
90
- ],
108
+ ]
109
+ + [archive.cache_repr() for archive in self.archives],
91
110
  sort_keys=True,
92
111
  )
93
112
 
@@ -45,14 +45,47 @@ def parse_dockerignore(context_dir: Path) -> tuple[DockerignoreRule, ...]:
45
45
 
46
46
 
47
47
  def is_ignored(rel_path: str, rules: tuple[DockerignoreRule, ...]) -> bool:
48
- """Apply rules in order; last match wins (negation re-includes)."""
48
+ """Apply ordered rules to the path and its parents; the last match wins."""
49
+ parts = rel_path.split("/")
50
+ candidates = ["/".join(parts[:index]) for index in range(1, len(parts) + 1)]
49
51
  ignored = False
50
52
  for rule in rules:
51
- if rule.regex.fullmatch(rel_path):
53
+ if any(rule.regex.fullmatch(candidate) for candidate in candidates):
52
54
  ignored = not rule.negate
53
55
  return ignored
54
56
 
55
57
 
58
+ def may_include_descendants(rel_path: str, rules: tuple[DockerignoreRule, ...]) -> bool:
59
+ """Keep an ignored directory only if a later exception can reach inside it."""
60
+ parts = rel_path.split("/")
61
+ candidates = ["/".join(parts[:index]) for index in range(1, len(parts) + 1)]
62
+ last_match = -1
63
+ for index, rule in enumerate(rules):
64
+ if any(rule.regex.fullmatch(candidate) for candidate in candidates):
65
+ last_match = index
66
+ if last_match < 0 or rules[last_match].negate:
67
+ return True
68
+ return any(
69
+ rule.negate
70
+ and pattern_may_match_descendant(rule.raw.strip()[1:].strip(), rel_path)
71
+ for rule in rules[last_match + 1 :]
72
+ )
73
+
74
+
75
+ def pattern_may_match_descendant(pattern: str, rel_path: str) -> bool:
76
+ """Compare fixed components; retain ambiguous patterns that can cross '/'."""
77
+ components = pattern.strip("/").split("/")
78
+ for pattern_part, path_part in zip(components, rel_path.split("/"), strict=False):
79
+ unfinished_class = any(
80
+ "]" not in suffix for suffix in pattern_part.split("[")[1:]
81
+ )
82
+ if "**" in pattern_part or unfinished_class:
83
+ return True
84
+ if re.fullmatch(pattern_to_regex(pattern_part), path_part) is None:
85
+ return False
86
+ return True
87
+
88
+
56
89
  def pattern_to_regex(pattern: str) -> str:
57
90
  """Translate a ``.dockerignore`` glob into a Python regex string.
58
91
 
@@ -60,7 +60,9 @@ class AddKeyword(DockerKeyword):
60
60
 
61
61
  sub_dest = ctx.substitute(self.dest)
62
62
  if not posixpath.isabs(sub_dest):
63
- sub_dest = posixpath.normpath(posixpath.join(ctx.workdir or "/", sub_dest))
63
+ sub_dest = posixpath.normpath(
64
+ posixpath.join(ctx.resolve_workdir(), sub_dest)
65
+ )
64
66
 
65
67
  local_sources: list[str] = []
66
68
  url_sources: list[str] = []