feat: Use docker api to pull files from container
This commit is contained in:
@@ -172,6 +172,42 @@ class DockerSandbox:
|
||||
# File I/O
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _resolve_path(self, path: str) -> Path:
|
||||
"""Resolve *path* against working_dir if relative."""
|
||||
p = Path(path)
|
||||
if not p.is_absolute() and self._working_dir is not None:
|
||||
p = Path(self._working_dir) / p
|
||||
return p
|
||||
|
||||
def read_file(self, path: str) -> bytes:
|
||||
"""
|
||||
Read the file at *path* from the container using ``get_archive``.
|
||||
|
||||
Returns the raw file bytes. Raises ``FileNotFoundError`` if the path
|
||||
does not exist and ``RuntimeError`` if the container is not running.
|
||||
"""
|
||||
if self._container is None:
|
||||
raise RuntimeError("Sandbox container is not running.")
|
||||
|
||||
p = self._resolve_path(path)
|
||||
|
||||
try:
|
||||
stream, _ = self._container.get_archive(str(p))
|
||||
except docker.errors.NotFound:
|
||||
raise FileNotFoundError(f"No such file in container: {path!r}") from None
|
||||
|
||||
buf = io.BytesIO()
|
||||
for chunk in stream:
|
||||
buf.write(chunk)
|
||||
buf.seek(0)
|
||||
|
||||
with tarfile.open(fileobj=buf) as tar:
|
||||
member = tar.getmembers()[0]
|
||||
f = tar.extractfile(member)
|
||||
if f is None:
|
||||
raise IsADirectoryError(f"{path!r} is a directory, not a file")
|
||||
return f.read()
|
||||
|
||||
def write_file(self, path: str, content: str) -> None:
|
||||
"""
|
||||
Write *content* to *path* inside the container using ``put_archive``.
|
||||
@@ -182,9 +218,7 @@ class DockerSandbox:
|
||||
if self._container is None:
|
||||
raise RuntimeError("Sandbox container is not running.")
|
||||
|
||||
p = Path(path)
|
||||
if not p.is_absolute() and self._working_dir is not None:
|
||||
p = Path(self._working_dir) / p
|
||||
p = self._resolve_path(path)
|
||||
encoded = content.encode("utf-8")
|
||||
|
||||
self._container.exec_run(["mkdir", "-p", str(p.parent)])
|
||||
|
||||
Reference in New Issue
Block a user