Fix hostile project files, non-blocking tick lock, store commit lock, and revert checks
This commit is contained in:
1 parent
e969aa2bd4
commit
2bec0823f3
5 files changed
+285
-39
No files matched your search
+1
-1
@@ -20,7 +20,7 @@ The learning loop
|
||||
sisi rules organize [--record FILE]
|
||||
the brief for a cheap worker to audit and organize them; record its answer
|
||||
sisi rules revert undo the last rule change made with learn, a retro or organize (user or project;
|
||||
not the one-time move of old rules); declines if the project file changed since
|
||||
not the move of old rules; a second re-applies it); declines if the project file changed
|
||||
|
||||
Delegation
|
||||
sisi models the workers you have: what each is good at and what it costs
|
||||
|
||||
+20
-20
@@ -66,12 +66,12 @@ def lines(p):
|
||||
|
||||
|
||||
def _text(p):
|
||||
"""What a project's rule list holds now, None when there is none; OSError when it is not UTF-8."""
|
||||
"""What a regular file holds now, None when absent; OSError when unusable or not UTF-8."""
|
||||
why, raw = store.regular(p, True)
|
||||
if why:
|
||||
raise OSError("%s is %s" % (p, why))
|
||||
try:
|
||||
with open(p, "rb") as f:
|
||||
return f.read().decode("utf-8")
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
return None if raw is None else raw.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
raise OSError(".sisi/rules.md is not valid UTF-8")
|
||||
|
||||
@@ -84,8 +84,8 @@ def _check_writable(p):
|
||||
if not p:
|
||||
raise OSError("this folder is inside a git directory or a bare repository")
|
||||
for t, label, folder in ((os.path.dirname(p), ".sisi", True), (p, ".sisi/rules.md", False)):
|
||||
why = ("a symlink" if os.path.islink(t) else ("not a directory" if folder else "a directory") if os.path.lexists(t) and os.path.isdir(t) != folder
|
||||
else "read-only" if os.path.exists(t) and not os.access(t, os.W_OK) else "")
|
||||
why = (("a symlink" if os.path.islink(t) else "not a directory" if os.path.lexists(t) and not os.path.isdir(t) else "") if folder
|
||||
else store.regular(t)[0]) or ("read-only" if os.path.exists(t) and not os.access(t, os.W_OK) else "")
|
||||
if why:
|
||||
raise OSError("%s is %s" % (label, why))
|
||||
if not os.path.exists(os.path.dirname(p)) and not os.access(os.path.dirname(os.path.dirname(p)), os.W_OK):
|
||||
@@ -137,15 +137,15 @@ def _move(dest, old):
|
||||
return ""
|
||||
|
||||
|
||||
def _migrate(cwd=None):
|
||||
def _migrate(cwd=None, wait=True):
|
||||
"""Move this project's rules out of the store if an old file exists. Returns (rules, warning)."""
|
||||
dest, old = path(PROJECT, cwd), _legacy(cwd)
|
||||
msg = ("sisi: project rules are not kept inside a git directory or a bare repository." if not dest
|
||||
else "sisi: %s is a link, and sisi does not use a linked .sisi; its rules are not read." % os.path.dirname(dest) if os.path.islink(os.path.dirname(dest))
|
||||
else "")
|
||||
else "sisi: %s is a link, and sisi does not use a linked .sisi; its rules are not read." % d if os.path.islink(d := os.path.dirname(dest))
|
||||
else "sisi: %s is %s; its rules are not read." % (dest, why) if not os.path.isfile(old) and (why := "not a directory" if os.path.lexists(d) and not os.path.isdir(d) else store.regular(dest)[0]) else "")
|
||||
if not msg and os.path.isfile(old):
|
||||
with store.lock(dest):
|
||||
msg = _move(dest, old)
|
||||
with store.lock(dest, wait=wait) as ok:
|
||||
msg = _move(dest, old) if ok else ""
|
||||
return scope_lines(PROJECT, cwd, migrate=False), msg
|
||||
|
||||
|
||||
@@ -155,8 +155,8 @@ def scope_lines(scope, cwd=None, migrate=True):
|
||||
if migrate:
|
||||
return _migrate(cwd)[0]
|
||||
dest, old = path(PROJECT, cwd), _legacy(cwd)
|
||||
mine = [] if not dest or os.path.islink(os.path.dirname(dest)) else lines(dest)
|
||||
return list(dict.fromkeys(mine + lines(old)))
|
||||
raw = store.regular(dest, True)[1] if dest and not os.path.islink(os.path.dirname(dest)) else None
|
||||
return list(dict.fromkeys((_parse(raw.decode("utf-8", "replace")) if raw is not None else []) + lines(old)))
|
||||
|
||||
|
||||
def _commit(msg, *paths, snap=None):
|
||||
@@ -227,7 +227,7 @@ def build_rulebook():
|
||||
|
||||
|
||||
def project_text(cwd):
|
||||
ls, note = _migrate(cwd)
|
||||
ls, note = _migrate(cwd, wait=False)
|
||||
mine = _fit(ls)
|
||||
return "\n".join(x for x in (note, HEAD_PROJECT + "\n" + "\n".join(mine) if mine else "") if x)
|
||||
|
||||
@@ -252,7 +252,7 @@ def due(cwd):
|
||||
"""One line when the learned rules need organizing, else ""."""
|
||||
cfg, seen, why = store.config(), _organized(), []
|
||||
for scope in (USER, PROJECT):
|
||||
ls, k = scope_lines(scope, cwd), _mark_key(scope, cwd)
|
||||
ls, k = scope_lines(scope, cwd, migrate=False), _mark_key(scope, cwd)
|
||||
prev = int(seen.get(k, seen.get("rules/projects/%s.md" % store.project_key(cwd), 0) if scope == PROJECT else 0))
|
||||
over = len(ls) > cfg["rules_lines"] or sum(map(len, ls)) > cfg["rules_chars"]
|
||||
added = len(ls) - prev
|
||||
@@ -294,7 +294,7 @@ def organize_record(answer_file, cwd):
|
||||
msg = _move(pp, _legacy(cwd))
|
||||
if msg:
|
||||
return msg.removeprefix("sisi: ")
|
||||
had = {USER: lines(up), PROJECT: lines(pp)}
|
||||
had = {USER: lines(up), PROJECT: scope_lines(PROJECT, cwd, migrate=False)}
|
||||
if not any(got.values()) and any(had.values()):
|
||||
return "the answer holds no rules at all"
|
||||
try:
|
||||
@@ -346,12 +346,12 @@ def revert():
|
||||
snap = json.loads(raw)
|
||||
except ValueError:
|
||||
snap = None
|
||||
if (not isinstance(snap, dict) or not {"path", "before", "after"} <= set(snap)
|
||||
or not isinstance(snap["path"], str) or not snap["path"].endswith("/.sisi/rules.md")
|
||||
if (not isinstance(snap, dict) or not {"path", "before", "after"} <= set(snap) or not isinstance(sp := snap["path"], str)
|
||||
or not os.path.isabs(sp) or os.path.normpath(sp) != sp or not sp.endswith("/.sisi/rules.md") or ".git" in sp.split(os.sep)
|
||||
or any(snap[k] is not None and not isinstance(snap[k], str) for k in ("before", "after"))):
|
||||
return "the undo record for `%s` is missing, corrupt or outside .sisi/rules.md, so it cannot be undone%s" % (subject, advice)
|
||||
p, (now, want) = snap.get("path"), (snap.get("before"), snap.get("after"))[::1 if redo else -1]
|
||||
with store.lock(p or "user"):
|
||||
with store.lock(p or "user"), store.lock("store"):
|
||||
if store.git(["log", "-1", "--format=%H", "--", *files], store.DATA)[1].strip() != commit:
|
||||
return "another rule change finished while waiting; run `sisi rules revert` again"
|
||||
try:
|
||||
|
||||
+29
-12
@@ -92,11 +92,12 @@ def git(args, cwd, timeout=15):
|
||||
|
||||
def commit(message, *paths):
|
||||
"""One commit in the person's store holding only these paths, so the change can be undone on its own."""
|
||||
if not os.path.isdir(os.path.join(DATA, ".git")):
|
||||
git(["init", "-q"], DATA)
|
||||
rel = [os.path.relpath(p, DATA) for p in paths]
|
||||
return (git(["add", "-A", "--"] + rel, DATA)[0] == 0 and
|
||||
git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "-m", message, "--"] + rel, DATA)[0] == 0)
|
||||
with lock("store"):
|
||||
os.path.isdir(os.path.join(DATA, ".git")) or git(["init", "-q"], DATA)
|
||||
rel = [os.path.relpath(p, DATA) for p in paths]
|
||||
return (git(["add", "-A", "--"] + rel, DATA)[0] == 0 and
|
||||
(git(["status", "--porcelain", "--"] + rel, DATA) == (0, "") or
|
||||
git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "-m", message, "--"] + rel, DATA)[0] == 0))
|
||||
|
||||
|
||||
_roots = {}
|
||||
@@ -128,6 +129,19 @@ def project_key(cwd=None):
|
||||
return "%s-%s" % (os.path.basename(root) or "root", hashlib.sha1(root.encode()).hexdigest()[:8])
|
||||
|
||||
|
||||
def regular(path, load=False):
|
||||
"""("", bytes|None) if `path` is absent or a regular non-link file within 64,000 bytes, else (reason, None)."""
|
||||
try:
|
||||
st = os.lstat(path)
|
||||
why = "a symlink" if stat.S_ISLNK(st.st_mode) else "not a regular file" if not stat.S_ISREG(st.st_mode) else "over 64,000 bytes" if st.st_size > 64000 else ""
|
||||
if why or not load:
|
||||
return why, None
|
||||
with open(path, "rb") as f:
|
||||
return ("", raw) if len(raw := f.read(64001)) <= 64000 else ("over 64,000 bytes", None)
|
||||
except (FileNotFoundError, NotADirectoryError):
|
||||
return "", None
|
||||
|
||||
|
||||
def agents_target(root):
|
||||
"""(real_path, rel_path, "") for `root/AGENTS.md` when safe, else (None, "", reason)."""
|
||||
agents, real_root = os.path.join(root, "AGENTS.md"), os.path.realpath(root)
|
||||
@@ -136,7 +150,7 @@ def agents_target(root):
|
||||
why = ("it is a dangling symlink" if link and not os.path.exists(agents) else "it is a directory" if os.path.isdir(agents)
|
||||
else "it is a symlink outside the project" if link and os.path.commonpath([real_root, real]) != real_root
|
||||
else "it is a symlink into " + rel.split(os.sep)[0] if link and rel.split(os.sep)[0] in (".git", ".sisi")
|
||||
else "it is not a regular file" if os.path.lexists(agents) and not os.path.isfile(agents) else "")
|
||||
else "it is " + issue if (issue := regular(real if link else agents)[0]) else "")
|
||||
return (None, "", why) if why else (real, rel, "")
|
||||
|
||||
|
||||
@@ -149,7 +163,7 @@ def snapshot(cwd):
|
||||
real, rel, _ = agents_target(top)
|
||||
spec = ["--", ":(top)", ":(top,exclude).sisi"] + ([":(top,exclude)" + rel] if rel else [])
|
||||
head, status, diff = (out if rc == 0 else ""), git(["status", "--porcelain"] + spec, cwd)[1], git(["diff", "HEAD"] + spec, cwd)[1]
|
||||
body = NOTE_RE.sub("", read(real)).rstrip("\r\n") if real and os.path.isfile(real) else ""
|
||||
body = NOTE_RE.sub("", (regular(real, True)[1] or b"").decode("utf-8", "replace") if real else "").rstrip("\r\n")
|
||||
return hashlib.sha1((head + status + diff + "\0" + body).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
@@ -173,12 +187,15 @@ def session(sid):
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def lock(key):
|
||||
"""Exclusive lock in the store for one project (or user)."""
|
||||
p = data("locks", "%s-%s.lock" % (os.path.basename(key) or "root", hashlib.sha1(key.encode()).hexdigest()[:8]))
|
||||
def lock(key, wait=True):
|
||||
"""Exclusive lock in the store for one project (or user); with wait=False, yields False if busy."""
|
||||
p, ok = data("locks", "%s-%s.lock" % (os.path.basename(key) or "root", hashlib.sha1(key.encode()).hexdigest()[:8])), True
|
||||
with open(p, "a") as f:
|
||||
fcntl.flock(f, fcntl.LOCK_EX)
|
||||
yield
|
||||
try:
|
||||
fcntl.flock(f, fcntl.LOCK_EX | (0 if wait else fcntl.LOCK_NB))
|
||||
except BlockingIOError:
|
||||
ok = False
|
||||
yield ok
|
||||
|
||||
|
||||
def current_session(cwd=None):
|
||||
|
||||
Reference in new issue
Block a user