flat-packager 0.4.0__tar.gz → 0.4.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.4.0/src/flat_packager.egg-info → flat_packager-0.4.2}/PKG-INFO +36 -4
- {flat_packager-0.4.0 → flat_packager-0.4.2}/README.md +35 -3
- {flat_packager-0.4.0 → flat_packager-0.4.2}/pyproject.toml +1 -1
- {flat_packager-0.4.0 → flat_packager-0.4.2}/src/flat_packager/__init__.py +1 -1
- flat_packager-0.4.2/src/flat_packager/content.py +55 -0
- {flat_packager-0.4.0 → flat_packager-0.4.2}/src/flat_packager/pack.py +94 -21
- flat_packager-0.4.2/src/flat_packager/text_encoding.py +99 -0
- {flat_packager-0.4.0 → flat_packager-0.4.2}/src/flat_packager/unpack.py +164 -62
- {flat_packager-0.4.0 → flat_packager-0.4.2/src/flat_packager.egg-info}/PKG-INFO +36 -4
- {flat_packager-0.4.0 → flat_packager-0.4.2}/src/flat_packager.egg-info/SOURCES.txt +2 -0
- {flat_packager-0.4.0 → flat_packager-0.4.2}/tests/test_roundtrip.py +199 -3
- {flat_packager-0.4.0 → flat_packager-0.4.2}/LICENSE +0 -0
- {flat_packager-0.4.0 → flat_packager-0.4.2}/setup.cfg +0 -0
- {flat_packager-0.4.0 → flat_packager-0.4.2}/src/flat_packager/archive.py +0 -0
- {flat_packager-0.4.0 → flat_packager-0.4.2}/src/flat_packager/inspect.py +0 -0
- {flat_packager-0.4.0 → flat_packager-0.4.2}/src/flat_packager/verify.py +0 -0
- {flat_packager-0.4.0 → flat_packager-0.4.2}/src/flat_packager.egg-info/dependency_links.txt +0 -0
- {flat_packager-0.4.0 → flat_packager-0.4.2}/src/flat_packager.egg-info/entry_points.txt +0 -0
- {flat_packager-0.4.0 → flat_packager-0.4.2}/src/flat_packager.egg-info/requires.txt +0 -0
- {flat_packager-0.4.0 → flat_packager-0.4.2}/src/flat_packager.egg-info/top_level.txt +0 -0
- {flat_packager-0.4.0 → flat_packager-0.4.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.4.
|
|
3
|
+
Version: 0.4.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
|
|
@@ -114,8 +114,29 @@ Useful options:
|
|
|
114
114
|
flat-pack /path/to/repo repo.flat.txt --exclude "node_modules/*"
|
|
115
115
|
flat-pack /path/to/repo repo.flat.txt --max-file-bytes 10485760
|
|
116
116
|
flat-pack /path/to/repo repo.flat.txt --include-git
|
|
117
|
+
flat-pack /path/to/repo repo.flat.txt --text-encoding auto
|
|
117
118
|
```
|
|
118
119
|
|
|
120
|
+
## Text Encoding
|
|
121
|
+
|
|
122
|
+
By default every file is stored as base64 (binary-safe). For human-readable
|
|
123
|
+
archives, use `--text-encoding auto` to store known text files such as `.py`,
|
|
124
|
+
`.md`, `.yaml`, and `.json` as plain UTF-8 JSON strings:
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
flat-pack /path/to/repo repo.flat.txt --text-encoding auto --compress none
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
In the archive, text files look like:
|
|
131
|
+
|
|
132
|
+
```json
|
|
133
|
+
{"encoding":"utf8","path":"src/app.py","content":"def main():\n ..."}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Binary files still use base64 chunks. Use `--text-encoding utf8` to store any
|
|
137
|
+
valid UTF-8 file as readable text. The default `--text-encoding base64` keeps
|
|
138
|
+
every file base64-encoded for maximum compatibility.
|
|
139
|
+
|
|
119
140
|
## Format and Compression
|
|
120
141
|
|
|
121
142
|
New archives use format version 2 by default. Version 2 stores each regular
|
|
@@ -198,19 +219,30 @@ The restore step rejects:
|
|
|
198
219
|
- absolute archive paths
|
|
199
220
|
- `..`, `.`, empty, or backslash path segments
|
|
200
221
|
- duplicate archive paths
|
|
201
|
-
- file or directory records nested underneath an archived symlink
|
|
222
|
+
- file or directory records nested underneath an archived symlink or file,
|
|
223
|
+
checked before anything is written for that record
|
|
224
|
+
- a symlink or file that would replace a directory other entries live in
|
|
202
225
|
- chunk records that are missing, out of order, corrupt, or attached to the
|
|
203
226
|
wrong file
|
|
204
227
|
- corrupt base64, size, or SHA-256 data
|
|
205
228
|
|
|
229
|
+
As a second layer, restores create directories one component at a time without
|
|
230
|
+
following symlinks and create files exclusively (`O_EXCL`/`O_NOFOLLOW`). Writes
|
|
231
|
+
therefore cannot be routed outside the output directory, including through
|
|
232
|
+
names that collide on case-insensitive filesystems such as default macOS.
|
|
233
|
+
|
|
234
|
+
Setuid, setgid, and sticky mode bits are stripped on restore. Pass
|
|
235
|
+
`--preserve-special-bits` to keep them for archives you trust.
|
|
236
|
+
|
|
206
237
|
Restored symlinks may still point outside the restored repository, because that
|
|
207
238
|
is valid repository content. Use `--no-symlinks` if you want symlink targets
|
|
208
239
|
written as text files instead.
|
|
209
240
|
|
|
210
241
|
## Limitations
|
|
211
242
|
|
|
212
|
-
-
|
|
213
|
-
|
|
243
|
+
- With the default `--text-encoding base64`, file contents are base64 encoded,
|
|
244
|
+
so archives are larger than raw file bytes. Use `--text-encoding auto` for
|
|
245
|
+
readable source text, or gzip compression when archive size matters.
|
|
214
246
|
- Legacy format version 1 stores each file as one JSON record and is
|
|
215
247
|
memory-heavy for large files. Version 2 is chunked and is the default.
|
|
216
248
|
- Remote GitHub packing depends on local `git` and whatever authentication your
|
|
@@ -83,8 +83,29 @@ Useful options:
|
|
|
83
83
|
flat-pack /path/to/repo repo.flat.txt --exclude "node_modules/*"
|
|
84
84
|
flat-pack /path/to/repo repo.flat.txt --max-file-bytes 10485760
|
|
85
85
|
flat-pack /path/to/repo repo.flat.txt --include-git
|
|
86
|
+
flat-pack /path/to/repo repo.flat.txt --text-encoding auto
|
|
86
87
|
```
|
|
87
88
|
|
|
89
|
+
## Text Encoding
|
|
90
|
+
|
|
91
|
+
By default every file is stored as base64 (binary-safe). For human-readable
|
|
92
|
+
archives, use `--text-encoding auto` to store known text files such as `.py`,
|
|
93
|
+
`.md`, `.yaml`, and `.json` as plain UTF-8 JSON strings:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
flat-pack /path/to/repo repo.flat.txt --text-encoding auto --compress none
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
In the archive, text files look like:
|
|
100
|
+
|
|
101
|
+
```json
|
|
102
|
+
{"encoding":"utf8","path":"src/app.py","content":"def main():\n ..."}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Binary files still use base64 chunks. Use `--text-encoding utf8` to store any
|
|
106
|
+
valid UTF-8 file as readable text. The default `--text-encoding base64` keeps
|
|
107
|
+
every file base64-encoded for maximum compatibility.
|
|
108
|
+
|
|
88
109
|
## Format and Compression
|
|
89
110
|
|
|
90
111
|
New archives use format version 2 by default. Version 2 stores each regular
|
|
@@ -167,19 +188,30 @@ The restore step rejects:
|
|
|
167
188
|
- absolute archive paths
|
|
168
189
|
- `..`, `.`, empty, or backslash path segments
|
|
169
190
|
- duplicate archive paths
|
|
170
|
-
- file or directory records nested underneath an archived symlink
|
|
191
|
+
- file or directory records nested underneath an archived symlink or file,
|
|
192
|
+
checked before anything is written for that record
|
|
193
|
+
- a symlink or file that would replace a directory other entries live in
|
|
171
194
|
- chunk records that are missing, out of order, corrupt, or attached to the
|
|
172
195
|
wrong file
|
|
173
196
|
- corrupt base64, size, or SHA-256 data
|
|
174
197
|
|
|
198
|
+
As a second layer, restores create directories one component at a time without
|
|
199
|
+
following symlinks and create files exclusively (`O_EXCL`/`O_NOFOLLOW`). Writes
|
|
200
|
+
therefore cannot be routed outside the output directory, including through
|
|
201
|
+
names that collide on case-insensitive filesystems such as default macOS.
|
|
202
|
+
|
|
203
|
+
Setuid, setgid, and sticky mode bits are stripped on restore. Pass
|
|
204
|
+
`--preserve-special-bits` to keep them for archives you trust.
|
|
205
|
+
|
|
175
206
|
Restored symlinks may still point outside the restored repository, because that
|
|
176
207
|
is valid repository content. Use `--no-symlinks` if you want symlink targets
|
|
177
208
|
written as text files instead.
|
|
178
209
|
|
|
179
210
|
## Limitations
|
|
180
211
|
|
|
181
|
-
-
|
|
182
|
-
|
|
212
|
+
- With the default `--text-encoding base64`, file contents are base64 encoded,
|
|
213
|
+
so archives are larger than raw file bytes. Use `--text-encoding auto` for
|
|
214
|
+
readable source text, or gzip compression when archive size matters.
|
|
183
215
|
- Legacy format version 1 stores each file as one JSON record and is
|
|
184
216
|
memory-heavy for large files. Version 2 is chunked and is the default.
|
|
185
217
|
- Remote GitHub packing depends on local `git` and whatever authentication your
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Encode and decode inline archive file payloads."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import binascii
|
|
7
|
+
import hashlib
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
INLINE_ENCODINGS = frozenset({"base64", "utf8"})
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def file_content_bytes(path: str, record: dict[str, Any]) -> bytes:
|
|
15
|
+
encoding = record.get("encoding")
|
|
16
|
+
if encoding not in INLINE_ENCODINGS:
|
|
17
|
+
raise ValueError(f"{path}: unsupported inline encoding {encoding!r}")
|
|
18
|
+
|
|
19
|
+
if encoding == "base64":
|
|
20
|
+
content = record.get("content")
|
|
21
|
+
if not isinstance(content, str):
|
|
22
|
+
raise ValueError(f"{path}: content must be a base64 string")
|
|
23
|
+
try:
|
|
24
|
+
return base64.b64decode(content.encode("ascii"), validate=True)
|
|
25
|
+
except (UnicodeEncodeError, binascii.Error) as exc:
|
|
26
|
+
raise ValueError(f"{path}: invalid base64 content") from exc
|
|
27
|
+
|
|
28
|
+
content = record.get("content")
|
|
29
|
+
if not isinstance(content, str):
|
|
30
|
+
raise ValueError(f"{path}: content must be a UTF-8 string")
|
|
31
|
+
try:
|
|
32
|
+
return content.encode("utf-8")
|
|
33
|
+
except UnicodeEncodeError as exc:
|
|
34
|
+
raise ValueError(f"{path}: content is not valid UTF-8 text") from exc
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def validate_inline_file_record(record: dict[str, Any]) -> int:
|
|
38
|
+
path = record.get("path")
|
|
39
|
+
if not isinstance(path, str):
|
|
40
|
+
raise ValueError("record path must be a string")
|
|
41
|
+
encoding = record.get("encoding")
|
|
42
|
+
if encoding not in INLINE_ENCODINGS:
|
|
43
|
+
raise ValueError(f"{path}: unsupported encoding {encoding!r}")
|
|
44
|
+
|
|
45
|
+
content = file_content_bytes(path, record)
|
|
46
|
+
expected_size = record.get("size")
|
|
47
|
+
if not isinstance(expected_size, int) or expected_size < 0:
|
|
48
|
+
raise ValueError(f"{path}: invalid size {expected_size!r}")
|
|
49
|
+
if len(content) != expected_size:
|
|
50
|
+
raise ValueError(f"{path}: size mismatch")
|
|
51
|
+
|
|
52
|
+
digest = hashlib.sha256(content).hexdigest()
|
|
53
|
+
if digest != record.get("sha256"):
|
|
54
|
+
raise ValueError(f"{path}: sha256 mismatch")
|
|
55
|
+
return expected_size
|
|
@@ -23,6 +23,7 @@ from .archive import (
|
|
|
23
23
|
emit_json_line,
|
|
24
24
|
open_archive_for_write,
|
|
25
25
|
)
|
|
26
|
+
from .text_encoding import TEXT_ENCODING_CHOICES, should_store_as_utf8
|
|
26
27
|
|
|
27
28
|
|
|
28
29
|
def parse_args() -> argparse.Namespace:
|
|
@@ -97,6 +98,16 @@ def parse_args() -> argparse.Namespace:
|
|
|
97
98
|
default="auto",
|
|
98
99
|
help="Compress archive output. 'auto' uses gzip for .gz output paths.",
|
|
99
100
|
)
|
|
101
|
+
parser.add_argument(
|
|
102
|
+
"--text-encoding",
|
|
103
|
+
choices=sorted(TEXT_ENCODING_CHOICES),
|
|
104
|
+
default="base64",
|
|
105
|
+
help=(
|
|
106
|
+
"How to store file contents. 'base64' always encodes binary-safe base64. "
|
|
107
|
+
"'auto' stores known text files as readable UTF-8 JSON strings. "
|
|
108
|
+
"'utf8' stores any valid UTF-8 file as readable text."
|
|
109
|
+
),
|
|
110
|
+
)
|
|
100
111
|
return parser.parse_args()
|
|
101
112
|
|
|
102
113
|
|
|
@@ -273,21 +284,39 @@ def validate_regular_file(path: Path, rel: str, max_file_bytes: int | None) -> o
|
|
|
273
284
|
return metadata
|
|
274
285
|
|
|
275
286
|
|
|
276
|
-
def
|
|
287
|
+
def inline_file_record(
|
|
288
|
+
root: Path,
|
|
289
|
+
path: Path,
|
|
290
|
+
max_file_bytes: int | None,
|
|
291
|
+
text_encoding: str,
|
|
292
|
+
) -> dict[str, object]:
|
|
277
293
|
rel = safe_relative_path(root, path)
|
|
278
294
|
metadata = validate_regular_file(path, rel, max_file_bytes)
|
|
279
295
|
mode = stat.S_IMODE(metadata.st_mode)
|
|
280
|
-
size = metadata.st_size
|
|
281
296
|
content = path.read_bytes()
|
|
282
|
-
|
|
297
|
+
record: dict[str, object] = {
|
|
283
298
|
"type": "file",
|
|
284
299
|
"path": rel,
|
|
285
300
|
"mode": mode,
|
|
286
|
-
"size":
|
|
301
|
+
"size": len(content),
|
|
287
302
|
"sha256": hashlib.sha256(content).hexdigest(),
|
|
288
|
-
"encoding": "base64",
|
|
289
|
-
"content": base64.b64encode(content).decode("ascii"),
|
|
290
303
|
}
|
|
304
|
+
if should_store_as_utf8(rel, content, text_encoding):
|
|
305
|
+
record["encoding"] = "utf8"
|
|
306
|
+
record["content"] = content.decode("utf-8")
|
|
307
|
+
else:
|
|
308
|
+
record["encoding"] = "base64"
|
|
309
|
+
record["content"] = base64.b64encode(content).decode("ascii")
|
|
310
|
+
return record
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def file_record_v1(
|
|
314
|
+
root: Path,
|
|
315
|
+
path: Path,
|
|
316
|
+
max_file_bytes: int | None,
|
|
317
|
+
text_encoding: str = "base64",
|
|
318
|
+
) -> dict[str, object]:
|
|
319
|
+
return inline_file_record(root, path, max_file_bytes, text_encoding)
|
|
291
320
|
|
|
292
321
|
|
|
293
322
|
def hash_file(path: Path, chunk_size: int) -> str:
|
|
@@ -298,6 +327,47 @@ def hash_file(path: Path, chunk_size: int) -> str:
|
|
|
298
327
|
return digest.hexdigest()
|
|
299
328
|
|
|
300
329
|
|
|
330
|
+
def emit_file_records(
|
|
331
|
+
handle,
|
|
332
|
+
root: Path,
|
|
333
|
+
path: Path,
|
|
334
|
+
max_file_bytes: int | None,
|
|
335
|
+
format_version: int,
|
|
336
|
+
chunk_size: int,
|
|
337
|
+
text_encoding: str,
|
|
338
|
+
) -> int:
|
|
339
|
+
rel = safe_relative_path(root, path)
|
|
340
|
+
metadata = validate_regular_file(path, rel, max_file_bytes)
|
|
341
|
+
content = path.read_bytes()
|
|
342
|
+
|
|
343
|
+
if should_store_as_utf8(rel, content, text_encoding):
|
|
344
|
+
emit_json_line(handle, inline_file_record(root, path, max_file_bytes, text_encoding))
|
|
345
|
+
return 0
|
|
346
|
+
|
|
347
|
+
if format_version == 1:
|
|
348
|
+
emit_json_line(
|
|
349
|
+
handle,
|
|
350
|
+
{
|
|
351
|
+
"type": "file",
|
|
352
|
+
"path": rel,
|
|
353
|
+
"mode": stat.S_IMODE(metadata.st_mode),
|
|
354
|
+
"size": len(content),
|
|
355
|
+
"sha256": hashlib.sha256(content).hexdigest(),
|
|
356
|
+
"encoding": "base64",
|
|
357
|
+
"content": base64.b64encode(content).decode("ascii"),
|
|
358
|
+
},
|
|
359
|
+
)
|
|
360
|
+
return 0
|
|
361
|
+
|
|
362
|
+
return emit_file_records_v2(
|
|
363
|
+
handle,
|
|
364
|
+
root,
|
|
365
|
+
path,
|
|
366
|
+
max_file_bytes,
|
|
367
|
+
chunk_size,
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
|
|
301
371
|
def emit_file_records_v2(
|
|
302
372
|
handle,
|
|
303
373
|
root: Path,
|
|
@@ -367,11 +437,14 @@ def build_archive(
|
|
|
367
437
|
format_version: int = ARCHIVE_VERSION,
|
|
368
438
|
chunk_size: int = DEFAULT_CHUNK_SIZE,
|
|
369
439
|
compression: str = "auto",
|
|
440
|
+
text_encoding: str = "base64",
|
|
370
441
|
) -> tuple[int, int]:
|
|
371
442
|
if format_version not in (1, 2):
|
|
372
443
|
raise ValueError(f"unsupported archive format version: {format_version}")
|
|
373
444
|
if chunk_size <= 0:
|
|
374
445
|
raise ValueError("--chunk-size must be greater than zero")
|
|
446
|
+
if text_encoding not in TEXT_ENCODING_CHOICES:
|
|
447
|
+
raise ValueError(f"unsupported text encoding mode: {text_encoding}")
|
|
375
448
|
|
|
376
449
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
377
450
|
|
|
@@ -386,6 +459,8 @@ def build_archive(
|
|
|
386
459
|
}
|
|
387
460
|
if format_version == 2:
|
|
388
461
|
header["chunk_size"] = chunk_size
|
|
462
|
+
if text_encoding != "base64":
|
|
463
|
+
header["text_encoding"] = text_encoding
|
|
389
464
|
|
|
390
465
|
entry_count = 0
|
|
391
466
|
file_count = 0
|
|
@@ -417,21 +492,18 @@ def build_archive(
|
|
|
417
492
|
symlink_count += 1
|
|
418
493
|
emit_json_line(handle, record)
|
|
419
494
|
else:
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
max_file_bytes,
|
|
433
|
-
chunk_size,
|
|
434
|
-
)
|
|
495
|
+
rel = safe_relative_path(root, path)
|
|
496
|
+
metadata = validate_regular_file(path, rel, max_file_bytes)
|
|
497
|
+
byte_count += metadata.st_size
|
|
498
|
+
chunk_count += emit_file_records(
|
|
499
|
+
handle,
|
|
500
|
+
root,
|
|
501
|
+
path,
|
|
502
|
+
max_file_bytes,
|
|
503
|
+
format_version,
|
|
504
|
+
chunk_size,
|
|
505
|
+
text_encoding,
|
|
506
|
+
)
|
|
435
507
|
file_count += 1
|
|
436
508
|
entry_count += 1
|
|
437
509
|
|
|
@@ -476,6 +548,7 @@ def main() -> int:
|
|
|
476
548
|
format_version=int(args.format_version),
|
|
477
549
|
chunk_size=args.chunk_size,
|
|
478
550
|
compression=args.compress,
|
|
551
|
+
text_encoding=args.text_encoding,
|
|
479
552
|
)
|
|
480
553
|
except (OSError, ValueError) as exc:
|
|
481
554
|
print(f"error: {exc}", file=sys.stderr)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Detect text files suitable for UTF-8 archive storage."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import PurePosixPath
|
|
6
|
+
|
|
7
|
+
TEXT_EXTENSIONS = frozenset(
|
|
8
|
+
{
|
|
9
|
+
".c",
|
|
10
|
+
".cfg",
|
|
11
|
+
".conf",
|
|
12
|
+
".cpp",
|
|
13
|
+
".css",
|
|
14
|
+
".csv",
|
|
15
|
+
".env",
|
|
16
|
+
".gitattributes",
|
|
17
|
+
".gitignore",
|
|
18
|
+
".go",
|
|
19
|
+
".h",
|
|
20
|
+
".hpp",
|
|
21
|
+
".html",
|
|
22
|
+
".ini",
|
|
23
|
+
".java",
|
|
24
|
+
".js",
|
|
25
|
+
".json",
|
|
26
|
+
".jsx",
|
|
27
|
+
".kt",
|
|
28
|
+
".lock",
|
|
29
|
+
".lua",
|
|
30
|
+
".md",
|
|
31
|
+
".mjs",
|
|
32
|
+
".php",
|
|
33
|
+
".pl",
|
|
34
|
+
".properties",
|
|
35
|
+
".py",
|
|
36
|
+
".pyi",
|
|
37
|
+
".rb",
|
|
38
|
+
".rs",
|
|
39
|
+
".rst",
|
|
40
|
+
".scala",
|
|
41
|
+
".sh",
|
|
42
|
+
".sql",
|
|
43
|
+
".svg",
|
|
44
|
+
".swift",
|
|
45
|
+
".toml",
|
|
46
|
+
".ts",
|
|
47
|
+
".tsx",
|
|
48
|
+
".txt",
|
|
49
|
+
".xml",
|
|
50
|
+
".yaml",
|
|
51
|
+
".yml",
|
|
52
|
+
".zsh",
|
|
53
|
+
}
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
TEXT_FILENAMES = frozenset(
|
|
57
|
+
{
|
|
58
|
+
"CODEOWNERS",
|
|
59
|
+
"Dockerfile",
|
|
60
|
+
"LICENSE",
|
|
61
|
+
"Makefile",
|
|
62
|
+
"README",
|
|
63
|
+
"requirements.txt",
|
|
64
|
+
}
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
TEXT_ENCODING_CHOICES = frozenset({"base64", "auto", "utf8"})
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def bytes_look_like_utf8_text(data: bytes) -> bool:
|
|
71
|
+
if b"\x00" in data:
|
|
72
|
+
return False
|
|
73
|
+
try:
|
|
74
|
+
data.decode("utf-8")
|
|
75
|
+
except UnicodeDecodeError:
|
|
76
|
+
return False
|
|
77
|
+
return True
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def path_looks_like_text(rel_path: str) -> bool:
|
|
81
|
+
name = PurePosixPath(rel_path).name
|
|
82
|
+
if name in TEXT_FILENAMES:
|
|
83
|
+
return True
|
|
84
|
+
if name.startswith("README."):
|
|
85
|
+
return True
|
|
86
|
+
suffix = PurePosixPath(rel_path).suffix.lower()
|
|
87
|
+
return suffix in TEXT_EXTENSIONS
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def should_store_as_utf8(rel_path: str, data: bytes, text_encoding: str) -> bool:
|
|
91
|
+
if text_encoding not in TEXT_ENCODING_CHOICES:
|
|
92
|
+
raise ValueError(f"unsupported text encoding mode: {text_encoding}")
|
|
93
|
+
if text_encoding == "base64":
|
|
94
|
+
return False
|
|
95
|
+
if not bytes_look_like_utf8_text(data):
|
|
96
|
+
return False
|
|
97
|
+
if text_encoding == "utf8":
|
|
98
|
+
return True
|
|
99
|
+
return path_looks_like_text(rel_path)
|
|
@@ -8,6 +8,7 @@ import binascii
|
|
|
8
8
|
import hashlib
|
|
9
9
|
import os
|
|
10
10
|
import shutil
|
|
11
|
+
import stat
|
|
11
12
|
import sys
|
|
12
13
|
import tempfile
|
|
13
14
|
from dataclasses import dataclass, field
|
|
@@ -15,10 +16,16 @@ from pathlib import Path
|
|
|
15
16
|
from typing import Any
|
|
16
17
|
|
|
17
18
|
from .archive import ARCHIVE_KIND, SUPPORTED_ARCHIVE_VERSIONS, read_json_lines
|
|
19
|
+
from .content import file_content_bytes, validate_inline_file_record
|
|
18
20
|
|
|
19
21
|
|
|
20
22
|
ArchiveRecord = tuple[int, dict[str, Any]]
|
|
21
23
|
|
|
24
|
+
O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
|
|
25
|
+
O_BINARY = getattr(os, "O_BINARY", 0)
|
|
26
|
+
PERMISSION_BITS = 0o777
|
|
27
|
+
ALL_MODE_BITS = 0o7777
|
|
28
|
+
|
|
22
29
|
|
|
23
30
|
@dataclass
|
|
24
31
|
class ActiveFile:
|
|
@@ -30,6 +37,7 @@ class ActiveFile:
|
|
|
30
37
|
seen_size: int = 0
|
|
31
38
|
hasher: Any = field(default_factory=hashlib.sha256)
|
|
32
39
|
handle: Any | None = None
|
|
40
|
+
target: Path | None = None
|
|
33
41
|
mode: int | None = None
|
|
34
42
|
|
|
35
43
|
|
|
@@ -67,6 +75,14 @@ def parse_args() -> argparse.Namespace:
|
|
|
67
75
|
action="store_true",
|
|
68
76
|
help="Restore symlinks as small text files containing their target path.",
|
|
69
77
|
)
|
|
78
|
+
parser.add_argument(
|
|
79
|
+
"--preserve-special-bits",
|
|
80
|
+
action="store_true",
|
|
81
|
+
help=(
|
|
82
|
+
"Restore setuid, setgid, and sticky mode bits. By default only "
|
|
83
|
+
"read/write/execute permission bits are restored."
|
|
84
|
+
),
|
|
85
|
+
)
|
|
70
86
|
return parser.parse_args()
|
|
71
87
|
|
|
72
88
|
|
|
@@ -97,8 +113,58 @@ def safe_relative_parts(rel_path: str) -> tuple[str, ...]:
|
|
|
97
113
|
return parts
|
|
98
114
|
|
|
99
115
|
|
|
100
|
-
def
|
|
101
|
-
|
|
116
|
+
def ensure_safe_dir(root: Path, parts: tuple[str, ...]) -> Path:
|
|
117
|
+
"""Create ``root/parts`` one component at a time without following symlinks.
|
|
118
|
+
|
|
119
|
+
Every existing component must be a real directory. This keeps writes inside
|
|
120
|
+
``root`` even when an archive tries to route a path through a symlink,
|
|
121
|
+
including through case-insensitive name collisions.
|
|
122
|
+
"""
|
|
123
|
+
current = root
|
|
124
|
+
for index, part in enumerate(parts):
|
|
125
|
+
current = current / part
|
|
126
|
+
try:
|
|
127
|
+
metadata = os.lstat(current)
|
|
128
|
+
except FileNotFoundError:
|
|
129
|
+
os.mkdir(current)
|
|
130
|
+
continue
|
|
131
|
+
rel = "/".join(parts[: index + 1])
|
|
132
|
+
if stat.S_ISLNK(metadata.st_mode):
|
|
133
|
+
raise ValueError(f"{rel}: refusing to write through symlink")
|
|
134
|
+
if not stat.S_ISDIR(metadata.st_mode):
|
|
135
|
+
raise ValueError(f"{rel}: path component is not a directory")
|
|
136
|
+
return current
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def create_new_file(root: Path, rel_path: str) -> tuple[Any, Path]:
|
|
140
|
+
"""Create a new file inside ``root``; never follow or replace existing entries."""
|
|
141
|
+
parts = safe_relative_parts(rel_path)
|
|
142
|
+
parent = ensure_safe_dir(root, parts[:-1])
|
|
143
|
+
target = parent / parts[-1]
|
|
144
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | O_NOFOLLOW | O_BINARY
|
|
145
|
+
try:
|
|
146
|
+
fd = os.open(target, flags, 0o666)
|
|
147
|
+
except FileExistsError as exc:
|
|
148
|
+
raise ValueError(
|
|
149
|
+
f"{rel_path}: output path already exists (case-insensitive name collision?)"
|
|
150
|
+
) from exc
|
|
151
|
+
return os.fdopen(fd, "wb"), target
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def apply_file_mode(handle: Any, target: Path, mode: int | None) -> None:
|
|
155
|
+
if mode is None:
|
|
156
|
+
return
|
|
157
|
+
if hasattr(os, "fchmod"):
|
|
158
|
+
os.fchmod(handle.fileno(), mode)
|
|
159
|
+
else:
|
|
160
|
+
os.chmod(target, mode)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def write_new_file(root: Path, rel_path: str, content: bytes, mode: int | None) -> None:
|
|
164
|
+
handle, target = create_new_file(root, rel_path)
|
|
165
|
+
with handle:
|
|
166
|
+
handle.write(content)
|
|
167
|
+
apply_file_mode(handle, target, mode)
|
|
102
168
|
|
|
103
169
|
|
|
104
170
|
def validate_header(line_number: int, payload: dict[str, Any]) -> int:
|
|
@@ -126,9 +192,14 @@ def validate_mode(record: dict[str, Any]) -> None:
|
|
|
126
192
|
raise ValueError(f"{record.get('path')}: invalid mode {mode!r}")
|
|
127
193
|
|
|
128
194
|
|
|
129
|
-
def mode_from_record(
|
|
195
|
+
def mode_from_record(
|
|
196
|
+
record: dict[str, Any],
|
|
197
|
+
preserve_special_bits: bool = False,
|
|
198
|
+
) -> int | None:
|
|
130
199
|
mode = record.get("mode")
|
|
131
|
-
|
|
200
|
+
if not isinstance(mode, int):
|
|
201
|
+
return None
|
|
202
|
+
return mode & (ALL_MODE_BITS if preserve_special_bits else PERMISSION_BITS)
|
|
132
203
|
|
|
133
204
|
|
|
134
205
|
def decode_base64(path: str, content: Any) -> bytes:
|
|
@@ -140,40 +211,36 @@ def decode_base64(path: str, content: Any) -> bytes:
|
|
|
140
211
|
raise ValueError(f"{path}: invalid base64 content") from exc
|
|
141
212
|
|
|
142
213
|
|
|
143
|
-
def
|
|
214
|
+
def process_inline_file(
|
|
144
215
|
record: dict[str, Any],
|
|
145
216
|
write_root: Path | None,
|
|
217
|
+
preserve_special_bits: bool = False,
|
|
146
218
|
) -> int:
|
|
147
219
|
path = record_path(record)
|
|
148
220
|
validate_mode(record)
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
content = decode_base64(path, record.get("content"))
|
|
153
|
-
expected_size = record.get("size")
|
|
154
|
-
if not isinstance(expected_size, int) or expected_size < 0:
|
|
155
|
-
raise ValueError(f"{path}: invalid size {expected_size!r}")
|
|
156
|
-
if len(content) != expected_size:
|
|
157
|
-
raise ValueError(f"{path}: size mismatch")
|
|
158
|
-
|
|
159
|
-
digest = hashlib.sha256(content).hexdigest()
|
|
160
|
-
if digest != record.get("sha256"):
|
|
161
|
-
raise ValueError(f"{path}: sha256 mismatch")
|
|
221
|
+
expected_size = validate_inline_file_record(record)
|
|
222
|
+
content = file_content_bytes(path, record)
|
|
162
223
|
|
|
163
224
|
if write_root is not None:
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
mode = mode_from_record(record)
|
|
168
|
-
if mode is not None:
|
|
169
|
-
os.chmod(target, mode)
|
|
225
|
+
write_new_file(
|
|
226
|
+
write_root, path, content, mode_from_record(record, preserve_special_bits)
|
|
227
|
+
)
|
|
170
228
|
|
|
171
229
|
return expected_size
|
|
172
230
|
|
|
173
231
|
|
|
232
|
+
def process_file_v1(
|
|
233
|
+
record: dict[str, Any],
|
|
234
|
+
write_root: Path | None,
|
|
235
|
+
preserve_special_bits: bool = False,
|
|
236
|
+
) -> int:
|
|
237
|
+
return process_inline_file(record, write_root, preserve_special_bits)
|
|
238
|
+
|
|
239
|
+
|
|
174
240
|
def start_active_file(
|
|
175
241
|
record: dict[str, Any],
|
|
176
242
|
write_root: Path | None,
|
|
243
|
+
preserve_special_bits: bool = False,
|
|
177
244
|
) -> ActiveFile | None:
|
|
178
245
|
path = record_path(record)
|
|
179
246
|
validate_mode(record)
|
|
@@ -190,25 +257,20 @@ def start_active_file(
|
|
|
190
257
|
if not isinstance(expected_sha256, str) or expected_sha256 == "":
|
|
191
258
|
raise ValueError(f"{path}: sha256 must be a non-empty string")
|
|
192
259
|
|
|
193
|
-
mode = mode_from_record(record)
|
|
260
|
+
mode = mode_from_record(record, preserve_special_bits)
|
|
194
261
|
if expected_chunks == 0:
|
|
195
262
|
if expected_size != 0:
|
|
196
263
|
raise ValueError(f"{path}: zero chunks with non-zero size")
|
|
197
264
|
if hashlib.sha256(b"").hexdigest() != expected_sha256:
|
|
198
265
|
raise ValueError(f"{path}: sha256 mismatch")
|
|
199
266
|
if write_root is not None:
|
|
200
|
-
|
|
201
|
-
target.parent.mkdir(parents=True, exist_ok=True)
|
|
202
|
-
target.write_bytes(b"")
|
|
203
|
-
if mode is not None:
|
|
204
|
-
os.chmod(target, mode)
|
|
267
|
+
write_new_file(write_root, path, b"", mode)
|
|
205
268
|
return None
|
|
206
269
|
|
|
207
270
|
handle = None
|
|
271
|
+
target = None
|
|
208
272
|
if write_root is not None:
|
|
209
|
-
target =
|
|
210
|
-
target.parent.mkdir(parents=True, exist_ok=True)
|
|
211
|
-
handle = target.open("wb")
|
|
273
|
+
handle, target = create_new_file(write_root, path)
|
|
212
274
|
|
|
213
275
|
return ActiveFile(
|
|
214
276
|
path=path,
|
|
@@ -216,6 +278,7 @@ def start_active_file(
|
|
|
216
278
|
expected_size=expected_size,
|
|
217
279
|
expected_sha256=expected_sha256,
|
|
218
280
|
handle=handle,
|
|
281
|
+
target=target,
|
|
219
282
|
mode=mode,
|
|
220
283
|
)
|
|
221
284
|
|
|
@@ -261,9 +324,9 @@ def process_chunk_record(
|
|
|
261
324
|
raise ValueError(f"{path}: sha256 mismatch")
|
|
262
325
|
|
|
263
326
|
if active.handle is not None:
|
|
327
|
+
assert active.target is not None
|
|
328
|
+
apply_file_mode(active.handle, active.target, active.mode)
|
|
264
329
|
active.handle.close()
|
|
265
|
-
if active.mode is not None:
|
|
266
|
-
os.chmod(active.handle.name, active.mode)
|
|
267
330
|
return None
|
|
268
331
|
|
|
269
332
|
|
|
@@ -271,15 +334,15 @@ def process_dir_record(
|
|
|
271
334
|
record: dict[str, Any],
|
|
272
335
|
write_root: Path | None,
|
|
273
336
|
dir_modes: list[tuple[Path, int]],
|
|
337
|
+
preserve_special_bits: bool = False,
|
|
274
338
|
) -> None:
|
|
275
|
-
record_path(record)
|
|
339
|
+
path = record_path(record)
|
|
276
340
|
validate_mode(record)
|
|
277
341
|
if write_root is None:
|
|
278
342
|
return
|
|
279
343
|
|
|
280
|
-
target =
|
|
281
|
-
|
|
282
|
-
mode = mode_from_record(record)
|
|
344
|
+
target = ensure_safe_dir(write_root, safe_relative_parts(path))
|
|
345
|
+
mode = mode_from_record(record, preserve_special_bits)
|
|
283
346
|
if mode is not None:
|
|
284
347
|
dir_modes.append((target, mode))
|
|
285
348
|
|
|
@@ -300,29 +363,50 @@ def process_symlink_record(
|
|
|
300
363
|
if write_root is None:
|
|
301
364
|
return
|
|
302
365
|
|
|
303
|
-
output_target = safe_output_path(write_root, path)
|
|
304
|
-
output_target.parent.mkdir(parents=True, exist_ok=True)
|
|
305
366
|
if no_symlinks:
|
|
306
|
-
|
|
367
|
+
write_new_file(write_root, path, (target + "\n").encode("utf-8"), None)
|
|
307
368
|
return
|
|
308
|
-
|
|
369
|
+
parts = safe_relative_parts(path)
|
|
370
|
+
output_target = ensure_safe_dir(write_root, parts[:-1]) / parts[-1]
|
|
371
|
+
try:
|
|
372
|
+
os.symlink(target, output_target)
|
|
373
|
+
except FileExistsError as exc:
|
|
374
|
+
raise ValueError(
|
|
375
|
+
f"{path}: output path already exists (case-insensitive name collision?)"
|
|
376
|
+
) from exc
|
|
309
377
|
|
|
310
378
|
|
|
311
379
|
def logical_record(record: dict[str, Any]) -> dict[str, Any]:
|
|
312
380
|
return {key: value for key, value in record.items() if key != "content"}
|
|
313
381
|
|
|
314
382
|
|
|
315
|
-
def
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
383
|
+
def check_path_ancestry(
|
|
384
|
+
path: str,
|
|
385
|
+
record_type: str,
|
|
386
|
+
path_types: dict[str, str],
|
|
387
|
+
implied_dirs: set[str],
|
|
388
|
+
) -> None:
|
|
389
|
+
"""Reject ``path`` before anything is written for it.
|
|
390
|
+
|
|
391
|
+
A path may not sit under an archived symlink or file, and a non-directory
|
|
392
|
+
may not take the place of a directory that earlier entries live in.
|
|
393
|
+
"""
|
|
394
|
+
parts = safe_relative_parts(path)
|
|
395
|
+
for index in range(1, len(parts)):
|
|
396
|
+
ancestor = "/".join(parts[:index])
|
|
397
|
+
ancestor_type = path_types.get(ancestor)
|
|
398
|
+
if ancestor_type == "symlink":
|
|
399
|
+
raise ValueError(f"{path}: path is nested under archived symlink {ancestor}")
|
|
400
|
+
if ancestor_type == "file":
|
|
325
401
|
raise ValueError(f"{path}: path is nested under archived file {ancestor}")
|
|
402
|
+
if record_type != "dir" and path in implied_dirs:
|
|
403
|
+
raise ValueError(f"{path}: archived {record_type} replaces a parent directory")
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def record_implied_dirs(path: str, implied_dirs: set[str]) -> None:
|
|
407
|
+
parts = safe_relative_parts(path)
|
|
408
|
+
for index in range(1, len(parts)):
|
|
409
|
+
implied_dirs.add("/".join(parts[:index]))
|
|
326
410
|
|
|
327
411
|
|
|
328
412
|
def validate_end_record(
|
|
@@ -363,6 +447,7 @@ def process_archive(
|
|
|
363
447
|
write_root: Path | None = None,
|
|
364
448
|
no_symlinks: bool = False,
|
|
365
449
|
collect_records: bool = False,
|
|
450
|
+
preserve_special_bits: bool = False,
|
|
366
451
|
) -> ArchiveManifest:
|
|
367
452
|
records_iter = read_json_lines(archive_path)
|
|
368
453
|
try:
|
|
@@ -375,6 +460,7 @@ def process_archive(
|
|
|
375
460
|
records: list[ArchiveRecord] = []
|
|
376
461
|
seen_paths: set[str] = set()
|
|
377
462
|
path_types: dict[str, str] = {}
|
|
463
|
+
implied_dirs: set[str] = set()
|
|
378
464
|
entries = 0
|
|
379
465
|
files = 0
|
|
380
466
|
dirs = 0
|
|
@@ -398,18 +484,31 @@ def process_archive(
|
|
|
398
484
|
path = record_path(record)
|
|
399
485
|
if path in seen_paths:
|
|
400
486
|
raise ValueError(f"{path}: duplicate archive path")
|
|
487
|
+
check_path_ancestry(path, str(record_type), path_types, implied_dirs)
|
|
401
488
|
seen_paths.add(path)
|
|
402
489
|
path_types[path] = str(record_type)
|
|
490
|
+
record_implied_dirs(path, implied_dirs)
|
|
403
491
|
|
|
404
492
|
if record_type == "dir":
|
|
405
|
-
process_dir_record(
|
|
493
|
+
process_dir_record(
|
|
494
|
+
record, write_root, dir_modes, preserve_special_bits
|
|
495
|
+
)
|
|
406
496
|
dirs += 1
|
|
407
497
|
elif record_type == "file":
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
498
|
+
encoding = record.get("encoding")
|
|
499
|
+
if version == 1 or encoding in {"base64", "utf8"}:
|
|
500
|
+
bytes_count += process_inline_file(
|
|
501
|
+
record, write_root, preserve_special_bits
|
|
502
|
+
)
|
|
503
|
+
elif encoding == "base64-chunks":
|
|
504
|
+
active_file = start_active_file(
|
|
505
|
+
record, write_root, preserve_special_bits
|
|
506
|
+
)
|
|
412
507
|
bytes_count += int(record["size"])
|
|
508
|
+
else:
|
|
509
|
+
raise ValueError(
|
|
510
|
+
f"{path}: unsupported file encoding {encoding!r}"
|
|
511
|
+
)
|
|
413
512
|
files += 1
|
|
414
513
|
else:
|
|
415
514
|
process_symlink_record(record, write_root, no_symlinks)
|
|
@@ -432,13 +531,13 @@ def process_archive(
|
|
|
432
531
|
raise ValueError(f"unknown record type {record_type!r}")
|
|
433
532
|
except KeyError as exc:
|
|
434
533
|
raise ValueError(f"line {line_number}: missing required key {exc}") from exc
|
|
435
|
-
except
|
|
436
|
-
raise
|
|
534
|
+
except (ValueError, TypeError) as exc:
|
|
535
|
+
raise ValueError(f"line {line_number}: {exc}") from exc
|
|
536
|
+
except OSError as exc:
|
|
537
|
+
raise OSError(f"line {line_number}: {exc}") from exc
|
|
437
538
|
|
|
438
539
|
if not saw_end:
|
|
439
540
|
raise ValueError("archive is missing end record")
|
|
440
|
-
|
|
441
|
-
validate_path_ancestry(path_types)
|
|
442
541
|
finally:
|
|
443
542
|
if active_file is not None and active_file.handle is not None:
|
|
444
543
|
active_file.handle.close()
|
|
@@ -512,6 +611,7 @@ def restore_archive(
|
|
|
512
611
|
overwrite: bool,
|
|
513
612
|
verify_only: bool,
|
|
514
613
|
no_symlinks: bool,
|
|
614
|
+
preserve_special_bits: bool = False,
|
|
515
615
|
) -> tuple[int, int]:
|
|
516
616
|
if verify_only:
|
|
517
617
|
manifest = process_archive(archive_path)
|
|
@@ -532,6 +632,7 @@ def restore_archive(
|
|
|
532
632
|
archive_path,
|
|
533
633
|
write_root=staging_dir,
|
|
534
634
|
no_symlinks=no_symlinks,
|
|
635
|
+
preserve_special_bits=preserve_special_bits,
|
|
535
636
|
)
|
|
536
637
|
replace_output_with_staging(staging_dir, output_dir, overwrite)
|
|
537
638
|
staging_dir = None
|
|
@@ -554,6 +655,7 @@ def main() -> int:
|
|
|
554
655
|
overwrite=args.overwrite,
|
|
555
656
|
verify_only=args.verify_only,
|
|
556
657
|
no_symlinks=args.no_symlinks,
|
|
658
|
+
preserve_special_bits=args.preserve_special_bits,
|
|
557
659
|
)
|
|
558
660
|
except (OSError, ValueError, FileExistsError) as exc:
|
|
559
661
|
print(f"error: {exc}", file=sys.stderr)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: flat-packager
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.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
|
|
@@ -114,8 +114,29 @@ Useful options:
|
|
|
114
114
|
flat-pack /path/to/repo repo.flat.txt --exclude "node_modules/*"
|
|
115
115
|
flat-pack /path/to/repo repo.flat.txt --max-file-bytes 10485760
|
|
116
116
|
flat-pack /path/to/repo repo.flat.txt --include-git
|
|
117
|
+
flat-pack /path/to/repo repo.flat.txt --text-encoding auto
|
|
117
118
|
```
|
|
118
119
|
|
|
120
|
+
## Text Encoding
|
|
121
|
+
|
|
122
|
+
By default every file is stored as base64 (binary-safe). For human-readable
|
|
123
|
+
archives, use `--text-encoding auto` to store known text files such as `.py`,
|
|
124
|
+
`.md`, `.yaml`, and `.json` as plain UTF-8 JSON strings:
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
flat-pack /path/to/repo repo.flat.txt --text-encoding auto --compress none
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
In the archive, text files look like:
|
|
131
|
+
|
|
132
|
+
```json
|
|
133
|
+
{"encoding":"utf8","path":"src/app.py","content":"def main():\n ..."}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Binary files still use base64 chunks. Use `--text-encoding utf8` to store any
|
|
137
|
+
valid UTF-8 file as readable text. The default `--text-encoding base64` keeps
|
|
138
|
+
every file base64-encoded for maximum compatibility.
|
|
139
|
+
|
|
119
140
|
## Format and Compression
|
|
120
141
|
|
|
121
142
|
New archives use format version 2 by default. Version 2 stores each regular
|
|
@@ -198,19 +219,30 @@ The restore step rejects:
|
|
|
198
219
|
- absolute archive paths
|
|
199
220
|
- `..`, `.`, empty, or backslash path segments
|
|
200
221
|
- duplicate archive paths
|
|
201
|
-
- file or directory records nested underneath an archived symlink
|
|
222
|
+
- file or directory records nested underneath an archived symlink or file,
|
|
223
|
+
checked before anything is written for that record
|
|
224
|
+
- a symlink or file that would replace a directory other entries live in
|
|
202
225
|
- chunk records that are missing, out of order, corrupt, or attached to the
|
|
203
226
|
wrong file
|
|
204
227
|
- corrupt base64, size, or SHA-256 data
|
|
205
228
|
|
|
229
|
+
As a second layer, restores create directories one component at a time without
|
|
230
|
+
following symlinks and create files exclusively (`O_EXCL`/`O_NOFOLLOW`). Writes
|
|
231
|
+
therefore cannot be routed outside the output directory, including through
|
|
232
|
+
names that collide on case-insensitive filesystems such as default macOS.
|
|
233
|
+
|
|
234
|
+
Setuid, setgid, and sticky mode bits are stripped on restore. Pass
|
|
235
|
+
`--preserve-special-bits` to keep them for archives you trust.
|
|
236
|
+
|
|
206
237
|
Restored symlinks may still point outside the restored repository, because that
|
|
207
238
|
is valid repository content. Use `--no-symlinks` if you want symlink targets
|
|
208
239
|
written as text files instead.
|
|
209
240
|
|
|
210
241
|
## Limitations
|
|
211
242
|
|
|
212
|
-
-
|
|
213
|
-
|
|
243
|
+
- With the default `--text-encoding base64`, file contents are base64 encoded,
|
|
244
|
+
so archives are larger than raw file bytes. Use `--text-encoding auto` for
|
|
245
|
+
readable source text, or gzip compression when archive size matters.
|
|
214
246
|
- Legacy format version 1 stores each file as one JSON record and is
|
|
215
247
|
memory-heavy for large files. Version 2 is chunked and is the default.
|
|
216
248
|
- Remote GitHub packing depends on local `git` and whatever authentication your
|
|
@@ -3,8 +3,10 @@ README.md
|
|
|
3
3
|
pyproject.toml
|
|
4
4
|
src/flat_packager/__init__.py
|
|
5
5
|
src/flat_packager/archive.py
|
|
6
|
+
src/flat_packager/content.py
|
|
6
7
|
src/flat_packager/inspect.py
|
|
7
8
|
src/flat_packager/pack.py
|
|
9
|
+
src/flat_packager/text_encoding.py
|
|
8
10
|
src/flat_packager/unpack.py
|
|
9
11
|
src/flat_packager/verify.py
|
|
10
12
|
src/flat_packager.egg-info/PKG-INFO
|
|
@@ -4,6 +4,7 @@ import base64
|
|
|
4
4
|
import hashlib
|
|
5
5
|
import os
|
|
6
6
|
import shutil
|
|
7
|
+
import stat
|
|
7
8
|
import subprocess
|
|
8
9
|
import sys
|
|
9
10
|
import tempfile
|
|
@@ -273,18 +274,116 @@ class RoundTripTests(unittest.TestCase):
|
|
|
273
274
|
self.assertTrue((output / "link").is_dir())
|
|
274
275
|
self.assertEqual((output / "link" / "owned.txt").read_text(encoding="utf-8"), "owned\n")
|
|
275
276
|
|
|
277
|
+
def restore_expecting_error(self, archive: Path, pattern: str) -> Path:
|
|
278
|
+
output = self.work_dir / "output"
|
|
279
|
+
with self.assertRaisesRegex(ValueError, pattern):
|
|
280
|
+
restore_archive(
|
|
281
|
+
archive_path=archive,
|
|
282
|
+
output_dir=output,
|
|
283
|
+
overwrite=False,
|
|
284
|
+
verify_only=False,
|
|
285
|
+
no_symlinks=False,
|
|
286
|
+
)
|
|
287
|
+
self.assertFalse(output.exists())
|
|
288
|
+
return output
|
|
289
|
+
|
|
290
|
+
def make_outside_dir(self) -> Path:
|
|
291
|
+
outside = self.work_dir / "outside"
|
|
292
|
+
outside.mkdir()
|
|
293
|
+
return outside
|
|
294
|
+
|
|
276
295
|
def test_archive_symlink_ancestor_is_rejected(self) -> None:
|
|
277
296
|
archive = self.work_dir / "archive.flat.txt"
|
|
297
|
+
outside = self.make_outside_dir()
|
|
298
|
+
write_archive(
|
|
299
|
+
archive,
|
|
300
|
+
[
|
|
301
|
+
symlink_record("link", str(outside)),
|
|
302
|
+
file_record("link/owned.txt", b"owned\n"),
|
|
303
|
+
],
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
self.restore_expecting_error(archive, "nested under archived symlink")
|
|
307
|
+
self.assertEqual(list(outside.iterdir()), [])
|
|
308
|
+
|
|
309
|
+
def test_chunked_file_under_archive_symlink_does_not_escape(self) -> None:
|
|
310
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
311
|
+
outside = self.make_outside_dir()
|
|
312
|
+
content = b"owned\n"
|
|
313
|
+
with archive.open("w", encoding="utf-8", newline="\n") as handle:
|
|
314
|
+
emit_json_line(handle, {"type": ARCHIVE_KIND, "version": 2})
|
|
315
|
+
emit_json_line(handle, symlink_record("link", str(outside)))
|
|
316
|
+
emit_json_line(
|
|
317
|
+
handle,
|
|
318
|
+
{
|
|
319
|
+
"type": "file",
|
|
320
|
+
"path": "link/owned.txt",
|
|
321
|
+
"mode": 0o644,
|
|
322
|
+
"size": len(content),
|
|
323
|
+
"sha256": hashlib.sha256(content).hexdigest(),
|
|
324
|
+
"encoding": "base64-chunks",
|
|
325
|
+
"chunks": 1,
|
|
326
|
+
},
|
|
327
|
+
)
|
|
328
|
+
emit_json_line(
|
|
329
|
+
handle,
|
|
330
|
+
{
|
|
331
|
+
"type": "chunk",
|
|
332
|
+
"path": "link/owned.txt",
|
|
333
|
+
"index": 0,
|
|
334
|
+
"size": len(content),
|
|
335
|
+
"content": base64.b64encode(content).decode("ascii"),
|
|
336
|
+
},
|
|
337
|
+
)
|
|
338
|
+
emit_json_line(handle, {"type": "end", "entries": 2, "files": 1})
|
|
339
|
+
|
|
340
|
+
self.restore_expecting_error(archive, "nested under archived symlink")
|
|
341
|
+
self.assertEqual(list(outside.iterdir()), [])
|
|
342
|
+
|
|
343
|
+
def test_dir_under_archive_symlink_does_not_escape(self) -> None:
|
|
344
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
345
|
+
outside = self.make_outside_dir()
|
|
346
|
+
write_archive(
|
|
347
|
+
archive,
|
|
348
|
+
[
|
|
349
|
+
symlink_record("link", str(outside)),
|
|
350
|
+
{"type": "dir", "path": "link/created", "mode": 0o755},
|
|
351
|
+
],
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
self.restore_expecting_error(archive, "nested under archived symlink")
|
|
355
|
+
self.assertEqual(list(outside.iterdir()), [])
|
|
356
|
+
|
|
357
|
+
def test_symlink_replacing_populated_directory_is_rejected(self) -> None:
|
|
358
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
359
|
+
outside = self.make_outside_dir()
|
|
360
|
+
write_archive(
|
|
361
|
+
archive,
|
|
362
|
+
[
|
|
363
|
+
file_record("dir/a.txt", b"a\n"),
|
|
364
|
+
symlink_record("dir", str(outside)),
|
|
365
|
+
],
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
self.restore_expecting_error(archive, "replaces a parent directory")
|
|
369
|
+
self.assertEqual(list(outside.iterdir()), [])
|
|
370
|
+
|
|
371
|
+
def test_case_variant_of_symlink_cannot_redirect_restore(self) -> None:
|
|
372
|
+
# On case-insensitive filesystems "Link" and "link" are the same entry.
|
|
373
|
+
# The restore must refuse rather than write through the symlink; on
|
|
374
|
+
# case-sensitive filesystems the archive is simply valid.
|
|
375
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
376
|
+
outside = self.make_outside_dir()
|
|
278
377
|
output = self.work_dir / "output"
|
|
279
378
|
write_archive(
|
|
280
379
|
archive,
|
|
281
380
|
[
|
|
282
|
-
symlink_record("
|
|
381
|
+
symlink_record("Link", str(outside)),
|
|
283
382
|
file_record("link/owned.txt", b"owned\n"),
|
|
284
383
|
],
|
|
285
384
|
)
|
|
286
385
|
|
|
287
|
-
|
|
386
|
+
try:
|
|
288
387
|
restore_archive(
|
|
289
388
|
archive_path=archive,
|
|
290
389
|
output_dir=output,
|
|
@@ -292,8 +391,68 @@ class RoundTripTests(unittest.TestCase):
|
|
|
292
391
|
verify_only=False,
|
|
293
392
|
no_symlinks=False,
|
|
294
393
|
)
|
|
394
|
+
except ValueError as exc:
|
|
395
|
+
self.assertIn("refusing to write through symlink", str(exc))
|
|
396
|
+
self.assertFalse(output.exists())
|
|
397
|
+
else:
|
|
398
|
+
self.assertEqual((output / "link" / "owned.txt").read_bytes(), b"owned\n")
|
|
399
|
+
self.assertEqual(list(outside.iterdir()), [])
|
|
295
400
|
|
|
296
|
-
|
|
401
|
+
def test_special_mode_bits_are_stripped_by_default(self) -> None:
|
|
402
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
403
|
+
output = self.work_dir / "output"
|
|
404
|
+
record = file_record("run.sh", b"#!/bin/sh\n")
|
|
405
|
+
record["mode"] = 0o6755
|
|
406
|
+
write_archive(archive, [record])
|
|
407
|
+
|
|
408
|
+
restore_archive(
|
|
409
|
+
archive_path=archive,
|
|
410
|
+
output_dir=output,
|
|
411
|
+
overwrite=False,
|
|
412
|
+
verify_only=False,
|
|
413
|
+
no_symlinks=False,
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
self.assertEqual(stat.S_IMODE((output / "run.sh").stat().st_mode), 0o755)
|
|
417
|
+
|
|
418
|
+
@unittest.skipIf(os.name == "nt", "sticky bit is POSIX-only")
|
|
419
|
+
def test_preserve_special_bits_opt_in(self) -> None:
|
|
420
|
+
# The sticky bit on a directory is settable by its owner on Linux and
|
|
421
|
+
# macOS, unlike setuid/setgid which the OS may silently clear.
|
|
422
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
423
|
+
write_archive(archive, [{"type": "dir", "path": "shared", "mode": 0o1777}])
|
|
424
|
+
|
|
425
|
+
for preserve, expected in ((False, 0o777), (True, 0o1777)):
|
|
426
|
+
output = self.work_dir / f"output-{preserve}"
|
|
427
|
+
restore_archive(
|
|
428
|
+
archive_path=archive,
|
|
429
|
+
output_dir=output,
|
|
430
|
+
overwrite=False,
|
|
431
|
+
verify_only=False,
|
|
432
|
+
no_symlinks=False,
|
|
433
|
+
preserve_special_bits=preserve,
|
|
434
|
+
)
|
|
435
|
+
self.assertEqual(stat.S_IMODE((output / "shared").stat().st_mode), expected)
|
|
436
|
+
|
|
437
|
+
def test_invalid_utf8_text_content_is_a_clean_error(self) -> None:
|
|
438
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
439
|
+
write_archive(
|
|
440
|
+
archive,
|
|
441
|
+
[
|
|
442
|
+
{
|
|
443
|
+
"type": "file",
|
|
444
|
+
"path": "x.txt",
|
|
445
|
+
"mode": 0o644,
|
|
446
|
+
"size": 1,
|
|
447
|
+
"sha256": "0" * 64,
|
|
448
|
+
"encoding": "utf8",
|
|
449
|
+
"content": "\ud800",
|
|
450
|
+
}
|
|
451
|
+
],
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
with self.assertRaisesRegex(ValueError, "line 2: x.txt: content is not valid UTF-8"):
|
|
455
|
+
load_and_validate_archive(archive)
|
|
297
456
|
|
|
298
457
|
def test_non_empty_output_without_overwrite_raises_file_exists_error(self) -> None:
|
|
299
458
|
source = self.work_dir / "source"
|
|
@@ -427,6 +586,43 @@ class RoundTripTests(unittest.TestCase):
|
|
|
427
586
|
|
|
428
587
|
self.assertFalse(output.exists())
|
|
429
588
|
|
|
589
|
+
def test_auto_text_encoding_stores_source_as_readable_utf8(self) -> None:
|
|
590
|
+
source = self.work_dir / "source"
|
|
591
|
+
archive = self.work_dir / "repo.flat.txt"
|
|
592
|
+
restored = self.work_dir / "restored"
|
|
593
|
+
source.mkdir()
|
|
594
|
+
(source / "hello.py").write_text("def greet():\n return 'hi'\n", encoding="utf-8")
|
|
595
|
+
(source / "data.bin").write_bytes(bytes(range(256)))
|
|
596
|
+
|
|
597
|
+
build_archive(
|
|
598
|
+
root=source,
|
|
599
|
+
output_path=archive,
|
|
600
|
+
source_label=str(source),
|
|
601
|
+
tracked_only=False,
|
|
602
|
+
include_git=False,
|
|
603
|
+
exclude_patterns=[],
|
|
604
|
+
max_file_bytes=None,
|
|
605
|
+
text_encoding="auto",
|
|
606
|
+
)
|
|
607
|
+
|
|
608
|
+
archive_text = archive.read_text(encoding="utf-8")
|
|
609
|
+
self.assertIn('"encoding":"utf8"', archive_text)
|
|
610
|
+
self.assertIn("def greet():", archive_text)
|
|
611
|
+
self.assertIn('"encoding":"base64-chunks"', archive_text)
|
|
612
|
+
|
|
613
|
+
restore_archive(
|
|
614
|
+
archive_path=archive,
|
|
615
|
+
output_dir=restored,
|
|
616
|
+
overwrite=False,
|
|
617
|
+
verify_only=False,
|
|
618
|
+
no_symlinks=False,
|
|
619
|
+
)
|
|
620
|
+
self.assertEqual(
|
|
621
|
+
(restored / "hello.py").read_text(encoding="utf-8"),
|
|
622
|
+
"def greet():\n return 'hi'\n",
|
|
623
|
+
)
|
|
624
|
+
self.assertEqual((restored / "data.bin").read_bytes(), bytes(range(256)))
|
|
625
|
+
|
|
430
626
|
def test_remote_clone_options_are_passed_to_git(self) -> None:
|
|
431
627
|
with patch("flat_packager.pack.subprocess.run") as run:
|
|
432
628
|
run.return_value = subprocess.CompletedProcess(args=[], returncode=0)
|
|
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
|