🚚 export: 16 files (moves)
M .gitignore M docs/windows-powershell-utf8.md M plugins/bevy/README.md M plugins/orbit/README.md M plugins/orbit/skills/orbit/references/review-recipes.md M plugins/project-uv/README.md M plugins/spire/CLAUDE.md R plugins/spire/agents/attacker.md -> plugins/spire/agents/advocate.md M plugins/spire/agents/igor.md M plugins/spire/agents/zathras.md M plugins/spire/skills/adepts/roster.sh M plugins/spire/skills/implementation/references/models.md A plugins/spire/skills/quire/tests/test_roster.py R plugins/spire/skills/workpad/SKILL.md -> plugins/spire/skills/quire/SKILL.md R plugins/spire/skills/workpad/tests/test_workpad.py -> plugins/spire/skills/quire/tests/test_quire.py R plugins/spire/skills/workpad/workpad.py -> plugins/spire/skills/quire/quire.py
This commit is contained in:
@@ -0,0 +1,247 @@
|
||||
# /// script
|
||||
# requires-python = ">=3.12"
|
||||
# dependencies = []
|
||||
# ///
|
||||
"""spire:quire helper: ignore guard, stale-run sweep, trash move. See SKILL.md (Tiers).
|
||||
|
||||
Stdlib only, no shell-outs, so it runs the same on Linux, macOS and Windows. Each command prints
|
||||
one JSON object. Exit 0 ok, 1 when some move failed, 2 refused or a usage error.
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class Refusal(Exception):
|
||||
def __init__(self, error: str, **fields):
|
||||
super().__init__(error)
|
||||
self.payload = {"error": error, **fields}
|
||||
|
||||
|
||||
class _Parser(argparse.ArgumentParser):
|
||||
def error(self, message):
|
||||
raise Refusal("usage", detail=message)
|
||||
|
||||
|
||||
def _abs(p) -> Path:
|
||||
return Path(os.path.abspath(str(p)))
|
||||
|
||||
|
||||
def _ceilings() -> set:
|
||||
return {os.path.normcase(os.path.realpath(c))
|
||||
for c in os.environ.get("GIT_CEILING_DIRECTORIES", "").split(os.pathsep) if c}
|
||||
|
||||
|
||||
def checkout(start: Path):
|
||||
"""(toplevel, git common dir) of the checkout holding `start`, else None. Reads `.git` the way
|
||||
git does instead of running it: a dir is the common dir; a file (worktree, submodule) names a
|
||||
gitdir, whose `commondir` file, if any, points to the common dir. Starts at the nearest existing
|
||||
ancestor, resolved, and does not climb into GIT_CEILING_DIRECTORIES."""
|
||||
while not start.is_dir() and start.parent != start:
|
||||
start = start.parent
|
||||
start, ceil = start.resolve(), _ceilings()
|
||||
for d in (start, *start.parents):
|
||||
if d != start and os.path.normcase(str(d)) in ceil:
|
||||
return None
|
||||
g = d / ".git"
|
||||
if g.is_dir():
|
||||
return d, g.resolve()
|
||||
if g.is_file():
|
||||
try:
|
||||
text = g.read_text(encoding="utf-8").strip()
|
||||
if not text.startswith("gitdir:"):
|
||||
return None
|
||||
gitdir = Path(os.path.join(d, text[len("gitdir:"):].strip()))
|
||||
common = gitdir / "commondir"
|
||||
if common.is_file():
|
||||
gitdir = Path(os.path.join(gitdir, common.read_text(encoding="utf-8").strip()))
|
||||
except OSError:
|
||||
return None
|
||||
return d, gitdir.resolve()
|
||||
return None
|
||||
|
||||
|
||||
def _key(p: Path) -> str:
|
||||
return os.path.normcase(str(p))
|
||||
|
||||
|
||||
def repo_of(args) -> Path:
|
||||
"""`--repo`; else gremlins' scratch rule (`grm/store.py` `scratch_root`): the run log's
|
||||
checkout, the cwd's when the run log is in another repo (worktrees of one repo are one repo) or
|
||||
in none, else the run log's dir. Without `--run`, the cwd's checkout."""
|
||||
if args.repo:
|
||||
return _abs(args.repo)
|
||||
try:
|
||||
cwd = checkout(_abs(Path.cwd()))
|
||||
except OSError: # cwd deleted
|
||||
cwd = None
|
||||
if args.run:
|
||||
run_dir = _abs(args.run).parent
|
||||
run = checkout(run_dir)
|
||||
if run is not None and (cwd is None or _key(run[1]) == _key(cwd[1])):
|
||||
return run[0]
|
||||
return cwd[0] if cwd is not None else run_dir
|
||||
if cwd is None:
|
||||
raise Refusal("no git checkout above the cwd; pass --repo", cwd=os.getcwd())
|
||||
return cwd[0]
|
||||
|
||||
|
||||
def ensure_ignore(d: Path) -> bool:
|
||||
"""Create `d` and a `*` .gitignore in it; never overwrite one. True if written."""
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
with open(d / ".gitignore", "x", encoding="utf-8", newline="\n") as f:
|
||||
f.write("*\n")
|
||||
except FileExistsError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def trash_dir(repo: Path) -> Path:
|
||||
return repo / ".spire" / "trash" / datetime.date.today().isoformat()
|
||||
|
||||
|
||||
def free_name(parent: Path, name: str) -> Path:
|
||||
"""`parent/name`, else `parent/name-2`, `-3`, … : the first that does not exist."""
|
||||
dst, i = parent / name, 2
|
||||
while dst.exists() or dst.is_symlink():
|
||||
dst, i = parent / ("%s-%d" % (name, i)), i + 1
|
||||
return dst
|
||||
|
||||
|
||||
def move_to_trash(repo: Path, srcs) -> dict:
|
||||
tdir = trash_dir(repo)
|
||||
ensure_ignore(repo / ".spire")
|
||||
moved, errors = [], []
|
||||
for s in srcs:
|
||||
src = _abs(s)
|
||||
if not src.exists() and not src.is_symlink():
|
||||
errors.append({"src": str(src), "error": "missing"})
|
||||
continue
|
||||
if src == tdir or src in tdir.parents:
|
||||
errors.append({"src": str(src), "error": "holds the trash dir"})
|
||||
continue
|
||||
tdir.mkdir(parents=True, exist_ok=True)
|
||||
dst = free_name(tdir, src.name)
|
||||
try:
|
||||
shutil.move(str(src), str(dst))
|
||||
except OSError as e:
|
||||
errors.append({"src": str(src), "error": str(e)})
|
||||
continue
|
||||
moved.append({"src": str(src), "dst": str(dst)})
|
||||
return {"trash": str(tdir), "moved": moved, "errors": errors}
|
||||
|
||||
|
||||
def newest_mtime(d: Path) -> float:
|
||||
"""Newest mtime of `d` and everything under it, symlinks not followed."""
|
||||
newest = d.lstat().st_mtime
|
||||
for root, dirs, files in d.walk():
|
||||
for n in dirs + files:
|
||||
try:
|
||||
newest = max(newest, (root / n).lstat().st_mtime)
|
||||
except OSError:
|
||||
pass
|
||||
return newest
|
||||
|
||||
|
||||
def cmd_guard(args) -> dict:
|
||||
repo = repo_of(args)
|
||||
written, present = [], []
|
||||
for d in (_abs(args.quire) / "logs", repo / ".spire"):
|
||||
(written if ensure_ignore(d) else present).append(str(d / ".gitignore"))
|
||||
return {"written": written, "present": present}
|
||||
|
||||
|
||||
def check_scratch_root(root: Path, repo: Path) -> None:
|
||||
"""Refuse a root that may hold repo content: one holding `repo`, one inside a checkout but not
|
||||
under its `.spire/scratch`, and one outside every checkout without the `*` .gitignore that
|
||||
gremlins writes in each scratch root."""
|
||||
rr = root.resolve()
|
||||
if rr in (repo.resolve(), *repo.resolve().parents):
|
||||
raise Refusal("not a scratch root: holds the repo", root=str(root))
|
||||
co = checkout(rr)
|
||||
if co is not None:
|
||||
if rr.relative_to(co[0]).parts[:2] != (".spire", "scratch"):
|
||||
raise Refusal("not a scratch root: in a checkout, not under its .spire/scratch",
|
||||
root=str(root), checkout=str(co[0]))
|
||||
return
|
||||
try:
|
||||
marked = (rr / ".gitignore").read_text(encoding="utf-8").strip() == "*"
|
||||
except OSError:
|
||||
marked = False
|
||||
if not marked:
|
||||
raise Refusal("not a scratch root: no `*` .gitignore", root=str(root))
|
||||
|
||||
|
||||
def cmd_sweep(args) -> dict:
|
||||
repo = repo_of(args)
|
||||
root = _abs(args.root or os.environ.get("SPIRE_SCRATCH") or repo / ".spire" / "scratch")
|
||||
cutoff = time.time() - args.days * 86400
|
||||
stale, kept = [], []
|
||||
if root.is_dir():
|
||||
check_scratch_root(root, repo)
|
||||
for d in sorted(root.iterdir()):
|
||||
if d.is_symlink() or not d.is_dir():
|
||||
continue
|
||||
if newest_mtime(d) < cutoff:
|
||||
(kept if (d / "keep").exists() else stale).append(str(d))
|
||||
out = {"root": str(root), "days": args.days, "stale": stale, "kept": kept}
|
||||
if args.move:
|
||||
out.update(move_to_trash(repo, stale))
|
||||
return out
|
||||
|
||||
|
||||
def cmd_trash(args) -> dict:
|
||||
return move_to_trash(repo_of(args), args.dirs)
|
||||
|
||||
|
||||
def _parser() -> argparse.ArgumentParser:
|
||||
p = _Parser(prog="quire.py", description=__doc__.splitlines()[0])
|
||||
sub = p.add_subparsers(dest="cmd", required=True, parser_class=_Parser)
|
||||
common = _Parser(add_help=False)
|
||||
common.add_argument("--run", help="the run log; <repo> follows gremlins' scratch rule")
|
||||
common.add_argument("--repo", help="checkout root (default: from --run, else the cwd's checkout)")
|
||||
g = sub.add_parser("guard", parents=[common], help="write `*` .gitignore files in <quire>/logs "
|
||||
"and <repo>/.spire; never overwrite")
|
||||
g.add_argument("quire", help="the quire base dir")
|
||||
s = sub.add_parser("sweep", parents=[common], help="list run dirs under the scratch root with no "
|
||||
"entry modified in --days and no `keep` file")
|
||||
s.add_argument("root", nargs="?", help="scratch root (default: $SPIRE_SCRATCH, else "
|
||||
"<repo>/.spire/scratch)")
|
||||
s.add_argument("--days", type=float, default=7)
|
||||
s.add_argument("--move", action="store_true", help="move the stale dirs to trash")
|
||||
t = sub.add_parser("trash", parents=[common], help="move dirs to <repo>/.spire/trash/<YYYY-MM-DD>/, "
|
||||
"suffix -2, -3 on a name collision; never overwrite")
|
||||
t.add_argument("dirs", nargs="+")
|
||||
return p
|
||||
|
||||
|
||||
COMMANDS = {"guard": cmd_guard, "sweep": cmd_sweep, "trash": cmd_trash}
|
||||
|
||||
|
||||
def _emit(obj: dict) -> None:
|
||||
sys.stdout.write(json.dumps(obj) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
try:
|
||||
args = _parser().parse_args(argv)
|
||||
out = COMMANDS[args.cmd](args)
|
||||
except Refusal as e:
|
||||
_emit(e.payload)
|
||||
return 2
|
||||
except OSError as e:
|
||||
_emit({"error": str(e), "type": type(e).__name__})
|
||||
return 2
|
||||
_emit(out)
|
||||
return 1 if out.get("errors") else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
Reference in New Issue
Block a user