flat-packager 0.5.0__tar.gz → 0.5.2__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.
- {flat_packager-0.5.0/src/flat_packager.egg-info → flat_packager-0.5.2}/PKG-INFO +7 -1
- {flat_packager-0.5.0 → flat_packager-0.5.2}/README.md +6 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/pyproject.toml +1 -1
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager/__init__.py +1 -1
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager/inspect.py +2 -10
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager/markdown.py +3 -9
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager/pack.py +11 -13
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager/text_encoding.py +33 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager/unpack.py +50 -21
- {flat_packager-0.5.0 → flat_packager-0.5.2/src/flat_packager.egg-info}/PKG-INFO +7 -1
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager.egg-info/SOURCES.txt +3 -1
- {flat_packager-0.5.0 → flat_packager-0.5.2}/tests/test_pack.py +83 -32
- {flat_packager-0.5.0 → flat_packager-0.5.2}/tests/test_restore_fuzz.py +31 -7
- {flat_packager-0.5.0 → flat_packager-0.5.2}/tests/test_roundtrip.py +1 -0
- flat_packager-0.5.2/tests/test_text_encoding.py +108 -0
- flat_packager-0.5.2/tests/test_windows_paths.py +191 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/LICENSE +0 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/setup.cfg +0 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager/archive.py +0 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager/content.py +0 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager/patterns.py +0 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager/secret_files.py +0 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager/verify.py +0 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager.egg-info/dependency_links.txt +0 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager.egg-info/entry_points.txt +0 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager.egg-info/requires.txt +0 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/src/flat_packager.egg-info/top_level.txt +0 -0
- {flat_packager-0.5.0 → flat_packager-0.5.2}/tests/test_markdown.py +1 -1
- {flat_packager-0.5.0 → flat_packager-0.5.2}/tests/test_version.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: flat-packager
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.2
|
|
4
4
|
Summary: Pack a repository into one flat text archive and restore it later.
|
|
5
5
|
Author: Thomas
|
|
6
6
|
License-Expression: MIT
|
|
@@ -355,6 +355,12 @@ As a second layer, restores create directories one component at a time without
|
|
|
355
355
|
following symlinks and create files exclusively (`O_EXCL`/`O_NOFOLLOW`). Writes
|
|
356
356
|
therefore cannot be routed outside the output directory, including through
|
|
357
357
|
names that collide on case-insensitive filesystems such as default macOS.
|
|
358
|
+
Every path component is joined only if it stays inside its parent directory.
|
|
359
|
+
|
|
360
|
+
On Windows, restores also reject names Windows cannot store safely: names
|
|
361
|
+
containing `:` (drive-relative paths such as `D:x`, or alternate data
|
|
362
|
+
streams), other characters Windows forbids, reserved device names such as
|
|
363
|
+
`NUL` or `aux.py`, and names ending in a dot or space.
|
|
358
364
|
|
|
359
365
|
[docs/FORMAT.md](docs/FORMAT.md#7-validation-performed-on-restore) lists
|
|
360
366
|
every validation rule.
|
|
@@ -320,6 +320,12 @@ As a second layer, restores create directories one component at a time without
|
|
|
320
320
|
following symlinks and create files exclusively (`O_EXCL`/`O_NOFOLLOW`). Writes
|
|
321
321
|
therefore cannot be routed outside the output directory, including through
|
|
322
322
|
names that collide on case-insensitive filesystems such as default macOS.
|
|
323
|
+
Every path component is joined only if it stays inside its parent directory.
|
|
324
|
+
|
|
325
|
+
On Windows, restores also reject names Windows cannot store safely: names
|
|
326
|
+
containing `:` (drive-relative paths such as `D:x`, or alternate data
|
|
327
|
+
streams), other characters Windows forbids, reserved device names such as
|
|
328
|
+
`NUL` or `aux.py`, and names ending in a dot or space.
|
|
323
329
|
|
|
324
330
|
[docs/FORMAT.md](docs/FORMAT.md#7-validation-performed-on-restore) lists
|
|
325
331
|
every validation rule.
|
|
@@ -42,19 +42,11 @@ def human_size(size: int) -> str:
|
|
|
42
42
|
|
|
43
43
|
|
|
44
44
|
def file_records(manifest: ArchiveManifest) -> list[dict[str, Any]]:
|
|
45
|
-
return [
|
|
46
|
-
record
|
|
47
|
-
for _line_number, record in manifest.records
|
|
48
|
-
if record.get("type") == "file"
|
|
49
|
-
]
|
|
45
|
+
return [record for _line_number, record in manifest.records if record.get("type") == "file"]
|
|
50
46
|
|
|
51
47
|
|
|
52
48
|
def symlink_records(manifest: ArchiveManifest) -> list[dict[str, Any]]:
|
|
53
|
-
return [
|
|
54
|
-
record
|
|
55
|
-
for _line_number, record in manifest.records
|
|
56
|
-
if record.get("type") == "symlink"
|
|
57
|
-
]
|
|
49
|
+
return [record for _line_number, record in manifest.records if record.get("type") == "symlink"]
|
|
58
50
|
|
|
59
51
|
|
|
60
52
|
def inspect_data(archive_path: Path, manifest: ArchiveManifest) -> dict[str, Any]:
|
|
@@ -264,9 +264,7 @@ def write_file_body(
|
|
|
264
264
|
raise changed_while_packing(rel)
|
|
265
265
|
ensure_unchanged(fd, before, rel)
|
|
266
266
|
reason = (
|
|
267
|
-
f"text, larger than {human_size(max_inline_text_bytes)}"
|
|
268
|
-
if kind == "text"
|
|
269
|
-
else "binary"
|
|
267
|
+
f"text, larger than {human_size(max_inline_text_bytes)}" if kind == "text" else "binary"
|
|
270
268
|
)
|
|
271
269
|
return (
|
|
272
270
|
f"- {code_span(rel)}: {reason}, {expected} bytes, sha256 `{digest.hexdigest()}`",
|
|
@@ -296,9 +294,7 @@ def build_markdown(
|
|
|
296
294
|
"""Write a one-way Markdown export of ``root``; return (entries, files)."""
|
|
297
295
|
from . import __version__
|
|
298
296
|
|
|
299
|
-
include_patterns, subdir = normalise_selection(
|
|
300
|
-
root, exclude_patterns, include_patterns, subdir
|
|
301
|
-
)
|
|
297
|
+
include_patterns, subdir = normalise_selection(root, exclude_patterns, include_patterns, subdir)
|
|
302
298
|
if max_inline_text_bytes < 0:
|
|
303
299
|
raise ValueError("max_inline_text_bytes must not be negative")
|
|
304
300
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
@@ -381,9 +377,7 @@ def build_markdown(
|
|
|
381
377
|
"left out of Markdown exports. Use `--no-default-excludes` to "
|
|
382
378
|
"include them.\n\n"
|
|
383
379
|
)
|
|
384
|
-
handle.write(
|
|
385
|
-
"\n".join(f"- {code_span(rel)}" for rel in sorted(skipped)) + "\n"
|
|
386
|
-
)
|
|
380
|
+
handle.write("\n".join(f"- {code_span(rel)}" for rel in sorted(skipped)) + "\n")
|
|
387
381
|
except BaseException:
|
|
388
382
|
remove_failed_output(output_path)
|
|
389
383
|
raise
|
|
@@ -208,8 +208,10 @@ def looks_like_git_source(source: str) -> bool:
|
|
|
208
208
|
|
|
209
209
|
|
|
210
210
|
def normalize_source(source: str) -> str:
|
|
211
|
-
if
|
|
212
|
-
|
|
211
|
+
if (
|
|
212
|
+
"/" in source
|
|
213
|
+
and not Path(source).exists()
|
|
214
|
+
and not source.startswith(("http://", "https://", "ssh://", "git@"))
|
|
213
215
|
):
|
|
214
216
|
owner, repo = source.split("/", 1)
|
|
215
217
|
return f"https://github.com/{owner}/{repo}.git"
|
|
@@ -438,9 +440,7 @@ def git_ls_files(worktree: Path, *args: str) -> list[str]:
|
|
|
438
440
|
message = exc.stderr.decode("utf-8", errors="replace").strip()
|
|
439
441
|
raise ValueError(f"git ls-files failed while reading .gitignore rules: {message}") from exc
|
|
440
442
|
return [
|
|
441
|
-
raw.decode("utf-8", errors="surrogateescape")
|
|
442
|
-
for raw in result.stdout.split(b"\0")
|
|
443
|
-
if raw
|
|
443
|
+
raw.decode("utf-8", errors="surrogateescape") for raw in result.stdout.split(b"\0") if raw
|
|
444
444
|
]
|
|
445
445
|
|
|
446
446
|
|
|
@@ -898,8 +898,10 @@ def select_paths(
|
|
|
898
898
|
``tracked_only``) the file list are raised or computed by the call itself,
|
|
899
899
|
so callers can call it before they open, and truncate, the output.
|
|
900
900
|
"""
|
|
901
|
-
if
|
|
902
|
-
|
|
901
|
+
if (
|
|
902
|
+
subdir is not None
|
|
903
|
+
and not include_git
|
|
904
|
+
and any(is_git_metadata_name(part) for part in subdir.split("/"))
|
|
903
905
|
):
|
|
904
906
|
raise ValueError(f"--subdir {subdir} is git metadata; pass --include-git to pack it")
|
|
905
907
|
|
|
@@ -936,9 +938,7 @@ def select_paths(
|
|
|
936
938
|
if ignored and any(
|
|
937
939
|
ignore_key("/".join(parts[: i + 1])) in ignored for i in range(len(parts))
|
|
938
940
|
):
|
|
939
|
-
raise ValueError(
|
|
940
|
-
f"--subdir {subdir} is ignored by .gitignore (use --no-gitignore)"
|
|
941
|
-
)
|
|
941
|
+
raise ValueError(f"--subdir {subdir} is ignored by .gitignore (use --no-gitignore)")
|
|
942
942
|
start = root.joinpath(*parts)
|
|
943
943
|
walked = walked_paths(
|
|
944
944
|
root,
|
|
@@ -1025,9 +1025,7 @@ def build_archive(
|
|
|
1025
1025
|
raise ValueError("max_inline_text_bytes must not be negative")
|
|
1026
1026
|
if text_encoding not in TEXT_ENCODING_CHOICES:
|
|
1027
1027
|
raise ValueError(f"unsupported text encoding mode: {text_encoding}")
|
|
1028
|
-
include_patterns, subdir = normalise_selection(
|
|
1029
|
-
root, exclude_patterns, include_patterns, subdir
|
|
1030
|
-
)
|
|
1028
|
+
include_patterns, subdir = normalise_selection(root, exclude_patterns, include_patterns, subdir)
|
|
1031
1029
|
|
|
1032
1030
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
1033
1031
|
|
|
@@ -64,6 +64,34 @@ TEXT_FILENAMES = frozenset(
|
|
|
64
64
|
}
|
|
65
65
|
)
|
|
66
66
|
|
|
67
|
+
# Dotfiles have no suffix as far as PurePosixPath is concerned
|
|
68
|
+
# (PurePosixPath(".gitignore").suffix == ""), so match them by exact name.
|
|
69
|
+
TEXT_DOTFILES = frozenset(
|
|
70
|
+
{
|
|
71
|
+
".bashrc",
|
|
72
|
+
".clang-format",
|
|
73
|
+
".dockerignore",
|
|
74
|
+
".editorconfig",
|
|
75
|
+
".env",
|
|
76
|
+
".eslintignore",
|
|
77
|
+
".eslintrc",
|
|
78
|
+
".flake8",
|
|
79
|
+
".gitattributes",
|
|
80
|
+
".gitignore",
|
|
81
|
+
".gitmodules",
|
|
82
|
+
".mailmap",
|
|
83
|
+
".npmignore",
|
|
84
|
+
".npmrc",
|
|
85
|
+
".nvmrc",
|
|
86
|
+
".prettierignore",
|
|
87
|
+
".prettierrc",
|
|
88
|
+
".pylintrc",
|
|
89
|
+
".python-version",
|
|
90
|
+
".tool-versions",
|
|
91
|
+
".zshrc",
|
|
92
|
+
}
|
|
93
|
+
)
|
|
94
|
+
|
|
67
95
|
TEXT_ENCODING_CHOICES = frozenset({"base64", "auto", "utf8"})
|
|
68
96
|
|
|
69
97
|
|
|
@@ -83,6 +111,11 @@ def path_looks_like_text(rel_path: str) -> bool:
|
|
|
83
111
|
return True
|
|
84
112
|
if name.startswith("README."):
|
|
85
113
|
return True
|
|
114
|
+
if name.lower() in TEXT_DOTFILES:
|
|
115
|
+
return True
|
|
116
|
+
if name.lower().startswith(".env."):
|
|
117
|
+
# .env.example, .env.local, .env.production, ...
|
|
118
|
+
return True
|
|
86
119
|
suffix = PurePosixPath(rel_path).suffix.lower()
|
|
87
120
|
return suffix in TEXT_EXTENSIONS
|
|
88
121
|
|
|
@@ -22,6 +22,12 @@ ArchiveRecord = tuple[int, dict[str, Any]]
|
|
|
22
22
|
|
|
23
23
|
O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
|
|
24
24
|
O_BINARY = getattr(os, "O_BINARY", 0)
|
|
25
|
+
IS_WINDOWS = os.name == "nt"
|
|
26
|
+
WINDOWS_FORBIDDEN_CHARS = frozenset('<>:"|?*')
|
|
27
|
+
WINDOWS_RESERVED_NAMES = frozenset(
|
|
28
|
+
{"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"}
|
|
29
|
+
| {f"{prefix}{suffix}" for prefix in ("COM", "LPT") for suffix in "123456789\u00b9\u00b2\u00b3"}
|
|
30
|
+
)
|
|
25
31
|
PERMISSION_BITS = 0o777
|
|
26
32
|
ALL_MODE_BITS = 0o7777
|
|
27
33
|
|
|
@@ -109,9 +115,44 @@ def safe_relative_parts(rel_path: str) -> tuple[str, ...]:
|
|
|
109
115
|
parts = tuple(rel_path.split("/"))
|
|
110
116
|
if any(part in ("", ".", "..") for part in parts):
|
|
111
117
|
raise ValueError(f"unsafe archive path: {rel_path}")
|
|
118
|
+
if IS_WINDOWS:
|
|
119
|
+
for part in parts:
|
|
120
|
+
reason = windows_unsafe_reason(part)
|
|
121
|
+
if reason is not None:
|
|
122
|
+
raise ValueError(f"unsafe archive path on Windows ({reason}): {rel_path}")
|
|
112
123
|
return parts
|
|
113
124
|
|
|
114
125
|
|
|
126
|
+
def windows_unsafe_reason(part: str) -> str | None:
|
|
127
|
+
"""Why ``part`` cannot be restored safely on Windows, or None if it can.
|
|
128
|
+
|
|
129
|
+
``:`` makes a drive-relative path (``D:x``) or an NTFS alternate data
|
|
130
|
+
stream (``file:stream``); device names such as ``NUL`` or ``aux.py``
|
|
131
|
+
address devices instead of files; trailing dots and spaces are silently
|
|
132
|
+
stripped, so ``name.`` would become ``name``.
|
|
133
|
+
"""
|
|
134
|
+
bad = sorted({char for char in part if char in WINDOWS_FORBIDDEN_CHARS or ord(char) < 32})
|
|
135
|
+
if bad:
|
|
136
|
+
return "forbidden character " + ", ".join(repr(char) for char in bad)
|
|
137
|
+
if part.endswith((".", " ")):
|
|
138
|
+
return "trailing dot or space"
|
|
139
|
+
if part.split(".", 1)[0].rstrip(" ").upper() in WINDOWS_RESERVED_NAMES:
|
|
140
|
+
return "reserved device name"
|
|
141
|
+
return None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def join_component(parent: Path, part: str) -> Path:
|
|
145
|
+
"""Join one validated component, refusing joins that leave ``parent``.
|
|
146
|
+
|
|
147
|
+
Platform-independent second layer: on Windows a component such as ``D:x``
|
|
148
|
+
would replace ``parent`` with a drive-relative path instead of extending it.
|
|
149
|
+
"""
|
|
150
|
+
joined = parent / part
|
|
151
|
+
if joined.parent != parent or joined.name != part:
|
|
152
|
+
raise ValueError(f"{part!r}: path component does not stay inside {parent}")
|
|
153
|
+
return joined
|
|
154
|
+
|
|
155
|
+
|
|
115
156
|
def ensure_safe_dir(root: Path, parts: tuple[str, ...]) -> Path:
|
|
116
157
|
"""Create ``root/parts`` one component at a time without following symlinks.
|
|
117
158
|
|
|
@@ -121,7 +162,7 @@ def ensure_safe_dir(root: Path, parts: tuple[str, ...]) -> Path:
|
|
|
121
162
|
"""
|
|
122
163
|
current = root
|
|
123
164
|
for index, part in enumerate(parts):
|
|
124
|
-
current = current
|
|
165
|
+
current = join_component(current, part)
|
|
125
166
|
try:
|
|
126
167
|
metadata = os.lstat(current)
|
|
127
168
|
except FileNotFoundError:
|
|
@@ -139,7 +180,7 @@ def create_new_file(root: Path, rel_path: str) -> tuple[Any, Path]:
|
|
|
139
180
|
"""Create a new file inside ``root``; never follow or replace existing entries."""
|
|
140
181
|
parts = safe_relative_parts(rel_path)
|
|
141
182
|
parent = ensure_safe_dir(root, parts[:-1])
|
|
142
|
-
target = parent
|
|
183
|
+
target = join_component(parent, parts[-1])
|
|
143
184
|
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | O_NOFOLLOW | O_BINARY
|
|
144
185
|
try:
|
|
145
186
|
fd = os.open(target, flags, 0o666)
|
|
@@ -224,9 +265,7 @@ def process_inline_file(
|
|
|
224
265
|
content = file_content_bytes(path, record)
|
|
225
266
|
|
|
226
267
|
if write_root is not None:
|
|
227
|
-
write_new_file(
|
|
228
|
-
write_root, path, content, mode_from_record(record, preserve_special_bits)
|
|
229
|
-
)
|
|
268
|
+
write_new_file(write_root, path, content, mode_from_record(record, preserve_special_bits))
|
|
230
269
|
|
|
231
270
|
return expected_size
|
|
232
271
|
|
|
@@ -294,9 +333,7 @@ def process_chunk_record(
|
|
|
294
333
|
|
|
295
334
|
path = record_path(record)
|
|
296
335
|
if path != active.path:
|
|
297
|
-
raise ValueError(
|
|
298
|
-
f"chunk path {path!r} does not match open file {active.path!r}"
|
|
299
|
-
)
|
|
336
|
+
raise ValueError(f"chunk path {path!r} does not match open file {active.path!r}")
|
|
300
337
|
index = record.get("index")
|
|
301
338
|
if index != active.seen_chunks:
|
|
302
339
|
raise ValueError(f"{path}: chunk index mismatch, expected {active.seen_chunks}")
|
|
@@ -369,7 +406,7 @@ def process_symlink_record(
|
|
|
369
406
|
write_new_file(write_root, path, (target + "\n").encode("utf-8"), None)
|
|
370
407
|
return
|
|
371
408
|
parts = safe_relative_parts(path)
|
|
372
|
-
output_target = ensure_safe_dir(write_root, parts[:-1])
|
|
409
|
+
output_target = join_component(ensure_safe_dir(write_root, parts[:-1]), parts[-1])
|
|
373
410
|
try:
|
|
374
411
|
os.symlink(target, output_target)
|
|
375
412
|
except FileExistsError as exc:
|
|
@@ -492,9 +529,7 @@ def process_archive(
|
|
|
492
529
|
record_implied_dirs(path, implied_dirs)
|
|
493
530
|
|
|
494
531
|
if record_type == "dir":
|
|
495
|
-
process_dir_record(
|
|
496
|
-
record, write_root, dir_modes, preserve_special_bits
|
|
497
|
-
)
|
|
532
|
+
process_dir_record(record, write_root, dir_modes, preserve_special_bits)
|
|
498
533
|
dirs += 1
|
|
499
534
|
elif record_type == "file":
|
|
500
535
|
encoding = record.get("encoding")
|
|
@@ -508,9 +543,7 @@ def process_archive(
|
|
|
508
543
|
)
|
|
509
544
|
bytes_count += int(record["size"])
|
|
510
545
|
else:
|
|
511
|
-
raise ValueError(
|
|
512
|
-
f"{path}: unsupported file encoding {encoding!r}"
|
|
513
|
-
)
|
|
546
|
+
raise ValueError(f"{path}: unsupported file encoding {encoding!r}")
|
|
514
547
|
files += 1
|
|
515
548
|
else:
|
|
516
549
|
process_symlink_record(record, write_root, no_symlinks)
|
|
@@ -545,9 +578,7 @@ def process_archive(
|
|
|
545
578
|
active_file.handle.close()
|
|
546
579
|
|
|
547
580
|
if write_root is not None:
|
|
548
|
-
for dir_path, mode in sorted(
|
|
549
|
-
dir_modes, key=lambda item: len(item[0].parts), reverse=True
|
|
550
|
-
):
|
|
581
|
+
for dir_path, mode in sorted(dir_modes, key=lambda item: len(item[0].parts), reverse=True):
|
|
551
582
|
os.chmod(dir_path, mode)
|
|
552
583
|
|
|
553
584
|
return ArchiveManifest(
|
|
@@ -573,9 +604,7 @@ def ensure_output_replaceable(output_dir: Path, overwrite: bool) -> None:
|
|
|
573
604
|
if output_dir.is_dir() and not output_dir.is_symlink():
|
|
574
605
|
is_non_empty = any(output_dir.iterdir())
|
|
575
606
|
if is_non_empty and not overwrite:
|
|
576
|
-
raise FileExistsError(
|
|
577
|
-
f"output directory is not empty; use --overwrite: {output_dir}"
|
|
578
|
-
)
|
|
607
|
+
raise FileExistsError(f"output directory is not empty; use --overwrite: {output_dir}")
|
|
579
608
|
return
|
|
580
609
|
if not overwrite:
|
|
581
610
|
raise FileExistsError(f"output path exists; use --overwrite: {output_dir}")
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: flat-packager
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.2
|
|
4
4
|
Summary: Pack a repository into one flat text archive and restore it later.
|
|
5
5
|
Author: Thomas
|
|
6
6
|
License-Expression: MIT
|
|
@@ -355,6 +355,12 @@ As a second layer, restores create directories one component at a time without
|
|
|
355
355
|
following symlinks and create files exclusively (`O_EXCL`/`O_NOFOLLOW`). Writes
|
|
356
356
|
therefore cannot be routed outside the output directory, including through
|
|
357
357
|
names that collide on case-insensitive filesystems such as default macOS.
|
|
358
|
+
Every path component is joined only if it stays inside its parent directory.
|
|
359
|
+
|
|
360
|
+
On Windows, restores also reject names Windows cannot store safely: names
|
|
361
|
+
containing `:` (drive-relative paths such as `D:x`, or alternate data
|
|
362
|
+
streams), other characters Windows forbids, reserved device names such as
|
|
363
|
+
`NUL` or `aux.py`, and names ending in a dot or space.
|
|
358
364
|
|
|
359
365
|
[docs/FORMAT.md](docs/FORMAT.md#7-validation-performed-on-restore) lists
|
|
360
366
|
every validation rule.
|
|
@@ -366,9 +366,13 @@ class StreamingPackTests(PackTestCase):
|
|
|
366
366
|
raise AssertionError(f"source opened via Path.open: {path}")
|
|
367
367
|
return real_path_open(path, *args, **kwargs)
|
|
368
368
|
|
|
369
|
-
with
|
|
370
|
-
|
|
371
|
-
|
|
369
|
+
with (
|
|
370
|
+
patch("flat_packager.pack.os.open", side_effect=counting_open),
|
|
371
|
+
patch.object(
|
|
372
|
+
Path, "read_bytes", side_effect=AssertionError("read_bytes must not be used")
|
|
373
|
+
),
|
|
374
|
+
patch.object(Path, "open", path_open),
|
|
375
|
+
):
|
|
372
376
|
pack(self.source, self.archive, chunk_size=1024, text_encoding="auto")
|
|
373
377
|
|
|
374
378
|
for name in ("big.bin", "small.py", "data.txt"):
|
|
@@ -472,8 +476,14 @@ class GitignoreTests(PackTestCase):
|
|
|
472
476
|
paths = archive_paths(self.archive)
|
|
473
477
|
for kept in (".gitignore", "src/.gitignore", "src/app.py", "keep.log", "empty"):
|
|
474
478
|
self.assertIn(kept, paths)
|
|
475
|
-
for dropped in (
|
|
476
|
-
|
|
479
|
+
for dropped in (
|
|
480
|
+
".env",
|
|
481
|
+
"debug.log",
|
|
482
|
+
"node_modules",
|
|
483
|
+
"node_modules/dep/index.js",
|
|
484
|
+
"src/generated",
|
|
485
|
+
"src/generated/g.py",
|
|
486
|
+
):
|
|
477
487
|
self.assertNotIn(dropped, paths)
|
|
478
488
|
self.restore()
|
|
479
489
|
|
|
@@ -506,11 +516,19 @@ class GitignoreTests(PackTestCase):
|
|
|
506
516
|
|
|
507
517
|
pack(self.source, self.archive, respect_gitignore=True)
|
|
508
518
|
paths = archive_paths(self.archive)
|
|
509
|
-
for kept in (
|
|
510
|
-
|
|
519
|
+
for kept in (
|
|
520
|
+
"main.py",
|
|
521
|
+
"vendor/sub/lib.py",
|
|
522
|
+
"vendor/sub/new.py",
|
|
523
|
+
"vendor/sub/inner/inner.py",
|
|
524
|
+
):
|
|
511
525
|
self.assertIn(kept, paths)
|
|
512
|
-
for dropped in (
|
|
513
|
-
|
|
526
|
+
for dropped in (
|
|
527
|
+
"vendor/sub/private.txt",
|
|
528
|
+
"vendor/sub/cache",
|
|
529
|
+
"vendor/sub/cache/blob",
|
|
530
|
+
"vendor/sub/inner/inner-secret.txt",
|
|
531
|
+
):
|
|
514
532
|
self.assertNotIn(dropped, paths)
|
|
515
533
|
|
|
516
534
|
def test_embedded_repo_without_gitmodules_keeps_its_ignore_rules(self) -> None:
|
|
@@ -546,7 +564,9 @@ class GitignoreTests(PackTestCase):
|
|
|
546
564
|
git(sub_origin, "commit", "-q", "-m", "sub")
|
|
547
565
|
head = subprocess.run(
|
|
548
566
|
["git", "-C", str(sub_origin), "rev-parse", "HEAD"],
|
|
549
|
-
check=True,
|
|
567
|
+
check=True,
|
|
568
|
+
capture_output=True,
|
|
569
|
+
text=True,
|
|
550
570
|
).stdout.strip()
|
|
551
571
|
git(self.source, "update-index", "--add", "--cacheinfo", f"160000,{head},sub")
|
|
552
572
|
(self.source / "sub").mkdir()
|
|
@@ -633,8 +653,14 @@ class GitignoreTests(PackTestCase):
|
|
|
633
653
|
|
|
634
654
|
class SecretWarningTests(PackTestCase):
|
|
635
655
|
def test_likely_secret_files_warn(self) -> None:
|
|
636
|
-
for name in (
|
|
637
|
-
|
|
656
|
+
for name in (
|
|
657
|
+
".env",
|
|
658
|
+
".env.production",
|
|
659
|
+
"server.pem",
|
|
660
|
+
"id_rsa",
|
|
661
|
+
".npmrc",
|
|
662
|
+
"credentials-prod.json",
|
|
663
|
+
):
|
|
638
664
|
(self.source / name).write_text("x\n")
|
|
639
665
|
for name in (".env.example", "id_rsa.pub", "app.py", "keys.py"):
|
|
640
666
|
(self.source / name).write_text("x\n")
|
|
@@ -643,8 +669,14 @@ class SecretWarningTests(PackTestCase):
|
|
|
643
669
|
with redirect_stderr(stderr):
|
|
644
670
|
pack(self.source, self.archive)
|
|
645
671
|
output = stderr.getvalue()
|
|
646
|
-
for name in (
|
|
647
|
-
|
|
672
|
+
for name in (
|
|
673
|
+
".env",
|
|
674
|
+
".env.production",
|
|
675
|
+
"server.pem",
|
|
676
|
+
"id_rsa",
|
|
677
|
+
".npmrc",
|
|
678
|
+
"credentials-prod.json",
|
|
679
|
+
):
|
|
648
680
|
self.assertIn(f"likely secret file: {name}\n", output)
|
|
649
681
|
for name in (".env.example", "id_rsa.pub", "app.py", "keys.py"):
|
|
650
682
|
self.assertNotIn(f"likely secret file: {name}\n", output)
|
|
@@ -676,9 +708,7 @@ class TextEncodingDefaultTests(PackTestCase):
|
|
|
676
708
|
redirect_stdout(io.StringIO()),
|
|
677
709
|
):
|
|
678
710
|
self.assertEqual(pack_main(), 0)
|
|
679
|
-
return {
|
|
680
|
-
r["path"]: r for _l, r in read_json_lines(self.archive) if r.get("type") == "file"
|
|
681
|
-
}
|
|
711
|
+
return {r["path"]: r for _l, r in read_json_lines(self.archive) if r.get("type") == "file"}
|
|
682
712
|
|
|
683
713
|
def write_sources(self) -> None:
|
|
684
714
|
(self.source / "app.py").write_text("print('hi')\n", encoding="utf-8")
|
|
@@ -745,7 +775,8 @@ class IncludeAndSubdirTests(PackTestCase):
|
|
|
745
775
|
{p for p, t in paths.items() if t == "dir"}, {"src", "src/pkg", "src/pkg/deep"}
|
|
746
776
|
)
|
|
747
777
|
records = {r["path"]: r for _l, r in read_json_lines(self.archive) if "path" in r}
|
|
748
|
-
|
|
778
|
+
if os.name != "nt": # Windows has no POSIX directory permissions
|
|
779
|
+
self.assertEqual(records["src/pkg"]["mode"], 0o750)
|
|
749
780
|
restored = self.restore()
|
|
750
781
|
self.assertEqual((restored / "src" / "pkg" / "deep" / "c.py").read_text(), "c\n")
|
|
751
782
|
|
|
@@ -791,8 +822,14 @@ class IncludeAndSubdirTests(PackTestCase):
|
|
|
791
822
|
paths = archive_paths(self.archive)
|
|
792
823
|
self.assertEqual(
|
|
793
824
|
set(paths),
|
|
794
|
-
{
|
|
795
|
-
|
|
825
|
+
{
|
|
826
|
+
"src",
|
|
827
|
+
"src/pkg",
|
|
828
|
+
"src/pkg/b.py",
|
|
829
|
+
"src/pkg/data.json",
|
|
830
|
+
"src/pkg/deep",
|
|
831
|
+
"src/pkg/deep/c.py",
|
|
832
|
+
},
|
|
796
833
|
)
|
|
797
834
|
header = next(read_json_lines(self.archive))[1]
|
|
798
835
|
self.assertEqual(header["subdir"], "src/pkg")
|
|
@@ -812,9 +849,7 @@ class IncludeAndSubdirTests(PackTestCase):
|
|
|
812
849
|
include_patterns=["*.json"],
|
|
813
850
|
)
|
|
814
851
|
paths = archive_paths(self.archive)
|
|
815
|
-
self.assertEqual(
|
|
816
|
-
{p for p, t in paths.items() if t == "file"}, {"src/pkg/data.json"}
|
|
817
|
-
)
|
|
852
|
+
self.assertEqual({p for p, t in paths.items() if t == "file"}, {"src/pkg/data.json"})
|
|
818
853
|
|
|
819
854
|
def test_bad_subdirs_are_rejected(self) -> None:
|
|
820
855
|
self.make_tree()
|
|
@@ -834,16 +869,29 @@ class IncludeAndSubdirTests(PackTestCase):
|
|
|
834
869
|
from flat_packager.pack import main as pack_main
|
|
835
870
|
|
|
836
871
|
self.make_tree()
|
|
837
|
-
argv = [
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
872
|
+
argv = [
|
|
873
|
+
"flat-pack",
|
|
874
|
+
str(self.source),
|
|
875
|
+
str(self.archive),
|
|
876
|
+
"--subdir",
|
|
877
|
+
"src/",
|
|
878
|
+
"--include",
|
|
879
|
+
"*.py",
|
|
880
|
+
"--include",
|
|
881
|
+
"*.json",
|
|
882
|
+
]
|
|
883
|
+
with (
|
|
884
|
+
patch.object(sys, "argv", argv),
|
|
885
|
+
redirect_stderr(io.StringIO()),
|
|
886
|
+
redirect_stdout(io.StringIO()),
|
|
887
|
+
):
|
|
841
888
|
self.assertEqual(pack_main(), 0)
|
|
842
889
|
files = {p for p, t in archive_paths(self.archive).items() if t == "file"}
|
|
843
|
-
self.assertEqual(
|
|
844
|
-
|
|
845
|
-
|
|
890
|
+
self.assertEqual(
|
|
891
|
+
files, {"src/a.py", "src/pkg/b.py", "src/pkg/deep/c.py", "src/pkg/data.json"}
|
|
892
|
+
)
|
|
846
893
|
|
|
894
|
+
@unittest.skipIf(os.name == "nt", "Windows strips trailing spaces from names")
|
|
847
895
|
def test_subdir_keeps_significant_whitespace(self) -> None:
|
|
848
896
|
(self.source / "data").mkdir()
|
|
849
897
|
(self.source / "data" / "plain.txt").write_text("plain\n")
|
|
@@ -953,8 +1001,10 @@ class FailedOutputTests(PackTestCase):
|
|
|
953
1001
|
(self.source / "big.bin").write_bytes(os.urandom(5 * 1024 * 1024))
|
|
954
1002
|
pack(self.source, Path(os.devnull))
|
|
955
1003
|
|
|
956
|
-
@unittest.skipIf(
|
|
957
|
-
|
|
1004
|
+
@unittest.skipIf(
|
|
1005
|
+
os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0),
|
|
1006
|
+
"needs an unprivileged POSIX user",
|
|
1007
|
+
)
|
|
958
1008
|
def test_chunked_pack_into_read_only_directory_with_writable_output(self) -> None:
|
|
959
1009
|
(self.source / "big.bin").write_bytes(os.urandom(5 * 1024 * 1024))
|
|
960
1010
|
ro = self.work_dir / "ro"
|
|
@@ -980,6 +1030,7 @@ class FailedOutputTests(PackTestCase):
|
|
|
980
1030
|
self.assertIn("keep.txt", paths)
|
|
981
1031
|
self.assertEqual([p for p in paths if p.endswith(".log")], [])
|
|
982
1032
|
|
|
1033
|
+
|
|
983
1034
|
class OutputHandlingTests(PackTestCase):
|
|
984
1035
|
def test_chunk_spool_lives_next_to_the_output(self) -> None:
|
|
985
1036
|
import tempfile as tempfile_module
|
|
@@ -35,11 +35,18 @@ OUTSIDE = "__OUTSIDE__" # replaced with the absolute path of the outside dir
|
|
|
35
35
|
|
|
36
36
|
if st is not None:
|
|
37
37
|
settings.register_profile(
|
|
38
|
-
"default",
|
|
38
|
+
"default",
|
|
39
|
+
max_examples=500,
|
|
40
|
+
deadline=None,
|
|
41
|
+
database=None,
|
|
39
42
|
suppress_health_check=[HealthCheck.too_slow],
|
|
40
43
|
)
|
|
41
44
|
settings.register_profile(
|
|
42
|
-
"ci",
|
|
45
|
+
"ci",
|
|
46
|
+
max_examples=1000,
|
|
47
|
+
deadline=None,
|
|
48
|
+
database=None,
|
|
49
|
+
derandomize=True,
|
|
43
50
|
suppress_health_check=[HealthCheck.too_slow],
|
|
44
51
|
)
|
|
45
52
|
settings.load_profile("ci" if os.environ.get("CI") else "default")
|
|
@@ -53,8 +60,19 @@ if st is not None:
|
|
|
53
60
|
)
|
|
54
61
|
paths = st.one_of(valid_paths, valid_paths, valid_paths, valid_paths, invalid_paths)
|
|
55
62
|
targets = st.sampled_from(
|
|
56
|
-
[
|
|
57
|
-
|
|
63
|
+
[
|
|
64
|
+
OUTSIDE,
|
|
65
|
+
OUTSIDE,
|
|
66
|
+
OUTSIDE + "/a",
|
|
67
|
+
"../outside",
|
|
68
|
+
"../outside",
|
|
69
|
+
"../../outside",
|
|
70
|
+
"..",
|
|
71
|
+
".",
|
|
72
|
+
"a",
|
|
73
|
+
"/",
|
|
74
|
+
"link",
|
|
75
|
+
]
|
|
58
76
|
)
|
|
59
77
|
contents = st.binary(max_size=8)
|
|
60
78
|
|
|
@@ -146,9 +164,15 @@ class RestoreFuzzTests(unittest.TestCase):
|
|
|
146
164
|
@example(
|
|
147
165
|
[
|
|
148
166
|
{"type": "symlink", "path": "Link", "mode": 0o777, "target": OUTSIDE},
|
|
149
|
-
{
|
|
150
|
-
|
|
151
|
-
|
|
167
|
+
{
|
|
168
|
+
"type": "file",
|
|
169
|
+
"path": "link/owned",
|
|
170
|
+
"mode": 0o644,
|
|
171
|
+
"size": 0,
|
|
172
|
+
"sha256": hashlib.sha256(b"").hexdigest(),
|
|
173
|
+
"encoding": "base64",
|
|
174
|
+
"content": "",
|
|
175
|
+
},
|
|
152
176
|
],
|
|
153
177
|
False,
|
|
154
178
|
)
|
|
@@ -398,6 +398,7 @@ class RoundTripTests(unittest.TestCase):
|
|
|
398
398
|
self.assertEqual((output / "link" / "owned.txt").read_bytes(), b"owned\n")
|
|
399
399
|
self.assertEqual(list(outside.iterdir()), [])
|
|
400
400
|
|
|
401
|
+
@unittest.skipIf(os.name == "nt", "Windows has no POSIX permission bits")
|
|
401
402
|
def test_special_mode_bits_are_stripped_by_default(self) -> None:
|
|
402
403
|
archive = self.work_dir / "archive.flat.txt"
|
|
403
404
|
output = self.work_dir / "output"
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
import shutil
|
|
5
|
+
import sys
|
|
6
|
+
import tempfile
|
|
7
|
+
import unittest
|
|
8
|
+
from contextlib import redirect_stderr
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
|
12
|
+
|
|
13
|
+
from flat_packager.archive import read_json_lines
|
|
14
|
+
from flat_packager.pack import build_archive
|
|
15
|
+
from flat_packager.text_encoding import path_looks_like_text, should_store_as_utf8
|
|
16
|
+
from flat_packager.unpack import restore_archive
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class PathLooksLikeTextTests(unittest.TestCase):
|
|
20
|
+
def test_text_dotfiles_are_detected(self) -> None:
|
|
21
|
+
# Regression for #26: PurePosixPath(".gitignore").suffix is "", so
|
|
22
|
+
# dotfiles listed as extensions never matched.
|
|
23
|
+
for path in (
|
|
24
|
+
".gitignore",
|
|
25
|
+
".gitattributes",
|
|
26
|
+
".gitmodules",
|
|
27
|
+
".env",
|
|
28
|
+
".editorconfig",
|
|
29
|
+
".dockerignore",
|
|
30
|
+
"src/.gitignore",
|
|
31
|
+
"deep/nested/.prettierrc",
|
|
32
|
+
):
|
|
33
|
+
with self.subTest(path=path):
|
|
34
|
+
self.assertTrue(path_looks_like_text(path))
|
|
35
|
+
|
|
36
|
+
def test_env_variants_are_detected(self) -> None:
|
|
37
|
+
for path in (".env.example", ".env.local", "app/.env.production", ".ENV.Local"):
|
|
38
|
+
with self.subTest(path=path):
|
|
39
|
+
self.assertTrue(path_looks_like_text(path))
|
|
40
|
+
|
|
41
|
+
def test_existing_rules_still_apply(self) -> None:
|
|
42
|
+
for path in ("a.py", "prod.env", "README.md", "Makefile", "docs/README"):
|
|
43
|
+
with self.subTest(path=path):
|
|
44
|
+
self.assertTrue(path_looks_like_text(path))
|
|
45
|
+
|
|
46
|
+
def test_unknown_files_are_not_text(self) -> None:
|
|
47
|
+
for path in ("image.png", "data.bin", ".DS_Store", ".hidden", "envfile", "a.envy"):
|
|
48
|
+
with self.subTest(path=path):
|
|
49
|
+
self.assertFalse(path_looks_like_text(path))
|
|
50
|
+
|
|
51
|
+
def test_dotfile_with_invalid_utf8_still_uses_base64(self) -> None:
|
|
52
|
+
self.assertFalse(should_store_as_utf8(".gitignore", b"\xff\xfe", "auto"))
|
|
53
|
+
self.assertTrue(should_store_as_utf8(".gitignore", b"*.pyc\n", "auto"))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class DotfileArchiveTests(unittest.TestCase):
|
|
57
|
+
def setUp(self) -> None:
|
|
58
|
+
self.work_dir = Path(tempfile.mkdtemp(prefix="flat-packager-text-"))
|
|
59
|
+
|
|
60
|
+
def tearDown(self) -> None:
|
|
61
|
+
shutil.rmtree(self.work_dir, ignore_errors=True)
|
|
62
|
+
|
|
63
|
+
def test_dotfiles_are_stored_as_readable_utf8_and_round_trip(self) -> None:
|
|
64
|
+
repo = self.work_dir / "repo"
|
|
65
|
+
repo.mkdir()
|
|
66
|
+
files = {
|
|
67
|
+
".gitignore": b"*.pyc\nnode_modules/\n",
|
|
68
|
+
".gitattributes": b"* text=auto\n",
|
|
69
|
+
".env.example": b"API_URL=https://example.invalid\n",
|
|
70
|
+
".editorconfig": b"root = true\n",
|
|
71
|
+
}
|
|
72
|
+
for name, content in files.items():
|
|
73
|
+
(repo / name).write_bytes(content)
|
|
74
|
+
|
|
75
|
+
archive = self.work_dir / "repo.flat.txt"
|
|
76
|
+
with redirect_stderr(io.StringIO()):
|
|
77
|
+
build_archive(
|
|
78
|
+
root=repo,
|
|
79
|
+
output_path=archive,
|
|
80
|
+
source_label="repo",
|
|
81
|
+
tracked_only=False,
|
|
82
|
+
include_git=False,
|
|
83
|
+
exclude_patterns=[],
|
|
84
|
+
max_file_bytes=None,
|
|
85
|
+
text_encoding="auto",
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
encodings = {
|
|
89
|
+
record["path"]: record.get("encoding")
|
|
90
|
+
for _line, record in read_json_lines(archive)
|
|
91
|
+
if record.get("type") == "file"
|
|
92
|
+
}
|
|
93
|
+
self.assertEqual(encodings, {name: "utf8" for name in files})
|
|
94
|
+
|
|
95
|
+
output = self.work_dir / "out"
|
|
96
|
+
restore_archive(
|
|
97
|
+
archive_path=archive,
|
|
98
|
+
output_dir=output,
|
|
99
|
+
overwrite=False,
|
|
100
|
+
verify_only=False,
|
|
101
|
+
no_symlinks=False,
|
|
102
|
+
)
|
|
103
|
+
for name, content in files.items():
|
|
104
|
+
self.assertEqual((output / name).read_bytes(), content)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
if __name__ == "__main__":
|
|
108
|
+
unittest.main()
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Windows-specific restore safety tests.
|
|
2
|
+
|
|
3
|
+
Windows path rules differ from POSIX: a component such as ``D:x`` is a
|
|
4
|
+
drive-relative path that replaces everything joined before it, ``name:stream``
|
|
5
|
+
addresses an NTFS alternate data stream, device names such as ``CON`` and
|
|
6
|
+
``NUL`` are reserved, and trailing dots and spaces are stripped. These tests
|
|
7
|
+
check that a restore never writes outside the output directory and rejects
|
|
8
|
+
such names. They only run on Windows.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import hashlib
|
|
15
|
+
import os
|
|
16
|
+
import shutil
|
|
17
|
+
import sys
|
|
18
|
+
import tempfile
|
|
19
|
+
import unittest
|
|
20
|
+
from pathlib import Path, PureWindowsPath
|
|
21
|
+
|
|
22
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
|
23
|
+
|
|
24
|
+
from flat_packager.archive import ARCHIVE_KIND, emit_json_line
|
|
25
|
+
from flat_packager.unpack import join_component, restore_archive, windows_unsafe_reason
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def write_single_file_archive(archive: Path, rel_path: str, content: bytes) -> None:
|
|
29
|
+
with archive.open("w", encoding="utf-8", newline="\n") as handle:
|
|
30
|
+
emit_json_line(handle, {"type": ARCHIVE_KIND, "version": 1})
|
|
31
|
+
emit_json_line(
|
|
32
|
+
handle,
|
|
33
|
+
{
|
|
34
|
+
"type": "file",
|
|
35
|
+
"path": rel_path,
|
|
36
|
+
"mode": 0o644,
|
|
37
|
+
"size": len(content),
|
|
38
|
+
"sha256": hashlib.sha256(content).hexdigest(),
|
|
39
|
+
"encoding": "base64",
|
|
40
|
+
"content": base64.b64encode(content).decode("ascii"),
|
|
41
|
+
},
|
|
42
|
+
)
|
|
43
|
+
emit_json_line(handle, {"type": "end", "entries": 1, "files": 1})
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@unittest.skipUnless(os.name == "nt", "Windows path semantics")
|
|
47
|
+
class WindowsRestorePathTests(unittest.TestCase):
|
|
48
|
+
def setUp(self) -> None:
|
|
49
|
+
self.work_dir = Path(tempfile.mkdtemp(prefix="flat-packager-win-"))
|
|
50
|
+
self.original_cwd = Path.cwd()
|
|
51
|
+
|
|
52
|
+
def tearDown(self) -> None:
|
|
53
|
+
os.chdir(self.original_cwd)
|
|
54
|
+
shutil.rmtree(self.work_dir, ignore_errors=True)
|
|
55
|
+
|
|
56
|
+
def restore(self, archive: Path, output: Path) -> Exception | None:
|
|
57
|
+
try:
|
|
58
|
+
restore_archive(
|
|
59
|
+
archive_path=archive,
|
|
60
|
+
output_dir=output,
|
|
61
|
+
overwrite=False,
|
|
62
|
+
verify_only=False,
|
|
63
|
+
no_symlinks=False,
|
|
64
|
+
)
|
|
65
|
+
except (ValueError, OSError) as exc:
|
|
66
|
+
return exc
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
def assert_drive_relative_path_does_not_escape(self, template: str) -> None:
|
|
70
|
+
# A drive-relative path ("D:x") only escapes when it names a different
|
|
71
|
+
# drive than the output directory, so put the "outside" directory and
|
|
72
|
+
# the current directory on the checkout's drive and restore to TEMP.
|
|
73
|
+
outside = Path(tempfile.mkdtemp(prefix="flat-packager-outside-", dir=self.original_cwd))
|
|
74
|
+
self.addCleanup(shutil.rmtree, outside, True)
|
|
75
|
+
if outside.drive.lower() == self.work_dir.drive.lower():
|
|
76
|
+
self.skipTest(f"needs two drives; TEMP and checkout are both on {outside.drive}")
|
|
77
|
+
os.chdir(outside)
|
|
78
|
+
|
|
79
|
+
rel_path = template.format(drive=outside.drive)
|
|
80
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
81
|
+
output = self.work_dir / "output"
|
|
82
|
+
write_single_file_archive(archive, rel_path, b"escaped\n")
|
|
83
|
+
|
|
84
|
+
error = self.restore(archive, output)
|
|
85
|
+
|
|
86
|
+
escaped = sorted(p.name for p in outside.iterdir())
|
|
87
|
+
self.assertEqual(
|
|
88
|
+
escaped,
|
|
89
|
+
[],
|
|
90
|
+
f"archive path {rel_path!r} wrote {escaped} into {outside} "
|
|
91
|
+
f"(outside the output directory {output}); restore error: {error!r}",
|
|
92
|
+
)
|
|
93
|
+
self.assertIsInstance(error, ValueError, f"{rel_path!r} was not rejected")
|
|
94
|
+
self.assertIn("unsafe archive path on Windows", str(error))
|
|
95
|
+
self.assertFalse(output.exists())
|
|
96
|
+
|
|
97
|
+
def test_drive_relative_path_does_not_escape(self) -> None:
|
|
98
|
+
self.assert_drive_relative_path_does_not_escape("{drive}escaped.txt")
|
|
99
|
+
|
|
100
|
+
def test_nested_drive_relative_path_does_not_escape(self) -> None:
|
|
101
|
+
self.assert_drive_relative_path_does_not_escape("sub/{drive}escaped.txt")
|
|
102
|
+
|
|
103
|
+
def assert_rejected(self, rel_path: str) -> None:
|
|
104
|
+
# A fresh directory per call: subtests must not share an output dir.
|
|
105
|
+
case_dir = Path(tempfile.mkdtemp(prefix="case-", dir=self.work_dir))
|
|
106
|
+
archive = case_dir / "archive.flat.txt"
|
|
107
|
+
output = case_dir / "output"
|
|
108
|
+
write_single_file_archive(archive, rel_path, b"data\n")
|
|
109
|
+
error = self.restore(archive, output)
|
|
110
|
+
self.assertIsInstance(
|
|
111
|
+
error, ValueError, f"{rel_path!r} was not rejected on Windows (error: {error!r})"
|
|
112
|
+
)
|
|
113
|
+
self.assertFalse(output.exists())
|
|
114
|
+
|
|
115
|
+
def test_alternate_data_stream_is_rejected(self) -> None:
|
|
116
|
+
self.assert_rejected("file.txt:hidden")
|
|
117
|
+
|
|
118
|
+
def test_reserved_device_names_are_rejected(self) -> None:
|
|
119
|
+
for rel_path in ("NUL", "nul.txt", "aux.py", "COM1/x.txt", "sub/LPT1", "CONIN$"):
|
|
120
|
+
with self.subTest(path=rel_path):
|
|
121
|
+
self.assert_rejected(rel_path)
|
|
122
|
+
|
|
123
|
+
def test_trailing_dot_or_space_is_rejected(self) -> None:
|
|
124
|
+
for rel_path in ("name.", "name ", "dir./x.txt", "dir /x.txt"):
|
|
125
|
+
with self.subTest(path=rel_path):
|
|
126
|
+
self.assert_rejected(rel_path)
|
|
127
|
+
|
|
128
|
+
def test_ordinary_names_still_restore(self) -> None:
|
|
129
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
130
|
+
output = self.work_dir / "output"
|
|
131
|
+
write_single_file_archive(archive, "src/console.py", b"print(1)\n")
|
|
132
|
+
self.assertIsNone(self.restore(archive, output))
|
|
133
|
+
self.assertEqual((output / "src" / "console.py").read_bytes(), b"print(1)\n")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class WindowsNameRulesTests(unittest.TestCase):
|
|
137
|
+
"""Platform-independent checks of the Windows rules, so every CI job covers them."""
|
|
138
|
+
|
|
139
|
+
def test_unsafe_names(self) -> None:
|
|
140
|
+
for part, reason in (
|
|
141
|
+
("D:escaped.txt", "forbidden character"),
|
|
142
|
+
("file.txt:hidden", "forbidden character"),
|
|
143
|
+
("a<b", "forbidden character"),
|
|
144
|
+
("tab\tname", "forbidden character"),
|
|
145
|
+
("NUL", "reserved device name"),
|
|
146
|
+
("nul.txt", "reserved device name"),
|
|
147
|
+
("aux.tar.gz", "reserved device name"),
|
|
148
|
+
("COM1", "reserved device name"),
|
|
149
|
+
("lpt9.log", "reserved device name"),
|
|
150
|
+
("CONIN$", "reserved device name"),
|
|
151
|
+
("COM\u00b9", "reserved device name"),
|
|
152
|
+
("name.", "trailing dot or space"),
|
|
153
|
+
("name ", "trailing dot or space"),
|
|
154
|
+
):
|
|
155
|
+
with self.subTest(part=part):
|
|
156
|
+
found = windows_unsafe_reason(part)
|
|
157
|
+
self.assertIsNotNone(found)
|
|
158
|
+
assert found is not None
|
|
159
|
+
self.assertIn(reason, found)
|
|
160
|
+
|
|
161
|
+
def test_safe_names(self) -> None:
|
|
162
|
+
for part in ("console.py", "nullable", "COM10", "auxiliary", ".gitignore", "a.b.c", "..x"):
|
|
163
|
+
with self.subTest(part=part):
|
|
164
|
+
self.assertIsNone(windows_unsafe_reason(part))
|
|
165
|
+
|
|
166
|
+
def test_join_component_refuses_to_leave_parent(self) -> None:
|
|
167
|
+
root = PureWindowsPath(r"C:\out")
|
|
168
|
+
for part in ("D:x", "C:x", r"\\server\share", "/etc"):
|
|
169
|
+
with self.subTest(part=part), self.assertRaises(ValueError):
|
|
170
|
+
join_component(root, part) # type: ignore[arg-type]
|
|
171
|
+
self.assertEqual(join_component(root, "sub"), PureWindowsPath(r"C:\out\sub")) # type: ignore[arg-type]
|
|
172
|
+
|
|
173
|
+
@unittest.skipIf(os.name == "nt", "colons are legal in POSIX names only")
|
|
174
|
+
def test_colon_names_still_restore_on_posix(self) -> None:
|
|
175
|
+
work_dir = Path(tempfile.mkdtemp(prefix="flat-packager-colon-"))
|
|
176
|
+
self.addCleanup(shutil.rmtree, work_dir, True)
|
|
177
|
+
archive = work_dir / "archive.flat.txt"
|
|
178
|
+
output = work_dir / "output"
|
|
179
|
+
write_single_file_archive(archive, "logs/2026-12-01T10:00.log", b"ok\n")
|
|
180
|
+
restore_archive(
|
|
181
|
+
archive_path=archive,
|
|
182
|
+
output_dir=output,
|
|
183
|
+
overwrite=False,
|
|
184
|
+
verify_only=False,
|
|
185
|
+
no_symlinks=False,
|
|
186
|
+
)
|
|
187
|
+
self.assertEqual((output / "logs" / "2026-12-01T10:00.log").read_bytes(), b"ok\n")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
if __name__ == "__main__":
|
|
191
|
+
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -207,7 +207,6 @@ class MarkdownCliTests(MarkdownTestCase):
|
|
|
207
207
|
self.assertNotIn("Traceback", result.stderr, command)
|
|
208
208
|
|
|
209
209
|
|
|
210
|
-
|
|
211
210
|
class MarkdownSelectionTests(MarkdownTestCase):
|
|
212
211
|
@unittest.skipIf(sys.platform == "darwin" or os.name == "nt", "filesystem requires UTF-8 names")
|
|
213
212
|
def test_unselected_non_utf8_default_excluded_dir_does_not_break_output(self) -> None:
|
|
@@ -249,5 +248,6 @@ class MarkdownSelectionTests(MarkdownTestCase):
|
|
|
249
248
|
text = render(self.source, self.output, subdir="build/x", default_excludes=False)
|
|
250
249
|
self.assertIn("build/x/a.py", text)
|
|
251
250
|
|
|
251
|
+
|
|
252
252
|
if __name__ == "__main__":
|
|
253
253
|
unittest.main()
|
|
File without changes
|