112 lines
4.7 KiB
Python
Executable File
112 lines
4.7 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""dirwatch - snapshot a directory tree (names+sizes+hashes) and later diff it to show exactly what changed.
|
|
Usage: dirwatch snapshot <dir> [-o snap.json] | dirwatch diff <dir> [-s snap.json] | dirwatch --selftest | --help
|
|
Snapshot records path, size, mtime and SHA-256 (first 64 KiB only for speed;
|
|
full hash on demand with --full). Diff reports ADDED / REMOVED / MODIFIED /
|
|
SIZE-CHANGED lines, so a later run shows exactly what changed — the
|
|
"what happened to this folder since Tuesday" answer in one command.
|
|
"""
|
|
import argparse, hashlib, json, os, sys, tempfile
|
|
from pathlib import Path
|
|
|
|
def file_hash(p, full=False):
|
|
h = hashlib.sha256()
|
|
try:
|
|
with open(p, "rb") as f:
|
|
if full:
|
|
while True:
|
|
b = f.read(1 << 20)
|
|
if not b:
|
|
break
|
|
h.update(b)
|
|
else:
|
|
h.update(f.read(65536))
|
|
except OSError:
|
|
return None
|
|
return h.hexdigest()
|
|
|
|
def snap_tree(root, full=False):
|
|
snap = {"root": str(Path(root).resolve()), "files": {}}
|
|
for p in sorted(Path(root).rglob("*")):
|
|
if p.is_file() and not p.is_symlink():
|
|
try:
|
|
st = p.stat()
|
|
except OSError:
|
|
continue
|
|
snap["files"][str(p.relative_to(root))] = {
|
|
"size": st.st_size, "mtime": st.st_mtime,
|
|
"hash": file_hash(p, full)}
|
|
return snap
|
|
|
|
def selftest():
|
|
with tempfile.TemporaryDirectory() as td:
|
|
base = Path(td)
|
|
(base / "a.txt").write_text("one")
|
|
(base / "b.txt").write_text("two")
|
|
s1 = snap_tree(base)
|
|
(base / "a.txt").write_text("one-CHANGED")
|
|
(base / "b.txt").unlink()
|
|
(base / "c.txt").write_text("three")
|
|
s2 = snap_tree(base)
|
|
added = set(s2["files"]) - set(s1["files"])
|
|
removed = set(s1["files"]) - set(s2["files"])
|
|
mod = {k for k in s1["files"] if k in s2["files"]
|
|
and s1["files"][k]["hash"] != s2["files"][k]["hash"]}
|
|
assert added == {"c.txt"} and removed == {"b.txt"} and mod == {"a.txt"}, (added, removed, mod)
|
|
print("selftest OK: diff detected 1 added, 1 removed, 1 modified")
|
|
return 0
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description="dirwatch - snapshot a tree, diff it later to see exactly what changed")
|
|
sub = ap.add_subparsers(dest="cmd")
|
|
sp = sub.add_parser("snapshot", help="take a snapshot")
|
|
sp.add_argument("dir"); sp.add_argument("-o", "--out", default=None)
|
|
sp.add_argument("--full", action="store_true", help="hash whole files, not just the first 64 KiB")
|
|
dp = sub.add_parser("diff", help="diff current tree against a snapshot")
|
|
dp.add_argument("dir"); dp.add_argument("-s", "--snap", default=None)
|
|
dp.add_argument("--full", action="store_true")
|
|
ap.add_argument("--selftest", action="store_true")
|
|
a = ap.parse_args()
|
|
if a.selftest:
|
|
return selftest()
|
|
if a.cmd == "snapshot":
|
|
root = Path(a.dir)
|
|
if not root.is_dir():
|
|
print(f"dirwatch: {a.dir}: not a directory", file=sys.stderr); return 2
|
|
snap = snap_tree(root, a.full)
|
|
out = Path(a.out) if a.out else root / ".dirwatch.json"
|
|
with open(out, "w") as f:
|
|
json.dump(snap, f, indent=2)
|
|
print(f"snapshot saved to {out} ({len(snap['files'])} files)")
|
|
return 0
|
|
if a.cmd == "diff":
|
|
root = Path(a.dir)
|
|
snapfile = Path(a.snap) if a.snap else root / ".dirwatch.json"
|
|
if not snapfile.exists():
|
|
print(f"dirwatch: no snapshot at {snapfile}; run `dirwatch snapshot {a.dir}` first",
|
|
file=sys.stderr); return 2
|
|
with open(snapfile) as f:
|
|
old = json.load(f)
|
|
now = snap_tree(root, a.full)
|
|
o, n = old["files"], now["files"]
|
|
added = sorted(set(n) - set(o)); removed = sorted(set(o) - set(n))
|
|
modified, sizechg = [], []
|
|
for k in sorted(set(o) & set(n)):
|
|
if o[k]["hash"] != n[k]["hash"]:
|
|
modified.append(k)
|
|
elif o[k]["size"] != n[k]["size"]:
|
|
sizechg.append(k)
|
|
for k in added: print(f"ADDED {k} ({n[k]['size']} B)")
|
|
for k in removed: print(f"REMOVED {k} ({o[k]['size']} B)")
|
|
for k in modified: print(f"MODIFIED {k} ({o[k]['size']} -> {n[k]['size']} B)")
|
|
for k in sizechg: print(f"SIZE-CHANGED {k} ({o[k]['size']} -> {n[k]['size']} B)")
|
|
total = len(added) + len(removed) + len(modified) + len(sizechg)
|
|
print(f"{total} change(s): {len(added)} added, {len(removed)} removed, "
|
|
f"{len(modified)} modified, {len(sizechg)} size-changed")
|
|
return 0
|
|
ap.print_help()
|
|
return 2
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|