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.
flat_packager/pack.py ADDED
@@ -0,0 +1,495 @@
1
+ """Pack a repository tree into one flat text archive."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import base64
7
+ import fnmatch
8
+ import hashlib
9
+ import os
10
+ import shutil
11
+ import stat
12
+ import subprocess
13
+ import sys
14
+ import tempfile
15
+ from datetime import datetime, timezone
16
+ from pathlib import Path
17
+ from typing import Iterable, Iterator
18
+
19
+ from .archive import (
20
+ ARCHIVE_KIND,
21
+ ARCHIVE_VERSION,
22
+ DEFAULT_CHUNK_SIZE,
23
+ emit_json_line,
24
+ open_archive_for_write,
25
+ )
26
+
27
+
28
+ def parse_args() -> argparse.Namespace:
29
+ parser = argparse.ArgumentParser(
30
+ description="Flatten a GitHub/local repository into one text archive."
31
+ )
32
+ parser.add_argument(
33
+ "source",
34
+ help=(
35
+ "Repository source. Use a local path, a git URL, or owner/repo "
36
+ "shorthand for public GitHub repos."
37
+ ),
38
+ )
39
+ parser.add_argument("output", help="Path to write the flat text archive.")
40
+ parser.add_argument(
41
+ "--tracked-only",
42
+ action="store_true",
43
+ help="For local git checkouts, include only files tracked by git.",
44
+ )
45
+ parser.add_argument(
46
+ "--include-git",
47
+ action="store_true",
48
+ help="Include the .git directory when walking a local directory.",
49
+ )
50
+ parser.add_argument(
51
+ "--exclude",
52
+ action="append",
53
+ default=[],
54
+ metavar="GLOB",
55
+ help="Exclude paths matching this glob. Can be supplied multiple times.",
56
+ )
57
+ parser.add_argument(
58
+ "--max-file-bytes",
59
+ type=int,
60
+ default=None,
61
+ help="Fail if any single file is larger than this many bytes.",
62
+ )
63
+ parser.add_argument(
64
+ "--keep-clone",
65
+ action="store_true",
66
+ help="Keep the temporary clone directory when source is a git URL.",
67
+ )
68
+ parser.add_argument(
69
+ "--branch",
70
+ help="Branch or tag to clone when source is a remote git repository.",
71
+ )
72
+ parser.add_argument(
73
+ "--recurse-submodules",
74
+ action="store_true",
75
+ help="Clone submodules when source is a remote git repository.",
76
+ )
77
+ parser.add_argument(
78
+ "--no-shallow",
79
+ action="store_true",
80
+ help="Do a full clone instead of the default depth-1 clone for remote repositories.",
81
+ )
82
+ parser.add_argument(
83
+ "--format-version",
84
+ choices=("1", "2"),
85
+ default=str(ARCHIVE_VERSION),
86
+ help="Archive format version to write. Version 2 uses chunked file records.",
87
+ )
88
+ parser.add_argument(
89
+ "--chunk-size",
90
+ type=int,
91
+ default=DEFAULT_CHUNK_SIZE,
92
+ help="Chunk size in bytes for format version 2.",
93
+ )
94
+ parser.add_argument(
95
+ "--compress",
96
+ choices=("auto", "none", "gzip"),
97
+ default="auto",
98
+ help="Compress archive output. 'auto' uses gzip for .gz output paths.",
99
+ )
100
+ return parser.parse_args()
101
+
102
+
103
+ def looks_like_git_source(source: str) -> bool:
104
+ if source.startswith(("http://", "https://", "ssh://", "git@")):
105
+ return True
106
+ if source.endswith(".git"):
107
+ return True
108
+ if "/" in source and not Path(source).exists():
109
+ owner_repo = source.split("/")
110
+ return len(owner_repo) == 2 and all(owner_repo)
111
+ return False
112
+
113
+
114
+ def normalize_source(source: str) -> str:
115
+ if "/" in source and not Path(source).exists() and not source.startswith(
116
+ ("http://", "https://", "ssh://", "git@")
117
+ ):
118
+ owner, repo = source.split("/", 1)
119
+ return f"https://github.com/{owner}/{repo}.git"
120
+ return source
121
+
122
+
123
+ def prepare_source(
124
+ source: str,
125
+ branch: str | None = None,
126
+ recurse_submodules: bool = False,
127
+ shallow: bool = True,
128
+ ) -> tuple[Path, str | None]:
129
+ path = Path(source).expanduser()
130
+ if path.exists():
131
+ if branch is not None:
132
+ raise SystemExit("--branch can only be used with remote git repositories")
133
+ return path.resolve(), None
134
+
135
+ if not looks_like_git_source(source):
136
+ raise SystemExit(f"source does not exist and does not look like a git repo: {source}")
137
+
138
+ clone_url = normalize_source(source)
139
+ temp_dir = tempfile.mkdtemp(prefix="repo-flat-clone-")
140
+ clone_path = Path(temp_dir) / "repo"
141
+ command = ["git", "clone"]
142
+ if shallow:
143
+ command.extend(["--depth", "1"])
144
+ if branch is not None:
145
+ command.extend(["--branch", branch])
146
+ if recurse_submodules:
147
+ command.append("--recurse-submodules")
148
+ command.extend([clone_url, str(clone_path)])
149
+ try:
150
+ subprocess.run(command, check=True)
151
+ except FileNotFoundError as exc:
152
+ shutil.rmtree(temp_dir, ignore_errors=True)
153
+ raise SystemExit("git is required to clone remote repositories") from exc
154
+ except subprocess.CalledProcessError as exc:
155
+ shutil.rmtree(temp_dir, ignore_errors=True)
156
+ raise SystemExit(f"git clone failed with exit code {exc.returncode}") from exc
157
+ return clone_path.resolve(), temp_dir
158
+
159
+
160
+ def is_excluded(path: str, patterns: Iterable[str]) -> bool:
161
+ return any(fnmatch.fnmatch(path, pattern) for pattern in patterns)
162
+
163
+
164
+ def safe_relative_path(root: Path, path: Path) -> str:
165
+ rel = path.relative_to(root).as_posix()
166
+ if rel == "." or rel.startswith("../") or rel.startswith("/"):
167
+ raise ValueError(f"unsafe path discovered: {path}")
168
+ return rel
169
+
170
+
171
+ def tracked_paths(root: Path, exclude_patterns: list[str]) -> Iterator[Path]:
172
+ try:
173
+ result = subprocess.run(
174
+ ["git", "-C", str(root), "ls-files", "-z"],
175
+ check=True,
176
+ stdout=subprocess.PIPE,
177
+ stderr=subprocess.PIPE,
178
+ )
179
+ except FileNotFoundError as exc:
180
+ raise SystemExit("git is required for --tracked-only") from exc
181
+ except subprocess.CalledProcessError as exc:
182
+ message = exc.stderr.decode("utf-8", errors="replace").strip()
183
+ raise SystemExit(f"git ls-files failed: {message}") from exc
184
+
185
+ for raw in result.stdout.split(b"\0"):
186
+ if not raw:
187
+ continue
188
+ rel = raw.decode("utf-8", errors="surrogateescape")
189
+ if is_excluded(rel, exclude_patterns):
190
+ continue
191
+ yield root / rel
192
+
193
+
194
+ def walked_paths(
195
+ root: Path,
196
+ output_path: Path,
197
+ include_git: bool,
198
+ exclude_patterns: list[str],
199
+ ) -> Iterator[Path]:
200
+ for current_root, dir_names, file_names in os.walk(root, topdown=True):
201
+ current = Path(current_root)
202
+ rel_current = "" if current == root else safe_relative_path(root, current)
203
+
204
+ kept_dirs = []
205
+ symlink_dirs = []
206
+ for name in sorted(dir_names):
207
+ path = current / name
208
+ rel = f"{rel_current}/{name}" if rel_current else name
209
+ if not include_git and rel == ".git":
210
+ continue
211
+ if is_excluded(rel, exclude_patterns):
212
+ continue
213
+ if path.is_symlink():
214
+ symlink_dirs.append(path)
215
+ continue
216
+ kept_dirs.append(name)
217
+ dir_names[:] = kept_dirs
218
+
219
+ if current != root:
220
+ yield current
221
+
222
+ yield from symlink_dirs
223
+
224
+ for name in sorted(file_names):
225
+ path = current / name
226
+ rel = safe_relative_path(root, path)
227
+ if path.resolve() == output_path:
228
+ continue
229
+ if is_excluded(rel, exclude_patterns):
230
+ continue
231
+ yield path
232
+
233
+
234
+ def parent_dirs_for_tracked_files(root: Path, files: Iterable[Path]) -> list[Path]:
235
+ seen: set[Path] = set()
236
+ ordered: list[Path] = []
237
+ for file_path in files:
238
+ for parent in reversed(file_path.relative_to(root).parents):
239
+ if parent == Path("."):
240
+ continue
241
+ full_parent = root / parent
242
+ if full_parent not in seen:
243
+ seen.add(full_parent)
244
+ ordered.append(full_parent)
245
+ return ordered
246
+
247
+
248
+ def symlink_record(root: Path, path: Path) -> dict[str, object]:
249
+ rel = safe_relative_path(root, path)
250
+ metadata = path.lstat()
251
+ mode = stat.S_IMODE(metadata.st_mode)
252
+
253
+ return {
254
+ "type": "symlink",
255
+ "path": rel,
256
+ "mode": mode,
257
+ "target": os.readlink(path),
258
+ }
259
+
260
+
261
+ def validate_regular_file(path: Path, rel: str, max_file_bytes: int | None) -> os.stat_result:
262
+ metadata = path.lstat()
263
+ if stat.S_ISLNK(metadata.st_mode):
264
+ raise ValueError(f"expected regular file, got symlink: {rel}")
265
+
266
+ if not stat.S_ISREG(metadata.st_mode):
267
+ raise ValueError(f"unsupported filesystem entry: {rel}")
268
+
269
+ size = metadata.st_size
270
+ if max_file_bytes is not None and size > max_file_bytes:
271
+ raise ValueError(f"{rel} is {size} bytes, above --max-file-bytes")
272
+
273
+ return metadata
274
+
275
+
276
+ def file_record_v1(root: Path, path: Path, max_file_bytes: int | None) -> dict[str, object]:
277
+ rel = safe_relative_path(root, path)
278
+ metadata = validate_regular_file(path, rel, max_file_bytes)
279
+ mode = stat.S_IMODE(metadata.st_mode)
280
+ size = metadata.st_size
281
+ content = path.read_bytes()
282
+ return {
283
+ "type": "file",
284
+ "path": rel,
285
+ "mode": mode,
286
+ "size": size,
287
+ "sha256": hashlib.sha256(content).hexdigest(),
288
+ "encoding": "base64",
289
+ "content": base64.b64encode(content).decode("ascii"),
290
+ }
291
+
292
+
293
+ def hash_file(path: Path, chunk_size: int) -> str:
294
+ digest = hashlib.sha256()
295
+ with path.open("rb") as handle:
296
+ for chunk in iter(lambda: handle.read(chunk_size), b""):
297
+ digest.update(chunk)
298
+ return digest.hexdigest()
299
+
300
+
301
+ def emit_file_records_v2(
302
+ handle,
303
+ root: Path,
304
+ path: Path,
305
+ max_file_bytes: int | None,
306
+ chunk_size: int,
307
+ ) -> int:
308
+ rel = safe_relative_path(root, path)
309
+ metadata = validate_regular_file(path, rel, max_file_bytes)
310
+ mode = stat.S_IMODE(metadata.st_mode)
311
+ size = metadata.st_size
312
+ chunks = 0 if size == 0 else (size + chunk_size - 1) // chunk_size
313
+ digest = hash_file(path, chunk_size)
314
+
315
+ emit_json_line(
316
+ handle,
317
+ {
318
+ "type": "file",
319
+ "path": rel,
320
+ "mode": mode,
321
+ "size": size,
322
+ "sha256": digest,
323
+ "encoding": "base64-chunks",
324
+ "chunks": chunks,
325
+ },
326
+ )
327
+
328
+ chunk_count = 0
329
+ with path.open("rb") as file_handle:
330
+ while True:
331
+ chunk = file_handle.read(chunk_size)
332
+ if not chunk:
333
+ break
334
+ emit_json_line(
335
+ handle,
336
+ {
337
+ "type": "chunk",
338
+ "path": rel,
339
+ "index": chunk_count,
340
+ "size": len(chunk),
341
+ "sha256": hashlib.sha256(chunk).hexdigest(),
342
+ "content": base64.b64encode(chunk).decode("ascii"),
343
+ },
344
+ )
345
+ chunk_count += 1
346
+
347
+ return chunk_count
348
+
349
+
350
+ def dir_record(root: Path, path: Path) -> dict[str, object]:
351
+ metadata = path.lstat()
352
+ return {
353
+ "type": "dir",
354
+ "path": safe_relative_path(root, path),
355
+ "mode": stat.S_IMODE(metadata.st_mode),
356
+ }
357
+
358
+
359
+ def build_archive(
360
+ root: Path,
361
+ output_path: Path,
362
+ source_label: str,
363
+ tracked_only: bool,
364
+ include_git: bool,
365
+ exclude_patterns: list[str],
366
+ max_file_bytes: int | None,
367
+ format_version: int = ARCHIVE_VERSION,
368
+ chunk_size: int = DEFAULT_CHUNK_SIZE,
369
+ compression: str = "auto",
370
+ ) -> tuple[int, int]:
371
+ if format_version not in (1, 2):
372
+ raise ValueError(f"unsupported archive format version: {format_version}")
373
+ if chunk_size <= 0:
374
+ raise ValueError("--chunk-size must be greater than zero")
375
+
376
+ output_path.parent.mkdir(parents=True, exist_ok=True)
377
+
378
+ header = {
379
+ "type": ARCHIVE_KIND,
380
+ "version": format_version,
381
+ "created_at": datetime.now(timezone.utc).isoformat(),
382
+ "source": source_label,
383
+ "root_name": root.name,
384
+ "tracked_only": tracked_only,
385
+ "format": "chunked-jsonl" if format_version == 2 else "inline-jsonl",
386
+ }
387
+ if format_version == 2:
388
+ header["chunk_size"] = chunk_size
389
+
390
+ entry_count = 0
391
+ file_count = 0
392
+ dir_count = 0
393
+ symlink_count = 0
394
+ chunk_count = 0
395
+ byte_count = 0
396
+
397
+ with open_archive_for_write(output_path, compression=compression) as handle:
398
+ emit_json_line(handle, header)
399
+
400
+ if tracked_only:
401
+ files = sorted(tracked_paths(root, exclude_patterns), key=lambda p: p.as_posix())
402
+ for directory in parent_dirs_for_tracked_files(root, files):
403
+ emit_json_line(handle, dir_record(root, directory))
404
+ entry_count += 1
405
+ dir_count += 1
406
+ paths: Iterable[Path] = files
407
+ else:
408
+ paths = walked_paths(root, output_path.resolve(), include_git, exclude_patterns)
409
+
410
+ for path in paths:
411
+ if path.is_dir() and not path.is_symlink():
412
+ record = dir_record(root, path)
413
+ dir_count += 1
414
+ emit_json_line(handle, record)
415
+ elif path.is_symlink():
416
+ record = symlink_record(root, path)
417
+ symlink_count += 1
418
+ emit_json_line(handle, record)
419
+ else:
420
+ if format_version == 1:
421
+ record = file_record_v1(root, path, max_file_bytes)
422
+ byte_count += int(record["size"])
423
+ emit_json_line(handle, record)
424
+ else:
425
+ rel = safe_relative_path(root, path)
426
+ metadata = validate_regular_file(path, rel, max_file_bytes)
427
+ byte_count += metadata.st_size
428
+ chunk_count += emit_file_records_v2(
429
+ handle,
430
+ root,
431
+ path,
432
+ max_file_bytes,
433
+ chunk_size,
434
+ )
435
+ file_count += 1
436
+ entry_count += 1
437
+
438
+ emit_json_line(
439
+ handle,
440
+ {
441
+ "type": "end",
442
+ "entries": entry_count,
443
+ "files": file_count,
444
+ "dirs": dir_count,
445
+ "symlinks": symlink_count,
446
+ "chunks": chunk_count,
447
+ "bytes": byte_count,
448
+ },
449
+ )
450
+
451
+ return entry_count, file_count
452
+
453
+
454
+ def main() -> int:
455
+ args = parse_args()
456
+ temp_dir: str | None = None
457
+ try:
458
+ root, temp_dir = prepare_source(
459
+ args.source,
460
+ branch=args.branch,
461
+ recurse_submodules=args.recurse_submodules,
462
+ shallow=not args.no_shallow,
463
+ )
464
+ if not root.is_dir():
465
+ raise SystemExit(f"source is not a directory: {root}")
466
+
467
+ output_path = Path(args.output).expanduser().resolve()
468
+ entries, files = build_archive(
469
+ root=root,
470
+ output_path=output_path,
471
+ source_label=args.source,
472
+ tracked_only=args.tracked_only,
473
+ include_git=args.include_git,
474
+ exclude_patterns=args.exclude,
475
+ max_file_bytes=args.max_file_bytes,
476
+ format_version=int(args.format_version),
477
+ chunk_size=args.chunk_size,
478
+ compression=args.compress,
479
+ )
480
+ except (OSError, ValueError) as exc:
481
+ print(f"error: {exc}", file=sys.stderr)
482
+ return 1
483
+ finally:
484
+ if temp_dir is not None:
485
+ if args.keep_clone:
486
+ print(f"kept clone at {temp_dir}", file=sys.stderr)
487
+ else:
488
+ shutil.rmtree(temp_dir, ignore_errors=True)
489
+
490
+ print(f"wrote {output_path} ({entries} entries, {files} files)")
491
+ return 0
492
+
493
+
494
+ if __name__ == "__main__":
495
+ raise SystemExit(main())