#!/usr/bin/env python3
# stashlist - list stashes with a summary of their contents
# Usage: stashlist [path] [--show N]
import argparse, os, subprocess, sys

def selftest():
    import tempfile
    from pathlib import Path
    with tempfile.TemporaryDirectory() as d:
        env = dict(os.environ, GIT_AUTHOR_NAME="T", GIT_AUTHOR_EMAIL="t@t",
                   GIT_COMMITTER_NAME="T", GIT_COMMITTER_EMAIL="t@t")
        def g(*a):
            subprocess.run(["git"] + list(a), cwd=d, env=env, check=True, capture_output=True)
        g("init", "-q", "-b", "main")
        Path(d, "a.txt").write_text("x\n"); g("add", "."); g("commit", "-qm", "c1")
        Path(d, "a.txt").write_text("x\ny\n")
        g("stash", "push", "-m", "wip stuff")
        out = subprocess.run([sys.executable, os.path.abspath(__file__), d],
                             capture_output=True, text=True)
        assert out.returncode == 0, out.stderr
        assert "wip stuff" in out.stdout and "a.txt" in out.stdout, out.stdout
        print("stashlist selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="stashlist",
        description="List git stashes with a summary of their contents.")
    ap.add_argument("path", nargs="?", default=".", help="path to the repo (default: .)")
    ap.add_argument("--show", type=int, default=None, metavar="N",
                    help="also show the full diff of stash N (e.g. --show 0)")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    r = subprocess.run(["git", "rev-parse", "--show-toplevel"], cwd=a.path,
                       capture_output=True, text=True)
    if r.returncode != 0:
        print("stashlist: not a git repository: %s" % a.path, file=sys.stderr); return 1
    cwd = r.stdout.strip()
    out = subprocess.run(["git", "stash", "list", "--format=%gd %gs"],
                         cwd=cwd, capture_output=True, text=True)
    entries = [l for l in out.stdout.splitlines() if l.strip()]
    if not entries:
        print("stashlist: no stashes."); return 0
    print("stashes (%d):" % len(entries))
    for line in entries:
        ref, _, msg = line.partition(" ")
        stat = subprocess.run(["git", "stash", "show", "--name-only", ref],
                              cwd=cwd, capture_output=True, text=True)
        files = [l for l in stat.stdout.splitlines() if l.strip()]
        num = subprocess.run(["git", "stash", "show", "--numstat", ref],
                             cwd=cwd, capture_output=True, text=True)
        add = dele = 0
        for l in num.stdout.splitlines():
            p = l.split("\t")
            if len(p) == 3:
                add += 0 if p[0] == "-" else int(p[0])
                dele += 0 if p[1] == "-" else int(p[1])
        print("  %-10s +%d/-%d  %d file(s): %s" % (ref, add, dele, len(files), msg))
        for f in files[:5]:
            print("      %s" % f)
        if len(files) > 5:
            print("      ... and %d more" % (len(files) - 5))
    if a.show is not None:
        print("\n--- stash@{%d} diff ---" % a.show)
        d = subprocess.run(["git", "stash", "show", "-p", "stash@{%d}" % a.show],
                           cwd=cwd, capture_output=True, text=True)
        print(d.stdout, end="")
    return 0

if __name__ == "__main__":
    sys.exit(main())
