Copy a file or directory from the local filesystem to a Docker container. The copy operation is recursive for directories. Be extremely careful with trailing slashes in src_path and dest_path, the behavior of docker cp is also different depending on whether the destination exists.
(
container: DockerEnvironment,
src_path: str | Path,
dest_path: str | Path,
)
| 100 | |
| 101 | |
| 102 | def copy_to_container( |
| 103 | container: DockerEnvironment, |
| 104 | src_path: str | Path, |
| 105 | dest_path: str | Path, |
| 106 | ): |
| 107 | """ |
| 108 | Copy a file or directory from the local filesystem to a Docker container. |
| 109 | |
| 110 | The copy operation is recursive for directories. |
| 111 | |
| 112 | Be extremely careful with trailing slashes in src_path and dest_path, the behavior |
| 113 | of docker cp is also different depending on whether the destination exists. |
| 114 | """ |
| 115 | if not str(dest_path).startswith("/"): |
| 116 | # If not an absolute path, assume relative to container's cwd |
| 117 | dest_path = f"{container.config.cwd}/{dest_path}" |
| 118 | cmd = [ |
| 119 | "docker", |
| 120 | "cp", |
| 121 | str(src_path), |
| 122 | f"{container.container_id}:{dest_path}", |
| 123 | ] |
| 124 | print(f"Copy to container: cmd={cmd}") |
| 125 | # Ensure destination folder exists |
| 126 | assert_zero_exit_code(container.execute(f"mkdir -p {Path(dest_path).parent}")) |
| 127 | result = subprocess.run(cmd, check=False, capture_output=True, text=True) |
| 128 | if result.returncode != 0: |
| 129 | raise RuntimeError( |
| 130 | f"Failed to copy {src_path} to {container.container_id}:{dest_path}: {result.stdout}{result.stderr}" |
| 131 | ) |
| 132 | return result |
| 133 | |
| 134 | |
| 135 | def copy_from_container( |
no test coverage detected