diff --git a/larger-than b/larger-than new file mode 100755 index 0000000..808c05d --- /dev/null +++ b/larger-than @@ -0,0 +1,54 @@ +#!/usr/bin/python3 +import os +import subprocess +import sys +import re + +import click + + +def du(paths): + # Just using coreutils du, to have deduping, and the correct size + result = subprocess.check_output(["du", "-sc", "--block-size=1", *paths]) + total_line = result.splitlines()[-1] + total_bytes, total_check = total_line.split(b"\t") + assert total_check == b"total" + return int(total_bytes) + + +def interpret_prefixes(number, si=False): + # prefix as the "K" in "KB" + multiplier = 1000 if si else 1024 + + if m := re.match(r"^(?i:(\d+)([kmg])?)", number): + number, prefix = m.groups() + else: + raise ValueError("Can't interpret size") + + number = int(number) + if prefix is not None: + prefix = prefix.lower() + + exponent = { + None: 0, + "k": 1, + "m": 2, + "g": 3, + "t": 4, + } + return number * multiplier ** exponent[prefix] + +@click.command() +@click.argument("threshold") +@click.argument("paths", nargs=-1) +def larger_than(threshold, paths): + """Check if disk usage of PATHS is larger than THRESHOLD""" + threshold = interpret_prefixes(threshold) + if du(paths) > threshold: + sys.exit(0) + else: + sys.exit(1) + + +if __name__ == "__main__": + larger_than()