| 1 |
# This code is part of the Ansible collection community.docker, but is an independent component. |
| 2 |
# This particular file, and this file only, is based on the Docker SDK for Python (https://github.com/docker/docker-py/) |
| 3 |
# |
| 4 |
# Copyright (c) 2016-2022 Docker, Inc. |
| 5 |
# |
| 6 |
# It is licensed under the Apache 2.0 license (see LICENSES/Apache-2.0.txt in this collection) |
| 7 |
# SPDX-License-Identifier: Apache-2.0 |
| 8 |
|
| 9 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 10 |
# Do not use this from other collections or standalone plugins/modules! |
| 11 |
|
| 12 |
from __future__ import annotations |
| 13 |
|
| 14 |
import io |
| 15 |
import os |
| 16 |
import random |
| 17 |
import re |
| 18 |
import tarfile |
| 19 |
import tempfile |
| 20 |
import typing as t |
| 21 |
|
| 22 |
from ..constants import IS_WINDOWS_PLATFORM, WINDOWS_LONGPATH_PREFIX |
| 23 |
from . import fnmatch |
| 24 |
|
| 25 |
if t.TYPE_CHECKING: |
| 26 |
from collections.abc import Sequence |
| 27 |
|
| 28 |
|
| 29 |
_SEP = re.compile("/|\\\\") if IS_WINDOWS_PLATFORM else re.compile("/") |
| 30 |
|
| 31 |
|
| 32 |
def tar( |
| 33 |
path: str, |
| 34 |
exclude: list[str] | None = None, |
| 35 |
dockerfile: tuple[str, str | None] | tuple[None, None] | None = None, |
| 36 |
fileobj: t.IO[bytes] | None = None, |
| 37 |
gzip: bool = False, |
| 38 |
) -> t.IO[bytes]: |
| 39 |
root = os.path.abspath(path) |
| 40 |
exclude = exclude or [] |
| 41 |
dockerfile = dockerfile or (None, None) |
| 42 |
extra_files: list[tuple[str, str]] = [] |
| 43 |
if dockerfile[1] is not None: |
| 44 |
assert dockerfile[0] is not None |
| 45 |
dockerignore_contents = "\n".join( |
| 46 |
(exclude or [".dockerignore"]) + [dockerfile[0]] |
| 47 |
) |
| 48 |
extra_files = [ |
| 49 |
(".dockerignore", dockerignore_contents), |
| 50 |
dockerfile, # type: ignore |
| 51 |
] |
| 52 |
return create_archive( |
| 53 |
files=sorted(exclude_paths(root, exclude, dockerfile=dockerfile[0])), |
| 54 |
root=root, |
| 55 |
fileobj=fileobj, |
| 56 |
gzip=gzip, |
| 57 |
extra_files=extra_files, |
| 58 |
) |
| 59 |
|
| 60 |
|
| 61 |
def exclude_paths( |
| 62 |
root: str, patterns: list[str], dockerfile: str | None = None |
| 63 |
) -> set[str]: |
| 64 |
""" |
| 65 |
Given a root directory path and a list of .dockerignore patterns, return |
| 66 |
an iterator of all paths (both regular files and directories) in the root |
| 67 |
directory that do *not* match any of the patterns. |
| 68 |
|
| 69 |
All paths returned are relative to the root. |
| 70 |
""" |
| 71 |
|
| 72 |
if dockerfile is None: |
| 73 |
dockerfile = "Dockerfile" |
| 74 |
|
| 75 |
patterns.append("!" + dockerfile) |
| 76 |
pm = PatternMatcher(patterns) |
| 77 |
return set(pm.walk(root)) |
| 78 |
|
| 79 |
|
| 80 |
def build_file_list(root: str) -> list[str]: |
| 81 |
files = [] |
| 82 |
for dirname, dirnames, fnames in os.walk(root): |
| 83 |
for filename in fnames + dirnames: |
| 84 |
longpath = os.path.join(dirname, filename) |
| 85 |
files.append(longpath.replace(root, "", 1).lstrip("/")) |
| 86 |
|
| 87 |
return files |
| 88 |
|
| 89 |
|
| 90 |
def create_archive( |
| 91 |
root: str, |
| 92 |
files: Sequence[str] | None = None, |
| 93 |
fileobj: t.IO[bytes] | None = None, |
| 94 |
gzip: bool = False, |
| 95 |
extra_files: Sequence[tuple[str, str]] | None = None, |
| 96 |
) -> t.IO[bytes]: |
| 97 |
extra_files = extra_files or [] |
| 98 |
if not fileobj: |
| 99 |
# pylint: disable-next=consider-using-with |
| 100 |
fileobj = tempfile.NamedTemporaryFile() # noqa: SIM115 |
| 101 |
|
| 102 |
with tarfile.open(mode="w:gz" if gzip else "w", fileobj=fileobj) as tarf: |
| 103 |
if files is None: |
| 104 |
files = build_file_list(root) |
| 105 |
extra_names = set(e[0] for e in extra_files) |
| 106 |
for path in files: |
| 107 |
if path in extra_names: |
| 108 |
# Extra files override context files with the same name |
| 109 |
continue |
| 110 |
full_path = os.path.join(root, path) |
| 111 |
|
| 112 |
i = tarf.gettarinfo(full_path, arcname=path) |
| 113 |
if i is None: |
| 114 |
# This happens when we encounter a socket file. We can safely |
| 115 |
# ignore it and proceed. |
| 116 |
continue # type: ignore |
| 117 |
|
| 118 |
# Workaround https://bugs.python.org/issue32713 |
| 119 |
if i.mtime < 0 or i.mtime > 8**11 - 1: |
| 120 |
i.mtime = int(i.mtime) |
| 121 |
|
| 122 |
if IS_WINDOWS_PLATFORM: |
| 123 |
# Windows does not keep track of the execute bit, so we make files |
| 124 |
# and directories executable by default. |
| 125 |
i.mode = i.mode & 0o755 | 0o111 |
| 126 |
|
| 127 |
if i.isfile(): |
| 128 |
try: |
| 129 |
with open(full_path, "rb") as f: |
| 130 |
tarf.addfile(i, f) |
| 131 |
except IOError as exc: |
| 132 |
raise IOError(f"Can not read file in context: {full_path}") from exc |
| 133 |
else: |
| 134 |
# Directories, FIFOs, symlinks... do not need to be read. |
| 135 |
tarf.addfile(i, None) |
| 136 |
|
| 137 |
for name, contents in extra_files: |
| 138 |
info = tarfile.TarInfo(name) |
| 139 |
contents_encoded = contents.encode("utf-8") |
| 140 |
info.size = len(contents_encoded) |
| 141 |
tarf.addfile(info, io.BytesIO(contents_encoded)) |
| 142 |
|
| 143 |
fileobj.seek(0) |
| 144 |
return fileobj |
| 145 |
|
| 146 |
|
| 147 |
def mkbuildcontext(dockerfile: io.BytesIO | t.IO[bytes]) -> t.IO[bytes]: |
| 148 |
# pylint: disable-next=consider-using-with |
| 149 |
f = tempfile.NamedTemporaryFile() # noqa: SIM115 |
| 150 |
try: |
| 151 |
with tarfile.open(mode="w", fileobj=f) as tarf: |
| 152 |
if isinstance(dockerfile, io.StringIO): # type: ignore |
| 153 |
raise TypeError("Please use io.BytesIO to create in-memory Dockerfiles") |
| 154 |
if isinstance(dockerfile, io.BytesIO): |
| 155 |
dfinfo = tarfile.TarInfo("Dockerfile") |
| 156 |
dfinfo.size = len(dockerfile.getvalue()) |
| 157 |
dockerfile.seek(0) |
| 158 |
else: |
| 159 |
dfinfo = tarf.gettarinfo(fileobj=dockerfile, arcname="Dockerfile") |
| 160 |
tarf.addfile(dfinfo, dockerfile) |
| 161 |
f.seek(0) |
| 162 |
except Exception: # noqa: E722 |
| 163 |
f.close() |
| 164 |
raise |
| 165 |
return f |
| 166 |
|
| 167 |
|
| 168 |
def split_path(p: str) -> list[str]: |
| 169 |
return [pt for pt in re.split(_SEP, p) if pt and pt != "."] |
| 170 |
|
| 171 |
|
| 172 |
def normalize_slashes(p: str) -> str: |
| 173 |
if IS_WINDOWS_PLATFORM: |
| 174 |
return "/".join(split_path(p)) |
| 175 |
return p |
| 176 |
|
| 177 |
|
| 178 |
def walk(root: str, patterns: Sequence[str], default: bool = True) -> t.Generator[str]: |
| 179 |
pm = PatternMatcher(patterns) |
| 180 |
return pm.walk(root) |
| 181 |
|
| 182 |
|
| 183 |
# Heavily based on |
| 184 |
# https://github.com/moby/moby/blob/master/pkg/fileutils/fileutils.go |
| 185 |
class PatternMatcher: |
| 186 |
def __init__(self, patterns: Sequence[str]) -> None: |
| 187 |
self.patterns = list(filter(lambda p: p.dirs, [Pattern(p) for p in patterns])) |
| 188 |
self.patterns.append(Pattern("!.dockerignore")) |
| 189 |
|
| 190 |
def matches(self, filepath: str) -> bool: |
| 191 |
matched = False |
| 192 |
parent_path = os.path.dirname(filepath) |
| 193 |
parent_path_dirs = split_path(parent_path) |
| 194 |
|
| 195 |
for pattern in self.patterns: |
| 196 |
negative = pattern.exclusion |
| 197 |
match = pattern.match(filepath) |
| 198 |
if ( |
| 199 |
not match |
| 200 |
and parent_path != "" |
| 201 |
and len(pattern.dirs) <= len(parent_path_dirs) |
| 202 |
): |
| 203 |
match = pattern.match( |
| 204 |
os.path.sep.join(parent_path_dirs[: len(pattern.dirs)]) |
| 205 |
) |
| 206 |
|
| 207 |
if match: |
| 208 |
matched = not negative |
| 209 |
|
| 210 |
return matched |
| 211 |
|
| 212 |
def walk(self, root: str) -> t.Generator[str]: |
| 213 |
def rec_walk(current_dir: str) -> t.Generator[str]: |
| 214 |
for f in os.listdir(current_dir): |
| 215 |
fpath = os.path.join(os.path.relpath(current_dir, root), f) |
| 216 |
if fpath.startswith("." + os.path.sep): |
| 217 |
fpath = fpath[2:] |
| 218 |
match = self.matches(fpath) |
| 219 |
if not match: |
| 220 |
yield fpath |
| 221 |
|
| 222 |
cur = os.path.join(root, fpath) |
| 223 |
if not os.path.isdir(cur) or os.path.islink(cur): |
| 224 |
continue |
| 225 |
|
| 226 |
if match: |
| 227 |
# If we want to skip this file and it is a directory |
| 228 |
# then we should first check to see if there's an |
| 229 |
# excludes pattern (e.g. !dir/file) that starts with this |
| 230 |
# dir. If so then we cannot skip this dir. |
| 231 |
skip = True |
| 232 |
|
| 233 |
for pat in self.patterns: |
| 234 |
if not pat.exclusion: |
| 235 |
continue |
| 236 |
if pat.cleaned_pattern.startswith(normalize_slashes(fpath)): |
| 237 |
skip = False |
| 238 |
break |
| 239 |
if skip: |
| 240 |
continue |
| 241 |
yield from rec_walk(cur) |
| 242 |
|
| 243 |
return rec_walk(root) |
| 244 |
|
| 245 |
|
| 246 |
class Pattern: |
| 247 |
def __init__(self, pattern_str: str) -> None: |
| 248 |
self.exclusion = False |
| 249 |
if pattern_str.startswith("!"): |
| 250 |
self.exclusion = True |
| 251 |
pattern_str = pattern_str[1:] |
| 252 |
|
| 253 |
self.dirs = self.normalize(pattern_str) |
| 254 |
self.cleaned_pattern = "/".join(self.dirs) |
| 255 |
|
| 256 |
@classmethod |
| 257 |
def normalize(cls, p: str) -> list[str]: |
| 258 |
# Remove trailing spaces |
| 259 |
p = p.strip() |
| 260 |
|
| 261 |
# Leading and trailing slashes are not relevant. Yes, |
| 262 |
# "foo.py/" must exclude the "foo.py" regular file. "." |
| 263 |
# components are not relevant either, even if the whole |
| 264 |
# pattern is only ".", as the Docker reference states: "For |
| 265 |
# historical reasons, the pattern . is ignored." |
| 266 |
# ".." component must be cleared with the potential previous |
| 267 |
# component, regardless of whether it exists: "A preprocessing |
| 268 |
# step [...] eliminates . and .. elements using Go's |
| 269 |
# filepath.". |
| 270 |
i = 0 |
| 271 |
split = split_path(p) |
| 272 |
while i < len(split): |
| 273 |
if split[i] == "..": |
| 274 |
del split[i] |
| 275 |
if i > 0: |
| 276 |
del split[i - 1] |
| 277 |
i -= 1 |
| 278 |
else: |
| 279 |
i += 1 |
| 280 |
return split |
| 281 |
|
| 282 |
def match(self, filepath: str) -> bool: |
| 283 |
return fnmatch.fnmatch(normalize_slashes(filepath), self.cleaned_pattern) |
| 284 |
|
| 285 |
|
| 286 |
def process_dockerfile( |
| 287 |
dockerfile: str | None, path: str |
| 288 |
) -> tuple[str, str | None] | tuple[None, None]: |
| 289 |
if not dockerfile: |
| 290 |
return (None, None) |
| 291 |
|
| 292 |
abs_dockerfile = dockerfile |
| 293 |
if not os.path.isabs(dockerfile): |
| 294 |
abs_dockerfile = os.path.join(path, dockerfile) |
| 295 |
if IS_WINDOWS_PLATFORM and path.startswith(WINDOWS_LONGPATH_PREFIX): |
| 296 |
abs_dockerfile = f"{WINDOWS_LONGPATH_PREFIX}{os.path.normpath(abs_dockerfile[len(WINDOWS_LONGPATH_PREFIX) :])}" |
| 297 |
if os.path.splitdrive(path)[0] != os.path.splitdrive(abs_dockerfile)[ |
| 298 |
0 |
| 299 |
] or os.path.relpath(abs_dockerfile, path).startswith(".."): |
| 300 |
# Dockerfile not in context - read data to insert into tar later |
| 301 |
with open(abs_dockerfile, "rt", encoding="utf-8") as df: |
| 302 |
return (f".dockerfile.{random.getrandbits(160):x}", df.read()) |
| 303 |
|
| 304 |
# Dockerfile is inside the context - return path relative to context root |
| 305 |
if dockerfile == abs_dockerfile: |
| 306 |
# Only calculate relpath if necessary to avoid errors |
| 307 |
# on Windows client -> Linux Docker |
| 308 |
# see https://github.com/docker/compose/issues/5969 |
| 309 |
dockerfile = os.path.relpath(abs_dockerfile, path) |
| 310 |
return (dockerfile, None) |