Files

166 lines
6.4 KiB
Python
Executable File

#!/usr/bin/env python3
"""snapdiff - compare two disk-usage snapshots and show what grew.
Usage: snapdiff snapshot DIR -o FILE
snapdiff diff OLD.snap NEW.snap [--min-delta SIZE]
snapdiff --selftest
A snapshot records path, size and mtime for every file in a tree; diffing
two of them shows what grew, shrank, appeared, or vanished."""
import argparse, os, sys
def human(n):
sign = "-" if n < 0 else ""
n = abs(n)
for u in ("B", "K", "M", "G", "T"):
if n < 1024 or u == "T":
return f"{sign}{n:.1f}{u}" if u != "B" else f"{sign}{int(n)}B"
n /= 1024.0
return f"{sign}{n:.1f}T"
def parse_size(s):
m = {"K": 1024, "M": 1024**2, "G": 1024**3}
if s and s[-1].upper() in m:
return int(float(s[:-1]) * m[s[-1].upper()])
return int(s)
def take_snapshot(root):
snap = {}
for cur, _dirs, files in os.walk(root):
for name in files:
p = os.path.join(cur, name)
try:
st = os.lstat(p)
except OSError:
continue
snap[os.path.relpath(p, root)] = (st.st_size, int(st.st_mtime))
return snap
def write_snapshot(snap, path):
with open(path, "w") as f:
for rel in sorted(snap):
sz, mt = snap[rel]
f.write(f"{sz}\t{mt}\t{rel}\n")
def read_snapshot(path):
snap = {}
with open(path) as f:
for line in f:
parts = line.rstrip("\n").split("\t", 2)
if len(parts) == 3:
try:
snap[parts[2]] = (int(parts[0]), int(parts[1]))
except ValueError:
continue
return snap
def diff_snaps(old, new, min_delta=0):
grown, shrunk, added, deleted = [], [], [], []
for rel, (sz, _mt) in new.items():
if rel not in old:
added.append((rel, sz))
elif sz != old[rel][0]:
d = sz - old[rel][0]
if d > 0:
grown.append((rel, old[rel][0], sz, d))
else:
shrunk.append((rel, old[rel][0], sz, d))
for rel, (sz, _mt) in old.items():
if rel not in new:
deleted.append((rel, sz))
grown = [g for g in grown if abs(g[3]) >= min_delta]
shrunk = [s for s in shrunk if abs(s[3]) >= min_delta]
grown.sort(key=lambda g: -g[3])
shrunk.sort(key=lambda s: s[3])
return grown, shrunk, added, deleted
def selftest():
import tempfile, time
tmp = tempfile.mkdtemp(prefix="snapdiff-test-")
with open(os.path.join(tmp, "grow.txt"), "wb") as f:
f.write(b"a" * 100)
with open(os.path.join(tmp, "gone.txt"), "w") as f:
f.write("bye")
with open(os.path.join(tmp, "same.txt"), "w") as f:
f.write("same")
s1 = take_snapshot(tmp)
time.sleep(0.05)
with open(os.path.join(tmp, "grow.txt"), "wb") as f:
f.write(b"a" * 500)
os.unlink(os.path.join(tmp, "gone.txt"))
with open(os.path.join(tmp, "new.txt"), "w") as f:
f.write("hello")
s2 = take_snapshot(tmp)
grown, shrunk, added, deleted = diff_snaps(s1, s2)
ok = True
if not any(g[0] == "grow.txt" and g[3] == 400 for g in grown):
print(f"FAIL: grow.txt +400 not detected: {grown}"); ok = False
if not any(a[0] == "new.txt" for a in added):
print("FAIL: new.txt not detected as added"); ok = False
if not any(d[0] == "gone.txt" for d in deleted):
print("FAIL: gone.txt not detected as deleted"); ok = False
if any(g[0] == "same.txt" for g in grown) or any(a[0] == "same.txt" for a in added):
print("FAIL: unchanged file reported"); ok = False
# round-trip through the file format
p1, p2 = os.path.join(tmp, "a.snap"), os.path.join(tmp, "b.snap")
write_snapshot(s1, p1)
write_snapshot(s2, p2)
if read_snapshot(p1) != s1 or read_snapshot(p2) != s2:
print("FAIL: snapshot file round-trip mismatch"); ok = False
import shutil; shutil.rmtree(tmp, ignore_errors=True)
if ok:
print("selftest: PASS (grew +400B, added, deleted, unchanged ignored, round-trip ok)")
return 0 if ok else 1
def main():
ap = argparse.ArgumentParser(prog="snapdiff",
description="Compare two disk-usage snapshots and show what grew.")
ap.add_argument("--selftest", action="store_true", help="run built-in checks in a temp dir")
sub = ap.add_subparsers(dest="cmd")
sp = sub.add_parser("snapshot", help="record a snapshot of a tree")
sp.add_argument("dir", help="tree to snapshot")
sp.add_argument("-o", "--output", required=True, help="snapshot file to write")
dp = sub.add_parser("diff", help="compare two snapshots")
dp.add_argument("old", help="older snapshot file")
dp.add_argument("new", help="newer snapshot file")
dp.add_argument("--min-delta", default="0", help="ignore changes smaller than SIZE (e.g. 1K)")
a = ap.parse_args()
if a.selftest:
return selftest()
if a.cmd == "snapshot":
snap = take_snapshot(a.dir)
write_snapshot(snap, a.output)
print(f"snapshot of {a.dir}: {len(snap)} files -> {a.output}")
return 0
if a.cmd == "diff":
old = read_snapshot(a.old)
new = read_snapshot(a.new)
grown, shrunk, added, deleted = diff_snaps(old, new, parse_size(a.min_delta))
old_total = sum(sz for sz, _ in old.values())
new_total = sum(sz for sz, _ in new.values())
print(f"{a.old}: {len(old)} files, {human(old_total)}")
print(f"{a.new}: {len(new)} files, {human(new_total)}")
print(f"net change: {human(new_total - old_total)}")
if grown:
print("\ngrew the most:")
for rel, o, n, d in grown[:15]:
print(f" +{human(d):>9} {human(o)} -> {human(n)} {rel}")
if shrunk:
print("\nshrank:")
for rel, o, n, d in shrunk[:10]:
print(f" {human(d):>10} {human(o)} -> {human(n)} {rel}")
if added:
print(f"\nnew files ({len(added)}, {human(sum(s for _, s in added))}):")
for rel, sz in sorted(added)[:15]:
print(f" +{human(sz):>9} {rel}")
if deleted:
print(f"\ndeleted files ({len(deleted)}, {human(sum(s for _, s in deleted))}):")
for rel, sz in sorted(deleted)[:15]:
print(f" -{human(sz):>9} {rel}")
if not (grown or shrunk or added or deleted):
print("no changes.")
return 0
ap.print_help()
return 2
if __name__ == "__main__":
sys.exit(main())