Providing complete CLI tool code
The provided code snippet implements a CLI that reorganizes files into a content-addressable storage by renaming them to their SHA-256 hash, handling duplicates by deleting sources when hashes match, and supporting recursive and cleanup options using pathlib.
Here's a small, self‑contained CLI that does what you described. It uses pathlib to walk a source directory, computes a SHA‑256 digest for each regular file, and either renames it to its hash in a target directory or deletes it if that hash already exists:
#!/usr/bin/env python3
import argparse
import hashlib
from pathlib import Path
def sha256sum(path: Path, chunk_size: int = 8192) -> str:
"""Compute the SHA‑256 hex digest of a file."""
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
h.update(chunk)
return h.hexdigest()
def organize(src: Path, dest: Path, recursive: bool = False, delete_empty: bool = False) -> None:
"""Rename files in `src` to their SHA‑256 hash into `dest`, deleting duplicates."""
dest.mkdir(parents=True, exist_ok=True)
# Choose how deep to walk
iterator = src.rglob("*") if recursive else src.glob("*")
for p in iterator:
if not p.is_file():
continue # skip directories and symlinks
digest = sha256sum(p)
target = dest / digest # you could append an extension if you want
if target.exists():
print(f"{p} is a duplicate of {target}, deleting source")
try:
p.unlink()
except Exception as e:
print(f"Failed to delete {p}: {e}")
else:
try:
p.rename(target)
print(f"Moved {p} -> {target}")
except Exception as e:
print(f"Failed to move {p}: {e}")
if delete_empty:
# Optionally clean up empty directories in the source
for d in sorted(src.rglob("*"), reverse=True):
if d.is_dir() and not any(d.iterdir()):
try:
d.rmdir()
except OSError:
pass
def main() -> None:
parser = argparse.ArgumentParser(description="Organize files into content‑addressable storage.")
parser.add_argument("src", type=Path, help="Source directory to organize")
parser.add_argument("dest", type=Path, help="Destination directory for hashed files")
parser.add_argument("-r", "--recursive", action="store_true",
help="Recurse into subdirectories of the source")
parser.add_argument("--delete-empty", action="store_true",
help="Remove empty directories from the source after moving files")
args = parser.parse_args()
organize(args.src.expanduser().resolve(),
args.dest.expanduser().resolve(),
recursive=args.recursive,
delete_empty=args.delete_empty)
if __name__ == "__main__":
main()
Save this as, for example, organize.py, make it executable (chmod +x organize.py), and run it like:
./organize.py /path/to/source /path/to/store --recursive --delete-empty
Files will be renamed to their SHA‑256 hex hash in the destination, and duplicates will be detected and removed from the source.