diff --git a/sisi/rules.py b/sisi/rules.py index e16782c..3bda6ee 100644 --- a/sisi/rules.py +++ b/sisi/rules.py @@ -180,12 +180,8 @@ def scope_lines(scope, cwd=None, migrate=True): def _commit(msg, *paths, snap=None, put=None): - """Commit `paths` to the store. `put` ({path: text}) and the undo snapshot `snap` are written inside the store lock, with the commit.""" - if snap: - p = store.data("rules", "last-project.json") - paths, put = (p,) + paths, {**(put or {}), p: json.dumps(dict(zip(("path", "before", "after"), snap)))} - # written inside the store lock, never under a project's or the user's: another process's `git add` read these - # files as they were replaced ("short read while indexing") + # `put` and the undo snapshot are written inside the store lock: another process's `git add` read them mid-replace ("short read") + put = dict(put or {}, **({store.data("rules", "last-project.json"): json.dumps(dict(zip(("path", "before", "after"), snap)))} if snap else {})) if not store.commit(msg, *paths, put=put): raise OSError("store git commit failed (%s)" % store.GIT_ERROR) @@ -397,11 +393,10 @@ def organize_record(answer_file, cwd): seen = _organized() seen.update({_mark_key(USER): len(_retro(got[USER])), _mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))}) seen.pop("rules/projects/%s.md" % store.project_key(cwd), None) - marks = store.data("rules", "organized.json") dp, ts = store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S") for r, pn, why in recs: store.append(dp, json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True)) - _commit("rules organized", marks, up, *([dp] if recs else []), snap=(pp, before, after), put={up: utext, marks: json.dumps(seen)}) + _commit("rules organized", *([dp] if recs else []), snap=(pp, before, after), put={up: utext, store.data("rules", "organized.json"): json.dumps(seen)}) except OSError as e: (wrote_u := store.regular(up, True)[1] == utext.encode()) and build_rulebook() if not wrote and not wrote_u: diff --git a/sisi/store.py b/sisi/store.py index 4813a38..78aff25 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -20,6 +20,7 @@ def _where(own, xdg, fallback): DATA = _where("SISI_DATA", "XDG_DATA_HOME", (".local", "share")) STATE = _where("SISI_STATE", "XDG_STATE_HOME", (".local", "state")) LIB = os.environ.get("SISI_LIB") or os.path.join(HOME, ".local", "lib", "sisi") +GIT_ERROR = "" # why the last git call that failed did: the first line of its stderr, or the error # Every setting there is. The person overrides one under "core" in config.json in their store. DEFAULTS = {"gate": True, "meter": True, "direct_calls": 8, "direct_extension": 8, @@ -96,31 +97,26 @@ def append(path, line, once=False): (not once or len(raw) <= 64000 and b"\0" not in raw and line[:-1] not in raw.splitlines()) and f.write(line) -GIT_ERROR = "" # why the last git call that failed did: the first line of its stderr, or the error - - def git(args, cwd, timeout=15): # A repository named by the caller's environment (a git hook sets GIT_DIR) must not decide which project this folder is. - # No optional locks: a plain `git status` holds index.lock while it runs, and a commit started then fails on it. global GIT_ERROR env = {k: v for k, v in os.environ.items() if k not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR")} - env["GIT_OPTIONAL_LOCKS"] = "0" + env["GIT_OPTIONAL_LOCKS"] = "0" # a plain `git status` holds index.lock while it runs, and a commit started then fails on it try: r = subprocess.run(["git"] + args, cwd=cwd, capture_output=True, text=True, timeout=timeout, env=env) except (OSError, subprocess.SubprocessError) as e: - GIT_ERROR = str(e) - return 1, "" + r = subprocess.CompletedProcess(args, 1, "", str(e)) GIT_ERROR = (r.stderr.strip().partition("\n")[0] or "git exited with %d" % r.returncode) if r.returncode else "" return r.returncode, r.stdout def commit(message, *paths, put=None): - """One commit in the person's store holding only these paths, so the change can be undone on its own. - `put` ({path: text}) is written first, under the same lock: `git add` in another process never reads a file as it is replaced.""" + """One commit in the person's store holding only these paths, so the change can be undone on its own. `put` ({path: text}) + is written under the lock and committed too: another process's `git add` never reads a file as it is replaced.""" with lock("store"): os.path.isdir(os.path.join(DATA, ".git")) or git(["init", "-q"], DATA) [write(p, text) for p, text in (put or {}).items()] - rel = [os.path.relpath(p, DATA) for p in paths] + rel = [os.path.relpath(p, DATA) for p in (*paths, *(put or {}))] 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)) diff --git a/tests/test_core.py b/tests/test_core.py index 2ec3f4c..4d2fc9b 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -51,8 +51,8 @@ class Core(unittest.TestCase): before = tree() self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree")) book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md") - mine = open(book).read() if os.path.exists(book) else None - self.addCleanup(lambda: self.assertEqual(open(book).read() if os.path.exists(book) else None, mine, "a test wrote the person's own rules file")) + mine = self.read(book) if os.path.exists(book) else None + self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file")) self.tmp = tempfile.mkdtemp(prefix="sisi-test-") self.addCleanup(shutil.rmtree, self.tmp, True) self.data = os.path.join(self.tmp, "data")