299 lines
14 KiB
Python
299 lines
14 KiB
Python
import contextlib
|
|
import datetime
|
|
import io
|
|
import json
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
from pathlib import Path
|
|
from unittest import mock
|
|
|
|
SKILL = Path(__file__).resolve().parent.parent
|
|
sys.path.insert(0, str(SKILL))
|
|
sys.path.insert(0, str(SKILL.parent / "gremlins"))
|
|
|
|
import workpad # noqa: E402
|
|
from grm import store # noqa: E402
|
|
|
|
DAY = 86400
|
|
|
|
|
|
class WorkpadTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = Path(tempfile.mkdtemp()).resolve()
|
|
self.addCleanup(shutil.rmtree, self.tmp, True)
|
|
env = mock.patch.dict(os.environ, {"GIT_CEILING_DIRECTORIES": str(self.tmp)})
|
|
env.start()
|
|
self.addCleanup(env.stop)
|
|
os.environ.pop("SPIRE_SCRATCH", None)
|
|
self.repo = self.tmp / "repo"
|
|
(self.repo / ".git").mkdir(parents=True)
|
|
self.wp = self.repo / "docs" / "workpad"
|
|
self.scratch = self.repo / ".spire" / "scratch"
|
|
self.trash = self.repo / ".spire" / "trash" / datetime.date.today().isoformat()
|
|
|
|
def w(self, *args, code=0, repo=True):
|
|
buf = io.StringIO()
|
|
with contextlib.redirect_stdout(buf):
|
|
rc = workpad.main([*args, "--repo", str(self.repo)] if repo else list(args))
|
|
lines = buf.getvalue().splitlines()
|
|
self.assertEqual(len(lines), 1, lines)
|
|
out = json.loads(lines[0])
|
|
self.assertEqual(rc, code, out)
|
|
return out
|
|
|
|
def run_dir(self, name, age_days=0, files=("a.txt",)):
|
|
d = self.scratch / name
|
|
(d / "sub").mkdir(parents=True)
|
|
for f in files:
|
|
(d / "sub" / f).write_text("x", encoding="utf-8")
|
|
t = time.time() - age_days * DAY
|
|
for root, dirs, fs in d.walk(top_down=False):
|
|
for n in dirs + fs:
|
|
os.utime(root / n, (t, t))
|
|
os.utime(d, (t, t))
|
|
return d
|
|
|
|
def chdir(self, d):
|
|
cwd = os.getcwd()
|
|
os.chdir(d)
|
|
self.addCleanup(os.chdir, cwd)
|
|
|
|
# guard
|
|
|
|
def test_guard_writes_then_is_idempotent(self):
|
|
out = self.w("guard", str(self.wp))
|
|
self.assertEqual(sorted(out["written"]), sorted([str(self.wp / "logs" / ".gitignore"),
|
|
str(self.repo / ".spire" / ".gitignore")]))
|
|
self.assertEqual(out["present"], [])
|
|
for d in (self.wp / "logs", self.repo / ".spire"):
|
|
self.assertEqual((d / ".gitignore").read_bytes(), b"*\n")
|
|
out = self.w("guard", str(self.wp))
|
|
self.assertEqual(out["written"], [])
|
|
self.assertEqual(len(out["present"]), 2)
|
|
|
|
def test_guard_never_overwrites(self):
|
|
(self.repo / ".spire").mkdir()
|
|
(self.repo / ".spire" / ".gitignore").write_text("mine\n", encoding="utf-8")
|
|
out = self.w("guard", str(self.wp))
|
|
self.assertEqual(out["present"], [str(self.repo / ".spire" / ".gitignore")])
|
|
self.assertEqual((self.repo / ".spire" / ".gitignore").read_text(encoding="utf-8"), "mine\n")
|
|
self.assertEqual((self.wp / "logs" / ".gitignore").read_bytes(), b"*\n")
|
|
|
|
def test_repo_defaults_to_cwd_toplevel(self):
|
|
(self.repo / "deep" / "er").mkdir(parents=True)
|
|
cwd = os.getcwd()
|
|
os.chdir(self.repo / "deep" / "er")
|
|
self.addCleanup(os.chdir, cwd)
|
|
buf = io.StringIO()
|
|
with contextlib.redirect_stdout(buf):
|
|
self.assertEqual(workpad.main(["guard", str(self.wp)]), 0)
|
|
self.assertTrue((self.repo / ".spire" / ".gitignore").exists())
|
|
|
|
def test_no_repo_is_refused(self):
|
|
# review R2 m5: a checkout above the cwd (here self.repo; on a host, maybe $HOME) is not
|
|
# found past GIT_CEILING_DIRECTORIES, as with git
|
|
bare = self.repo / "ceiling" / "bare"
|
|
bare.mkdir(parents=True)
|
|
self.chdir(bare)
|
|
with mock.patch.dict(os.environ, {"GIT_CEILING_DIRECTORIES": str(self.repo / "ceiling")}):
|
|
self.assertIn("--repo", self.w("trash", "x", code=2, repo=False)["error"])
|
|
|
|
def git(self, *args, cwd):
|
|
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false",
|
|
*args], cwd=str(cwd), check=True, capture_output=True, timeout=60)
|
|
|
|
@unittest.skipUnless(shutil.which("git"), "needs git")
|
|
def test_repo_matches_gremlins_scratch_root(self):
|
|
main, other, bare = self.tmp / "main", self.tmp / "other", self.tmp / "bare"
|
|
for d in (main, other, bare):
|
|
d.mkdir()
|
|
for d in (main, other):
|
|
self.git("init", "-q", cwd=d)
|
|
self.git("commit", "-q", "--no-verify", "--allow-empty", "-m", "i", cwd=main)
|
|
self.git("worktree", "add", "-q", str(self.tmp / "wt"), cwd=main)
|
|
wt = self.tmp / "wt"
|
|
log = lambda top: top / "docs" / "workpad" / "logs" / "x" / "run.md" # dir not created
|
|
cases = [(wt, main, main), (main, wt, wt), (other, main, other), (bare, main, main),
|
|
(wt / "src", bare, wt), (bare, bare, None)]
|
|
(wt / "src").mkdir()
|
|
for cwd, run_top, want in cases:
|
|
with self.subTest(cwd=cwd.name, run=run_top.name):
|
|
self.chdir(cwd)
|
|
run = log(run_top)
|
|
out = self.w("sweep", "--run", str(run), repo=False)
|
|
self.assertEqual(out["root"], str(store.scratch_root(run)))
|
|
if want is not None:
|
|
self.assertEqual(out["root"], str(want / ".spire" / "scratch"))
|
|
|
|
def test_worktree_resolves_to_the_run_logs_checkout(self):
|
|
# no git needed: a worktree's `.git` file names <common>/worktrees/<name>, whose `commondir`
|
|
# file points back to <common>
|
|
main, wt = self.tmp / "main", self.tmp / "wt"
|
|
(main / ".git" / "worktrees" / "wt").mkdir(parents=True)
|
|
(main / ".git" / "worktrees" / "wt" / "commondir").write_text("../..\n", encoding="utf-8")
|
|
wt.mkdir()
|
|
(wt / ".git").write_text("gitdir: %s\n" % (main / ".git" / "worktrees" / "wt"), encoding="utf-8")
|
|
self.chdir(wt)
|
|
run = main / "docs" / "workpad" / "logs" / "x" / "run.md"
|
|
self.assertEqual(self.w("sweep", "--run", str(run), repo=False)["root"],
|
|
str(main / ".spire" / "scratch"))
|
|
src = wt / "run-dir"
|
|
src.mkdir()
|
|
self.assertEqual(self.w("trash", str(src), "--run", str(run), repo=False)["trash"],
|
|
str(main / ".spire" / "trash" / datetime.date.today().isoformat()))
|
|
self.assertEqual(self.w("sweep", repo=False)["root"], str(wt / ".spire" / "scratch"))
|
|
|
|
# trash
|
|
|
|
def test_trash_collision_suffix(self):
|
|
srcs = []
|
|
for i in range(3):
|
|
d = self.tmp / ("src%d" % i) / "run"
|
|
d.mkdir(parents=True)
|
|
(d / "f").write_text(str(i), encoding="utf-8")
|
|
srcs.append(d)
|
|
out = self.w("trash", str(srcs[0]))
|
|
self.assertEqual(out["moved"], [{"src": str(srcs[0]), "dst": str(self.trash / "run")}])
|
|
out = self.w("trash", str(srcs[1]), str(srcs[2]))
|
|
self.assertEqual([m["dst"] for m in out["moved"]],
|
|
[str(self.trash / "run-2"), str(self.trash / "run-3")])
|
|
for i, n in enumerate(("run", "run-2", "run-3")):
|
|
self.assertEqual((self.trash / n / "f").read_text(encoding="utf-8"), str(i))
|
|
self.assertFalse(any(s.exists() for s in srcs))
|
|
self.assertEqual((self.repo / ".spire" / ".gitignore").read_bytes(), b"*\n")
|
|
|
|
def test_trash_never_overwrites_a_file_of_the_same_name(self):
|
|
self.trash.mkdir(parents=True)
|
|
(self.trash / "run").write_text("old", encoding="utf-8")
|
|
src = self.tmp / "run"
|
|
src.mkdir()
|
|
out = self.w("trash", str(src))
|
|
self.assertEqual(out["moved"][0]["dst"], str(self.trash / "run-2"))
|
|
self.assertEqual((self.trash / "run").read_text(encoding="utf-8"), "old")
|
|
|
|
def test_trash_name_with_spaces(self):
|
|
src = self.tmp / "my run dir"
|
|
src.mkdir()
|
|
(src / "a b.txt").write_text("x", encoding="utf-8")
|
|
self.w("trash", str(src))
|
|
src.mkdir()
|
|
out = self.w("trash", str(src) + os.sep)
|
|
self.assertEqual(out["moved"][0]["dst"], str(self.trash / "my run dir-2"))
|
|
self.assertTrue((self.trash / "my run dir" / "a b.txt").exists())
|
|
|
|
def test_trash_missing_and_self_are_errors(self):
|
|
src = self.tmp / "ok"
|
|
src.mkdir()
|
|
out = self.w("trash", str(self.tmp / "nope"), str(self.repo / ".spire"), str(src), code=1)
|
|
self.assertEqual([e["error"] for e in out["errors"]], ["missing", "holds the trash dir"])
|
|
self.assertEqual(out["moved"][0]["dst"], str(self.trash / "ok"))
|
|
self.assertTrue((self.repo / ".spire" / ".gitignore").exists())
|
|
|
|
# sweep
|
|
|
|
def test_sweep_age_and_keep(self):
|
|
old = self.run_dir("old", age_days=8)
|
|
self.run_dir("fresh", age_days=1)
|
|
kept = self.run_dir("kept", age_days=30, files=("a.txt", "keep"))
|
|
mixed = self.run_dir("mixed", age_days=30)
|
|
(mixed / "sub" / "new.txt").write_text("x", encoding="utf-8") # one fresh file deep down
|
|
(self.scratch / ".gitignore").write_text("*\n", encoding="utf-8")
|
|
out = self.w("sweep")
|
|
self.assertEqual(out["root"], str(self.scratch))
|
|
self.assertEqual(out["stale"], [str(kept), str(old)]) # `keep` counts only at the top
|
|
self.assertEqual(out["kept"], [])
|
|
(kept / "keep").write_text("", encoding="utf-8")
|
|
os.utime(kept / "keep", (time.time() - 30 * DAY,) * 2)
|
|
os.utime(kept, (time.time() - 30 * DAY,) * 2)
|
|
out = self.w("sweep")
|
|
self.assertEqual(out["stale"], [str(old)])
|
|
self.assertEqual(out["kept"], [str(kept)])
|
|
self.assertEqual(self.w("sweep", "--days", "10")["stale"], [])
|
|
self.assertTrue(old.exists()) # listing moves nothing
|
|
|
|
def test_sweep_move(self):
|
|
old = self.run_dir("old run", age_days=8)
|
|
fresh = self.run_dir("fresh", age_days=0)
|
|
out = self.w("sweep", str(self.scratch), "--move")
|
|
self.assertEqual(out["moved"], [{"src": str(old), "dst": str(self.trash / "old run")}])
|
|
self.assertFalse(old.exists())
|
|
self.assertTrue((self.trash / "old run" / "sub" / "a.txt").exists())
|
|
self.assertTrue(fresh.exists())
|
|
|
|
def test_sweep_missing_root(self):
|
|
out = self.w("sweep", str(self.tmp / "none"), "--move")
|
|
self.assertEqual((out["stale"], out["moved"]), ([], []))
|
|
|
|
def test_sweep_refuses_a_root_that_is_not_scratch(self):
|
|
# review R2 m1: SPIRE_SCRATCH set to the repo listed `.git` and `docs` as stale
|
|
(self.wp / "logs").mkdir(parents=True)
|
|
(self.wp / "logs" / ".gitignore").write_text("*\n", encoding="utf-8")
|
|
old = time.time() - 10 * DAY
|
|
for p in (self.repo / ".git", self.repo / "docs", self.wp, self.wp / "logs"):
|
|
os.utime(p, (old, old))
|
|
home = self.tmp / "home"
|
|
(home / "stuff").mkdir(parents=True)
|
|
os.utime(home / "stuff", (old, old))
|
|
for root in (self.repo, self.repo / "docs", self.wp / "logs", self.tmp, home):
|
|
with self.subTest(root=root):
|
|
with mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(root)}):
|
|
out = self.w("sweep", "--move", code=2)
|
|
self.assertIn("not a scratch root", out["error"])
|
|
self.assertEqual(self.w("sweep", str(root), "--move", code=2)["error"], out["error"])
|
|
self.assertTrue((self.repo / ".git").is_dir() and (self.wp / "logs").is_dir())
|
|
self.assertTrue((home / "stuff").is_dir())
|
|
self.assertFalse((self.repo / ".spire" / "trash").exists())
|
|
|
|
def test_sweep_outside_root_needs_the_scratch_ignore(self):
|
|
shared = self.tmp / "shared"
|
|
self.scratch = shared
|
|
old = self.run_dir("old", age_days=8)
|
|
(shared / ".gitignore").write_text("*\n", encoding="utf-8") # gremlins writes it
|
|
with mock.patch.dict(os.environ, {"SPIRE_SCRATCH": str(shared)}):
|
|
out = self.w("sweep", "--move")
|
|
self.assertEqual(out["moved"], [{"src": str(old), "dst": str(self.trash / "old")}])
|
|
|
|
def test_sweep_does_not_follow_symlinks(self):
|
|
fresh = self.tmp / "fresh-target"
|
|
(fresh / "d").mkdir(parents=True)
|
|
(fresh / "f").write_text("x", encoding="utf-8")
|
|
old = self.run_dir("old", age_days=8)
|
|
lonely = self.run_dir("lonely", age_days=8)
|
|
try:
|
|
for link, target in ((old / "link-f", fresh / "f"), (old / "link-d", fresh / "d"),
|
|
(self.scratch / "link-run", lonely)):
|
|
os.symlink(target, link, target_is_directory=target.is_dir())
|
|
if os.utime not in os.supports_follow_symlinks:
|
|
raise NotImplementedError
|
|
t = time.time() - 8 * DAY
|
|
for p in (old / "link-f", old / "link-d", self.scratch / "link-run"):
|
|
os.utime(p, (t, t), follow_symlinks=False)
|
|
os.utime(old, (t, t))
|
|
except (OSError, NotImplementedError):
|
|
self.skipTest("cannot create or date symlinks here")
|
|
out = self.w("sweep")
|
|
self.assertEqual(out["stale"], [str(lonely), str(old)]) # link targets are fresh; link-run skipped
|
|
|
|
# entry point
|
|
|
|
def test_script_runs_standalone(self):
|
|
r = subprocess.run([sys.executable, str(SKILL / "workpad.py"), "guard", str(self.wp),
|
|
"--repo", str(self.repo)], capture_output=True, text=True, timeout=60)
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(len(json.loads(r.stdout)["written"]), 2)
|
|
|
|
def test_usage_error_is_json(self):
|
|
buf = io.StringIO()
|
|
with contextlib.redirect_stdout(buf):
|
|
self.assertEqual(workpad.main(["sweep", "--days", "x"]), 2)
|
|
self.assertEqual(json.loads(buf.getvalue())["error"], "usage")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|