120 lines
5.1 KiB
Python
Executable File
120 lines
5.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""dustack - show which subdirectories grew most since the last snapshot (growth tracker, not just du).
|
|
Usage: dustack [dir] [--snapshot [file]] [--compare [file]] [--top N] [--selftest] [--help]
|
|
Snapshots record each immediate subdirectory's size + file count as JSON.
|
|
Run again later and dustack ranks subdirs by growth (bytes and %), so you see
|
|
what actually grew, not just what is big. Default snapshot: <dir>/.dustack.json
|
|
(unless --snapshot names a file). --compare reads a given snapshot instead of
|
|
the default one. First run with no snapshot just takes one and says so.
|
|
"""
|
|
import argparse, json, os, sys, tempfile, time
|
|
from pathlib import Path
|
|
|
|
def dir_size(p):
|
|
total, n = 0, 0
|
|
for dp, dns, fns in os.walk(p):
|
|
for fn in fns:
|
|
try:
|
|
st = os.lstat(os.path.join(dp, fn))
|
|
if os.path.isfile(os.path.join(dp, fn)):
|
|
total += st.st_size; n += 1
|
|
except OSError:
|
|
pass
|
|
return total, n
|
|
|
|
def human(n):
|
|
for u in ("B", "KiB", "MiB", "GiB", "TiB"):
|
|
if abs(n) < 1024 or u == "TiB":
|
|
return f"{n:.1f} {u}" if u != "B" else f"{n} B"
|
|
n /= 1024
|
|
|
|
def snapshot_tree(root):
|
|
root = Path(root)
|
|
snap = {"root": str(root.resolve()), "time": time.time(), "dirs": {}}
|
|
for child in sorted(root.iterdir()):
|
|
if child.is_dir() and not child.is_symlink():
|
|
s, n = dir_size(child)
|
|
snap["dirs"][child.name] = {"bytes": s, "files": n}
|
|
# files directly in root, as "."
|
|
s, n = 0, 0
|
|
for fn in root.iterdir():
|
|
if fn.is_file():
|
|
s += fn.stat().st_size; n += 1
|
|
snap["dirs"]["."] = {"bytes": s, "files": n}
|
|
return snap
|
|
|
|
def load(p):
|
|
with open(p) as f:
|
|
return json.load(f)
|
|
|
|
def selftest():
|
|
with tempfile.TemporaryDirectory() as td:
|
|
base = Path(td)
|
|
(base / "a").mkdir(); (base / "b").mkdir()
|
|
(base / "a" / "f1").write_bytes(b"x" * 100)
|
|
(base / "b" / "f1").write_bytes(b"y" * 100)
|
|
snap = snapshot_tree(base)
|
|
assert snap["dirs"]["a"]["bytes"] == 100 and snap["dirs"]["b"]["bytes"] == 100
|
|
(base / "a" / "f2").write_bytes(b"z" * 900)
|
|
(base / "b" / "f1").write_bytes(b"y" * 50) # shrink b
|
|
now = snapshot_tree(base)
|
|
rows = []
|
|
for name, cur in now["dirs"].items():
|
|
old = snap["dirs"].get(name, {"bytes": 0, "files": 0})
|
|
rows.append((name, cur["bytes"] - old["bytes"]))
|
|
rows.sort(key=lambda r: -r[1])
|
|
assert rows[0] == ("a", 900), rows
|
|
assert dict(rows)["b"] == -50
|
|
print("selftest OK: growth ranked correctly (a +900 B, b -50 B)")
|
|
return 0
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description="dustack - which subdirectories grew since the last snapshot")
|
|
ap.add_argument("dir", nargs="?", default=".")
|
|
ap.add_argument("--snapshot", nargs="?", const="__default__", default=None,
|
|
help="take a snapshot (default file <dir>/.dustack.json)")
|
|
ap.add_argument("--compare", metavar="FILE", help="compare against this snapshot file")
|
|
ap.add_argument("--top", type=int, default=10)
|
|
ap.add_argument("--selftest", action="store_true")
|
|
a = ap.parse_args()
|
|
if a.selftest:
|
|
return selftest()
|
|
root = Path(a.dir)
|
|
if not root.is_dir():
|
|
print(f"dustack: {a.dir}: not a directory", file=sys.stderr); return 2
|
|
snapfile = Path(a.compare) if a.compare else root / ".dustack.json"
|
|
if a.snapshot is not None:
|
|
target = (root / ".dustack.json") if a.snapshot == "__default__" else Path(a.snapshot)
|
|
snap = snapshot_tree(root)
|
|
with open(target, "w") as f:
|
|
json.dump(snap, f, indent=2)
|
|
print(f"snapshot saved to {target} ({len(snap['dirs'])} dirs)")
|
|
return 0
|
|
now = snapshot_tree(root)
|
|
if not snapfile.exists():
|
|
with open(root / ".dustack.json", "w") as f:
|
|
json.dump(now, f, indent=2)
|
|
print(f"no previous snapshot; saved one to {root / '.dustack.json'} — run again later to see growth")
|
|
return 0
|
|
old = load(snapfile)
|
|
age = time.time() - old.get("time", now["time"])
|
|
print(f"growth since {time.strftime('%Y-%m-%d %H:%M', time.localtime(old.get('time', 0)))} ({age/86400:.1f} days ago), root {old.get('root')}")
|
|
rows = []
|
|
for name, cur in now["dirs"].items():
|
|
o = old.get("dirs", {}).get(name, {"bytes": 0, "files": 0})
|
|
d = cur["bytes"] - o["bytes"]
|
|
pct = (d / o["bytes"] * 100) if o["bytes"] else (float("inf") if d > 0 else 0.0)
|
|
rows.append((name, d, pct, cur["bytes"], cur["files"] - o["files"]))
|
|
for name in old.get("dirs", {}):
|
|
if name not in now["dirs"]:
|
|
rows.append((name + " (gone)", -old["dirs"][name]["bytes"], -100.0, 0, -old["dirs"][name]["files"]))
|
|
rows.sort(key=lambda r: -abs(r[1]))
|
|
print(f"{'DIR':<20} {'GROWTH':>12} {'%':>8} {'NOW':>12} {'FILES +/-':>10}")
|
|
for name, d, pct, cur, df in rows[:a.top]:
|
|
ps = f"{pct:+.1f}%" if pct != float("inf") else "new"
|
|
print(f"{name:<20} {human(d) if d>=0 else '-'+human(-d):>12} {ps:>8} {human(cur):>12} {df:+d}")
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|