Files

89 lines
3.7 KiB
Python
Executable File

#!/usr/bin/env python3
"""flatpack - flatten a nested tree into one directory, resolving name clashes with suffixes.
Usage: flatpack <src> <dest> [--dry-run] [--move] [--selftest] [--help]
Copies (default) or moves (--move) every file under <src> into a single flat
<dest> directory. When two files share a name, the later one gets
`name_2.ext`, `name_3.ext`, ... and a collision report is printed, so nothing
is ever silently overwritten. Directory structure is deliberately discarded;
a manifest of source -> destination is written to <dest>/.flatpack-manifest.txt.
"""
import argparse, os, shutil, sys, tempfile
from pathlib import Path
def plan(src, dest):
files = sorted(p for p in src.rglob("*") if p.is_file())
used = {}
mapping = []
for p in files:
name = p.name
if name in used:
used[name] += 1
stem, dot, ext = name.rpartition(".")
cand = f"{stem}_{used[name]}{dot}{ext}" if dot else f"{name}_{used[name]}"
while cand in used:
used[name] += 1
cand = f"{stem}_{used[name]}{dot}{ext}" if dot else f"{name}_{used[name]}"
name = cand
else:
used[name] = 1
mapping.append((p, dest / name))
return mapping
def selftest():
with tempfile.TemporaryDirectory() as td:
base = Path(td)
src = base / "src"; dest = base / "flat"
(src / "a").mkdir(parents=True); (src / "b").mkdir(parents=True)
(src / "a" / "same.txt").write_text("A")
(src / "b" / "same.txt").write_text("B")
(src / "a" / "unique.txt").write_text("U")
m = plan(src, dest)
names = sorted(str(d.name) for _, d in m)
assert names == ["same.txt", "same_2.txt", "unique.txt"], names
import subprocess
r = subprocess.run([sys.executable, __file__, str(src), str(dest), "--move"],
capture_output=True, text=True)
assert r.returncode == 0, r.stderr
assert (dest / "same.txt").read_text() in ("A", "B")
assert (dest / "same_2.txt").exists() and (dest / "unique.txt").exists()
assert not list(src.rglob("*.txt"))
print("selftest OK: 3 files flattened, name clash resolved with _2 suffix")
return 0
def main():
ap = argparse.ArgumentParser(description="flatpack - flatten a nested tree into one directory")
ap.add_argument("src", nargs="?")
ap.add_argument("dest", nargs="?")
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--move", action="store_true", help="move instead of copy")
ap.add_argument("--selftest", action="store_true")
a = ap.parse_args()
if a.selftest:
return selftest()
if not a.src or not a.dest:
ap.error("src and dest are required")
src, dest = Path(a.src), Path(a.dest)
if not src.is_dir():
print(f"flatpack: {a.src}: not a directory", file=sys.stderr); return 2
mapping = plan(src, dest)
clashes = sum(1 for s, d in mapping if s.name != d.name)
for s, d in mapping:
mark = " (clash -> renamed)" if s.name != d.name else ""
print(f"{s} -> {d}{mark}")
if a.dry_run:
print(f"dry-run: {len(mapping)} file(s), {clashes} clash(es), nothing changed"); return 0
dest.mkdir(parents=True, exist_ok=True)
for s, d in mapping:
if a.move:
shutil.move(str(s), str(d))
else:
shutil.copy2(str(s), str(d))
with open(dest / ".flatpack-manifest.txt", "w") as f:
for s, d in mapping:
f.write(f"{s} -> {d}\n")
print(f"{'moved' if a.move else 'copied'} {len(mapping)} file(s) into {dest} ({clashes} clash(es) renamed)")
return 0
if __name__ == "__main__":
sys.exit(main())