flat-packager 0.4.0__py3-none-any.whl

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.
@@ -0,0 +1,568 @@
1
+ """Rebuild a repository tree from a flat text archive."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import base64
7
+ import binascii
8
+ import hashlib
9
+ import os
10
+ import shutil
11
+ import sys
12
+ import tempfile
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from .archive import ARCHIVE_KIND, SUPPORTED_ARCHIVE_VERSIONS, read_json_lines
18
+
19
+
20
+ ArchiveRecord = tuple[int, dict[str, Any]]
21
+
22
+
23
+ @dataclass
24
+ class ActiveFile:
25
+ path: str
26
+ expected_chunks: int
27
+ expected_size: int
28
+ expected_sha256: str
29
+ seen_chunks: int = 0
30
+ seen_size: int = 0
31
+ hasher: Any = field(default_factory=hashlib.sha256)
32
+ handle: Any | None = None
33
+ mode: int | None = None
34
+
35
+
36
+ @dataclass
37
+ class ArchiveManifest:
38
+ header: dict[str, Any]
39
+ version: int
40
+ records: list[ArchiveRecord]
41
+ entries: int
42
+ files: int
43
+ dirs: int
44
+ symlinks: int
45
+ chunks: int
46
+ bytes: int
47
+
48
+
49
+ def parse_args() -> argparse.Namespace:
50
+ parser = argparse.ArgumentParser(
51
+ description="Restore a repository tree from a flat text archive."
52
+ )
53
+ parser.add_argument("archive", help="Flat text archive created by flat-pack.")
54
+ parser.add_argument("output_dir", help="Directory to create or restore into.")
55
+ parser.add_argument(
56
+ "--overwrite",
57
+ action="store_true",
58
+ help="Allow replacing an existing output directory.",
59
+ )
60
+ parser.add_argument(
61
+ "--verify-only",
62
+ action="store_true",
63
+ help="Validate archive structure and hashes without writing files.",
64
+ )
65
+ parser.add_argument(
66
+ "--no-symlinks",
67
+ action="store_true",
68
+ help="Restore symlinks as small text files containing their target path.",
69
+ )
70
+ return parser.parse_args()
71
+
72
+
73
+ def absolute_path(path: Path) -> Path:
74
+ expanded = path.expanduser()
75
+ if expanded.is_absolute():
76
+ return expanded
77
+ return Path.cwd() / expanded
78
+
79
+
80
+ def path_exists(path: Path) -> bool:
81
+ return path.exists() or path.is_symlink()
82
+
83
+
84
+ def safe_relative_parts(rel_path: str) -> tuple[str, ...]:
85
+ if not isinstance(rel_path, str):
86
+ raise ValueError(f"archive path must be a string: {rel_path!r}")
87
+ if "\x00" in rel_path:
88
+ raise ValueError(f"archive path contains NUL byte: {rel_path!r}")
89
+ if "\\" in rel_path:
90
+ raise ValueError(f"archive path contains unsupported backslash: {rel_path!r}")
91
+ if rel_path in ("", ".") or rel_path.startswith("/"):
92
+ raise ValueError(f"unsafe archive path: {rel_path}")
93
+
94
+ parts = tuple(rel_path.split("/"))
95
+ if any(part in ("", ".", "..") for part in parts):
96
+ raise ValueError(f"unsafe archive path: {rel_path}")
97
+ return parts
98
+
99
+
100
+ def safe_output_path(root: Path, rel_path: str) -> Path:
101
+ return root.joinpath(*safe_relative_parts(rel_path))
102
+
103
+
104
+ def validate_header(line_number: int, payload: dict[str, Any]) -> int:
105
+ if payload.get("type") != ARCHIVE_KIND:
106
+ raise ValueError(f"line {line_number}: not a {ARCHIVE_KIND} archive")
107
+ version = payload.get("version")
108
+ if version not in SUPPORTED_ARCHIVE_VERSIONS:
109
+ raise ValueError(f"line {line_number}: unsupported archive version {version}")
110
+ return int(version)
111
+
112
+
113
+ def record_path(record: dict[str, Any]) -> str:
114
+ path = record.get("path")
115
+ if not isinstance(path, str):
116
+ raise ValueError("record path must be a string")
117
+ safe_relative_parts(path)
118
+ return path
119
+
120
+
121
+ def validate_mode(record: dict[str, Any]) -> None:
122
+ mode = record.get("mode")
123
+ if mode is None:
124
+ return
125
+ if not isinstance(mode, int) or mode < 0 or mode > 0o7777:
126
+ raise ValueError(f"{record.get('path')}: invalid mode {mode!r}")
127
+
128
+
129
+ def mode_from_record(record: dict[str, Any]) -> int | None:
130
+ mode = record.get("mode")
131
+ return mode if isinstance(mode, int) else None
132
+
133
+
134
+ def decode_base64(path: str, content: Any) -> bytes:
135
+ if not isinstance(content, str):
136
+ raise ValueError(f"{path}: content must be a base64 string")
137
+ try:
138
+ return base64.b64decode(content.encode("ascii"), validate=True)
139
+ except (UnicodeEncodeError, binascii.Error) as exc:
140
+ raise ValueError(f"{path}: invalid base64 content") from exc
141
+
142
+
143
+ def process_file_v1(
144
+ record: dict[str, Any],
145
+ write_root: Path | None,
146
+ ) -> int:
147
+ path = record_path(record)
148
+ validate_mode(record)
149
+ if record.get("encoding") != "base64":
150
+ raise ValueError(f"{path}: unsupported encoding {record.get('encoding')}")
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")
162
+
163
+ if write_root is not None:
164
+ target = safe_output_path(write_root, path)
165
+ target.parent.mkdir(parents=True, exist_ok=True)
166
+ target.write_bytes(content)
167
+ mode = mode_from_record(record)
168
+ if mode is not None:
169
+ os.chmod(target, mode)
170
+
171
+ return expected_size
172
+
173
+
174
+ def start_active_file(
175
+ record: dict[str, Any],
176
+ write_root: Path | None,
177
+ ) -> ActiveFile | None:
178
+ path = record_path(record)
179
+ validate_mode(record)
180
+ if record.get("encoding") != "base64-chunks":
181
+ raise ValueError(f"{path}: unsupported encoding {record.get('encoding')}")
182
+
183
+ expected_size = record.get("size")
184
+ if not isinstance(expected_size, int) or expected_size < 0:
185
+ raise ValueError(f"{path}: invalid size {expected_size!r}")
186
+ expected_chunks = record.get("chunks")
187
+ if not isinstance(expected_chunks, int) or expected_chunks < 0:
188
+ raise ValueError(f"{path}: invalid chunks count {expected_chunks!r}")
189
+ expected_sha256 = record.get("sha256")
190
+ if not isinstance(expected_sha256, str) or expected_sha256 == "":
191
+ raise ValueError(f"{path}: sha256 must be a non-empty string")
192
+
193
+ mode = mode_from_record(record)
194
+ if expected_chunks == 0:
195
+ if expected_size != 0:
196
+ raise ValueError(f"{path}: zero chunks with non-zero size")
197
+ if hashlib.sha256(b"").hexdigest() != expected_sha256:
198
+ raise ValueError(f"{path}: sha256 mismatch")
199
+ if write_root is not None:
200
+ target = safe_output_path(write_root, path)
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)
205
+ return None
206
+
207
+ handle = None
208
+ if write_root is not None:
209
+ target = safe_output_path(write_root, path)
210
+ target.parent.mkdir(parents=True, exist_ok=True)
211
+ handle = target.open("wb")
212
+
213
+ return ActiveFile(
214
+ path=path,
215
+ expected_chunks=expected_chunks,
216
+ expected_size=expected_size,
217
+ expected_sha256=expected_sha256,
218
+ handle=handle,
219
+ mode=mode,
220
+ )
221
+
222
+
223
+ def process_chunk_record(
224
+ record: dict[str, Any],
225
+ active: ActiveFile | None,
226
+ ) -> ActiveFile | None:
227
+ if active is None:
228
+ raise ValueError("chunk record is not attached to a file")
229
+
230
+ path = record_path(record)
231
+ if path != active.path:
232
+ raise ValueError(
233
+ f"chunk path {path!r} does not match open file {active.path!r}"
234
+ )
235
+ index = record.get("index")
236
+ if index != active.seen_chunks:
237
+ raise ValueError(f"{path}: chunk index mismatch, expected {active.seen_chunks}")
238
+
239
+ chunk = decode_base64(path, record.get("content"))
240
+ expected_size = record.get("size")
241
+ if not isinstance(expected_size, int) or expected_size < 0:
242
+ raise ValueError(f"{path}: invalid chunk size {expected_size!r}")
243
+ if len(chunk) != expected_size:
244
+ raise ValueError(f"{path}: chunk size mismatch")
245
+
246
+ chunk_digest = record.get("sha256")
247
+ if chunk_digest is not None and hashlib.sha256(chunk).hexdigest() != chunk_digest:
248
+ raise ValueError(f"{path}: chunk sha256 mismatch")
249
+
250
+ active.hasher.update(chunk)
251
+ if active.handle is not None:
252
+ active.handle.write(chunk)
253
+ active.seen_chunks += 1
254
+ active.seen_size += len(chunk)
255
+ if active.seen_chunks < active.expected_chunks:
256
+ return active
257
+
258
+ if active.seen_size != active.expected_size:
259
+ raise ValueError(f"{path}: size mismatch")
260
+ if active.hasher.hexdigest() != active.expected_sha256:
261
+ raise ValueError(f"{path}: sha256 mismatch")
262
+
263
+ if active.handle is not None:
264
+ active.handle.close()
265
+ if active.mode is not None:
266
+ os.chmod(active.handle.name, active.mode)
267
+ return None
268
+
269
+
270
+ def process_dir_record(
271
+ record: dict[str, Any],
272
+ write_root: Path | None,
273
+ dir_modes: list[tuple[Path, int]],
274
+ ) -> None:
275
+ record_path(record)
276
+ validate_mode(record)
277
+ if write_root is None:
278
+ return
279
+
280
+ target = safe_output_path(write_root, record["path"])
281
+ target.mkdir(parents=True, exist_ok=True)
282
+ mode = mode_from_record(record)
283
+ if mode is not None:
284
+ dir_modes.append((target, mode))
285
+
286
+
287
+ def process_symlink_record(
288
+ record: dict[str, Any],
289
+ write_root: Path | None,
290
+ no_symlinks: bool,
291
+ ) -> None:
292
+ path = record_path(record)
293
+ validate_mode(record)
294
+ target = record.get("target")
295
+ if not isinstance(target, str) or target == "":
296
+ raise ValueError(f"{path}: symlink target must be a non-empty string")
297
+ if "\x00" in target:
298
+ raise ValueError(f"{path}: symlink target contains NUL byte")
299
+
300
+ if write_root is None:
301
+ return
302
+
303
+ output_target = safe_output_path(write_root, path)
304
+ output_target.parent.mkdir(parents=True, exist_ok=True)
305
+ if no_symlinks:
306
+ output_target.write_text(str(target) + "\n", encoding="utf-8")
307
+ return
308
+ os.symlink(str(target), output_target)
309
+
310
+
311
+ def logical_record(record: dict[str, Any]) -> dict[str, Any]:
312
+ return {key: value for key, value in record.items() if key != "content"}
313
+
314
+
315
+ def validate_path_ancestry(path_types: dict[str, str]) -> None:
316
+ for path in path_types:
317
+ parts = safe_relative_parts(path)
318
+ for index in range(1, len(parts)):
319
+ ancestor = "/".join(parts[:index])
320
+ ancestor_type = path_types.get(ancestor)
321
+ if ancestor_type is None or ancestor_type == "dir":
322
+ continue
323
+ if ancestor_type == "symlink":
324
+ raise ValueError(f"{path}: path is nested under archived symlink {ancestor}")
325
+ raise ValueError(f"{path}: path is nested under archived file {ancestor}")
326
+
327
+
328
+ def validate_end_record(
329
+ record: dict[str, Any],
330
+ entries: int,
331
+ files: int,
332
+ dirs: int,
333
+ symlinks: int,
334
+ chunks: int,
335
+ bytes_count: int,
336
+ ) -> None:
337
+ expected_entries = record.get("entries")
338
+ expected_files = record.get("files")
339
+ if not isinstance(expected_entries, int):
340
+ raise ValueError("end record has invalid entries count")
341
+ if not isinstance(expected_files, int):
342
+ raise ValueError("end record has invalid files count")
343
+ if expected_entries != entries:
344
+ raise ValueError(f"entry count mismatch: expected {expected_entries}, got {entries}")
345
+ if expected_files != files:
346
+ raise ValueError(f"file count mismatch: expected {expected_files}, got {files}")
347
+
348
+ optional_counts = {
349
+ "dirs": dirs,
350
+ "symlinks": symlinks,
351
+ "chunks": chunks,
352
+ "bytes": bytes_count,
353
+ }
354
+ for key, actual in optional_counts.items():
355
+ expected = record.get(key)
356
+ if expected is not None and expected != actual:
357
+ raise ValueError(f"{key} count mismatch: expected {expected}, got {actual}")
358
+
359
+
360
+ def process_archive(
361
+ archive_path: Path,
362
+ *,
363
+ write_root: Path | None = None,
364
+ no_symlinks: bool = False,
365
+ collect_records: bool = False,
366
+ ) -> ArchiveManifest:
367
+ records_iter = read_json_lines(archive_path)
368
+ try:
369
+ first_line, header = next(records_iter)
370
+ except StopIteration as exc:
371
+ raise ValueError("archive is empty") from exc
372
+
373
+ version = validate_header(first_line, header)
374
+
375
+ records: list[ArchiveRecord] = []
376
+ seen_paths: set[str] = set()
377
+ path_types: dict[str, str] = {}
378
+ entries = 0
379
+ files = 0
380
+ dirs = 0
381
+ symlinks = 0
382
+ chunks = 0
383
+ bytes_count = 0
384
+ saw_end = False
385
+ active_file: ActiveFile | None = None
386
+ dir_modes: list[tuple[Path, int]] = []
387
+
388
+ try:
389
+ for line_number, record in records_iter:
390
+ if saw_end:
391
+ raise ValueError(f"line {line_number}: archive has data after end record")
392
+
393
+ record_type = record.get("type")
394
+ try:
395
+ if record_type in {"dir", "file", "symlink"}:
396
+ if active_file is not None:
397
+ raise ValueError(f"{active_file.path}: incomplete chunk stream")
398
+ path = record_path(record)
399
+ if path in seen_paths:
400
+ raise ValueError(f"{path}: duplicate archive path")
401
+ seen_paths.add(path)
402
+ path_types[path] = str(record_type)
403
+
404
+ if record_type == "dir":
405
+ process_dir_record(record, write_root, dir_modes)
406
+ dirs += 1
407
+ elif record_type == "file":
408
+ if version == 1:
409
+ bytes_count += process_file_v1(record, write_root)
410
+ else:
411
+ active_file = start_active_file(record, write_root)
412
+ bytes_count += int(record["size"])
413
+ files += 1
414
+ else:
415
+ process_symlink_record(record, write_root, no_symlinks)
416
+ symlinks += 1
417
+
418
+ if collect_records:
419
+ records.append((line_number, logical_record(record)))
420
+ entries += 1
421
+ elif record_type == "chunk":
422
+ if version != 2:
423
+ raise ValueError("chunk records require archive version 2")
424
+ active_file = process_chunk_record(record, active_file)
425
+ chunks += 1
426
+ elif record_type == "end":
427
+ if active_file is not None:
428
+ raise ValueError(f"{active_file.path}: incomplete chunk stream")
429
+ validate_end_record(record, entries, files, dirs, symlinks, chunks, bytes_count)
430
+ saw_end = True
431
+ else:
432
+ raise ValueError(f"unknown record type {record_type!r}")
433
+ except KeyError as exc:
434
+ raise ValueError(f"line {line_number}: missing required key {exc}") from exc
435
+ except Exception as exc:
436
+ raise type(exc)(f"line {line_number}: {exc}") from exc
437
+
438
+ if not saw_end:
439
+ raise ValueError("archive is missing end record")
440
+
441
+ validate_path_ancestry(path_types)
442
+ finally:
443
+ if active_file is not None and active_file.handle is not None:
444
+ active_file.handle.close()
445
+
446
+ if write_root is not None:
447
+ for path, mode in sorted(dir_modes, key=lambda item: len(item[0].parts), reverse=True):
448
+ os.chmod(path, mode)
449
+
450
+ return ArchiveManifest(
451
+ header=header,
452
+ version=version,
453
+ records=records,
454
+ entries=entries,
455
+ files=files,
456
+ dirs=dirs,
457
+ symlinks=symlinks,
458
+ chunks=chunks,
459
+ bytes=bytes_count,
460
+ )
461
+
462
+
463
+ def load_and_validate_archive(archive_path: Path) -> ArchiveManifest:
464
+ return process_archive(archive_path, collect_records=True)
465
+
466
+
467
+ def ensure_output_replaceable(output_dir: Path, overwrite: bool) -> None:
468
+ if not path_exists(output_dir):
469
+ return
470
+ if output_dir.is_dir() and not output_dir.is_symlink():
471
+ is_non_empty = any(output_dir.iterdir())
472
+ if is_non_empty and not overwrite:
473
+ raise FileExistsError(
474
+ f"output directory is not empty; use --overwrite: {output_dir}"
475
+ )
476
+ return
477
+ if not overwrite:
478
+ raise FileExistsError(f"output path exists; use --overwrite: {output_dir}")
479
+
480
+
481
+ def unique_temp_path(parent: Path, prefix: str) -> Path:
482
+ temp_path = Path(tempfile.mkdtemp(prefix=prefix, dir=parent))
483
+ temp_path.rmdir()
484
+ return temp_path
485
+
486
+
487
+ def replace_output_with_staging(staging_dir: Path, output_dir: Path, overwrite: bool) -> None:
488
+ ensure_output_replaceable(output_dir, overwrite)
489
+
490
+ backup_dir: Path | None = None
491
+ if path_exists(output_dir):
492
+ backup_dir = unique_temp_path(output_dir.parent, f".{output_dir.name}.backup-")
493
+ output_dir.rename(backup_dir)
494
+
495
+ try:
496
+ staging_dir.rename(output_dir)
497
+ except Exception:
498
+ if backup_dir is not None and path_exists(backup_dir) and not path_exists(output_dir):
499
+ backup_dir.rename(output_dir)
500
+ raise
501
+ else:
502
+ if backup_dir is not None and path_exists(backup_dir):
503
+ if backup_dir.is_dir() and not backup_dir.is_symlink():
504
+ shutil.rmtree(backup_dir)
505
+ else:
506
+ backup_dir.unlink()
507
+
508
+
509
+ def restore_archive(
510
+ archive_path: Path,
511
+ output_dir: Path,
512
+ overwrite: bool,
513
+ verify_only: bool,
514
+ no_symlinks: bool,
515
+ ) -> tuple[int, int]:
516
+ if verify_only:
517
+ manifest = process_archive(archive_path)
518
+ return manifest.entries, manifest.files
519
+
520
+ output_dir = absolute_path(output_dir)
521
+ if output_dir.parent == output_dir:
522
+ raise ValueError(f"refusing to restore directly to filesystem root: {output_dir}")
523
+
524
+ output_dir.parent.mkdir(parents=True, exist_ok=True)
525
+ ensure_output_replaceable(output_dir, overwrite)
526
+
527
+ staging_dir: Path | None = Path(
528
+ tempfile.mkdtemp(prefix=f".{output_dir.name}.restore-", dir=output_dir.parent)
529
+ )
530
+ try:
531
+ manifest = process_archive(
532
+ archive_path,
533
+ write_root=staging_dir,
534
+ no_symlinks=no_symlinks,
535
+ )
536
+ replace_output_with_staging(staging_dir, output_dir, overwrite)
537
+ staging_dir = None
538
+ finally:
539
+ if staging_dir is not None and path_exists(staging_dir):
540
+ shutil.rmtree(staging_dir, ignore_errors=True)
541
+
542
+ return manifest.entries, manifest.files
543
+
544
+
545
+ def main() -> int:
546
+ args = parse_args()
547
+ archive_path = Path(args.archive).expanduser().resolve()
548
+ output_dir = absolute_path(Path(args.output_dir))
549
+
550
+ try:
551
+ entries, files = restore_archive(
552
+ archive_path=archive_path,
553
+ output_dir=output_dir,
554
+ overwrite=args.overwrite,
555
+ verify_only=args.verify_only,
556
+ no_symlinks=args.no_symlinks,
557
+ )
558
+ except (OSError, ValueError, FileExistsError) as exc:
559
+ print(f"error: {exc}", file=sys.stderr)
560
+ return 1
561
+
562
+ action = "verified" if args.verify_only else "restored"
563
+ print(f"{action} {entries} entries ({files} files)")
564
+ return 0
565
+
566
+
567
+ if __name__ == "__main__":
568
+ raise SystemExit(main())
@@ -0,0 +1,41 @@
1
+ """Validate a flat archive without restoring it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .archive import detect_archive_compression
10
+ from .unpack import load_and_validate_archive
11
+
12
+
13
+ def parse_args() -> argparse.Namespace:
14
+ parser = argparse.ArgumentParser(description="Validate a flat-pack archive.")
15
+ parser.add_argument("archive", help="Archive to validate.")
16
+ return parser.parse_args()
17
+
18
+
19
+ def main() -> int:
20
+ args = parse_args()
21
+ archive_path = Path(args.archive).expanduser().resolve()
22
+
23
+ try:
24
+ manifest = load_and_validate_archive(archive_path)
25
+ except (OSError, ValueError) as exc:
26
+ print(f"error: {exc}", file=sys.stderr)
27
+ return 1
28
+
29
+ compression = detect_archive_compression(archive_path)
30
+ print(
31
+ "verified "
32
+ f"{manifest.entries} entries "
33
+ f"({manifest.files} files, {manifest.dirs} dirs, "
34
+ f"{manifest.symlinks} symlinks, {manifest.chunks} chunks, "
35
+ f"{manifest.bytes} bytes, version {manifest.version}, {compression})"
36
+ )
37
+ return 0
38
+
39
+
40
+ if __name__ == "__main__":
41
+ raise SystemExit(main())