diff --git a/sisi/rules.py b/sisi/rules.py index a866827..e06a361 100644 --- a/sisi/rules.py +++ b/sisi/rules.py @@ -213,16 +213,24 @@ _in_store = lambda p: p.startswith(os.path.join(store.DATA, "")) def _apply(msg, change, record): - """Write {path: (before, after)}, files outside the store first, then one store commit with `record`; a failed write undoes all.""" - try: - [store.write(p, a) for p, (b, a) in change.items() if not _in_store(p) and a is not None and a != b] - ok = store.commit(msg, put={**{p: a for p, (b, a) in change.items() if _in_store(p)}, store.data("rules", "last-project.json"): json.dumps(record)}) - except OSError: - for p, (b, a) in change.items(): + """Write {path: (before, after)}, files outside the store first, then one store commit with `record`; a failed write or commit restores every file before reporting.""" + rp = store.data("rules", "last-project.json") + backs = list(change.items()) + def _undo(): + for p, (b, a) in backs: with contextlib.suppress(OSError): store.write(p, b) if b is not None else os.path.lexists(p) and os.remove(p) + try: + backs.append((rp, (_text(rp), None))) + [store.write(p, a) for p, (b, a) in change.items() if not _in_store(p) and a is not None and a != b] + ok = store.commit(msg, put={**{p: a for p, (b, a) in change.items() if _in_store(p)}, rp: json.dumps(record)}) + except OSError: + _undo() raise - return "" if ok else "the change is made; it could not be recorded for undo: store git commit failed (%s)" % store.GIT_ERROR + if not ok: + _undo() + return "store git commit failed (%s)" % store.GIT_ERROR + return "" def _back(line, now, old, lv): @@ -456,12 +464,15 @@ def organize_record(answer_file, cwd): change[dp] = (old, _append(old, [json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True) for r, pn, why in recs])) [_check_writable(p) for p in change if change[p][1] is not None and (p != dp or os.path.islink(dp))] # the drops log may pass 64,000 bytes now, home = {USER: got[USER], PROJECT: got[PROJECT], CORE: core}, {USER: up, PROJECT: pp, CORE: cp} - back = [_back(l, home[lv], home[f], f) for lv in now for l in dict.fromkeys(now[lv]) for f in (USER, PROJECT) if f != lv and l in had[f] and l not in now[f] + had.get(lv, [])] + flat = [l for sec in now.values() for l in sec] + over = [l for l in dict.fromkeys(flat) if sum(l in sec for sec in now.values()) > 1] + merged = [l for l in dict.fromkeys(had[USER] + had[PROJECT]) if l in had[USER] and l in had[PROJECT] and 1 <= flat.count(l) < (had[USER] + had[PROJECT]).count(l)] + back = [_back(l, home[lv], home[f], f) for lv in now for l in dict.fromkeys(now[lv]) for f in (USER, PROJECT) if f != lv and l in had[f] and l not in now[f] + had.get(lv, []) and l not in over + merged] warn = _apply("rules organized" if proj else "rules organized (user only)", change, {"reverse": back} if back else {"path": pp, "before": before, "after": change[pp][1]} if proj else {}) except OSError as e: return "could not record the organized rules (%s)" % e - warn and print(warn.replace("the change is made", "the organized rules are in %s" % (pp or up))) + if warn: return "could not record the organized rules (%s); the files are restored, so run `sisi rules organize --record %s` again once the store is free" % (warn, answer_file) proj and change[pp][1] is not None and note(pp) with contextlib.suppress(OSError), store.lock("organize"): cl = {k: v for k, v in _organized(("locks", "organize.json")).items() @@ -471,6 +482,8 @@ def organize_record(answer_file, cwd): for scope in (USER, PROJECT): print("%s rules: %d lines (were %d)" % (scope, len(got[scope]), len(had[scope]))) no_why and print("%d dropped rule%s had no reason recorded" % (no_why, "" if no_why == 1 else "s")) + [print("the same rule was in both user and project and is now one copy in %s: %s; add it back by hand if you want it at both levels (run `sisi rules` to see the lists)" % (next(lv for lv in now if l in now[lv]), l)) for l in merged] + [print("the same rule now sits at two levels, so `sisi rules move` cannot pick one copy: %s; remove the copy you do not want by hand (run `sisi rules` to see the lists)" % l) for l in over if l not in merged] flags.strip() and print("Flagged for you (not changed):" + flags.rstrip()) back and print("Moved between levels, which `sisi rules revert` does not undo; to move them back, run:\n" + "\n".join(" " + c for c in back)) return None @@ -496,6 +509,8 @@ def revert(): if isinstance(snap, dict) and isinstance(snap.get("reverse"), list) and all(isinstance(c, str) for c in snap["reverse"]): print("to move them back, run:\n" + "\n".join(" " + c for c in snap["reverse"])) return "the last rule change, `%s`, moved rules between levels, which revert does not undo; the commands above move them back" % subject + if isinstance(snap, dict) and snap.get("final"): + return "the last rule change, `%s`, took the rule into canon/core.md, which is final and cannot be undone" % subject if snap != {} and (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"))): @@ -567,11 +582,13 @@ def move(args, cwd): return "--project needs the folder of a git repository (its root)" if len(args) != 2 or args[1] not in (CORE, USER, PROJECT, "canon"): return usage - start, to, to_cwd = args[0].strip().removeprefix("- ").strip(), args[1], top or cwd + start, to, to_cwd = " ".join(args[0].split()), args[1], top or cwd + forms = [f for f in ([start, start[2:]] if start.startswith("- ") else [start]) if f] homes = {path(lv, c): (lv, c) for lv, c in [(CORE, cwd), (USER, cwd)] + [(PROJECT, c) for c in (cwd, top) if c and has_project(c)]} - hits = [(p, lv, l) for p, (lv, c) in homes.items() for l in dict.fromkeys(scope_lines(lv, c) if lv == PROJECT else lines(p)) if l[2:].startswith(start)] if start else [] + hits = [(p, lv, l) for p, (lv, c) in homes.items() for l in dict.fromkeys(scope_lines(lv, c) if lv == PROJECT else lines(p)) if any(" ".join(l[2:].split()).startswith(f) for f in forms)] + hits = [h for h in hits if any(" ".join(h[2][2:].split()) == f for f in forms)] or hits if len(hits) != 1: - return "no rule line starts with that" if not hits else "more than one rule starts with that; give more of it:\n" + "\n".join(" [%s] %s" % (lv, l) for _, lv, l in hits) + return "no rule line starts with that; run `sisi rules` to see the rules" if not hits else "more than one rule starts with that; give more of it:\n" + "\n".join(" [%s] %s" % (lv, l) for _, lv, l in hits) src, lv, line = hits[0] dst = path(to, to_cwd) if to != "canon" else None if to == "canon" and lv != CORE: @@ -591,12 +608,13 @@ def move(args, cwd): change = {src: (b_src, "".join(keep))} dst and change.update({dst: (b_dst, b_dst if line in _parse(b_dst or "") else _append(b_dst, [line]))}) back = dst and _back(line, dst, src, lv) - warn = _apply("rule moved (%s to %s)" % (lv, to), change, {"reverse": [back]} if dst else {}) + warn = _apply("rule moved (%s to %s)" % (lv, to), change, {"reverse": [back]} if dst else {"final": "canon"}) except OSError as e: return "could not move it (%s)" % e + if warn: return "could not move it (%s); the files are restored, so run it again once the store is free: sisi rules move %s %s%s" % (warn, shlex.quote(args[0]), args[1], " --project " + shlex.quote(top) if top else "") to == PROJECT and note(dst) build_rulebook() - print(warn or ("moved to %s: %s\nto move it back (`sisi rules revert` does not undo a move), run:\n %s" % (to, line, back) if dst else "removed from the product queue: %s" % line)) + print("moved to %s: %s\nto move it back (`sisi rules revert` does not undo a move), run:\n %s" % (to, line, back) if dst else "removed from the product queue into canon/core.md, which is final: %s" % line) return None diff --git a/tests/test_core.py b/tests/test_core.py index d555ac4..00d30a4 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1434,7 +1434,7 @@ cli.main(["tick"]) self.assertIn("could not be recorded for undo", out) self.assertNotIn("Nothing was changed", out) - def test_failed_store_commit_reports_failure_and_blocks_older_revert(self): + def test_failed_store_commit_restores_files_and_reports_failure(self): self.assertEqual(self.sisi("learn", "--level", "user", "Older user rule that revert must not silently undo")[0], 0) lock = self.write(os.path.join(self.data, ".git", "index.lock"), "") rc, out, err = self.sisi("learn", "--project", "Project rule while index lock blocks commit") @@ -1456,13 +1456,15 @@ cli.main(["tick"]) "## project\n" + self.read(beta, ".sisi", "rules.md") + "- Organized beta rule [retro 2026-11-24]\n") lock = self.write(os.path.join(self.data, ".git", "index.lock"), "") rc_org, out_org, err_org = self.sisi("rules", "organize", "--record", ans, cwd=beta) - self.assertEqual((rc_org, err_org), (0, ""), out_org) - self.assertIn("could not be recorded for undo", out_org) - self.assertIn("Organized beta rule", self.read(beta, ".sisi", "rules.md")) + self.assertEqual(rc_org, 1, out_org) + self.assertIn("sisi rules organize --record", out_org) + self.assertNotIn("Organized beta rule", self.read(beta, ".sisi", "rules.md")) + self.assertEqual(subprocess.run(["git", "status", "--porcelain", "--", "rules"], cwd=self.data, capture_output=True, text=True).stdout, "") os.remove(lock) + # the failed organize left nothing behind, so revert undoes the last committed change (gamma's learn), as usual rc_rev2, out_rev2, _ = self.sisi("rules", "revert") - self.assertNotEqual(rc_rev2, 0, out_rev2) - self.assertIn("Rule in gamma that revert must not undo", self.read(gamma, ".sisi", "rules.md")) + self.assertEqual(rc_rev2, 0, out_rev2) + self.assertFalse(os.path.exists(os.path.join(gamma, ".sisi", "rules.md"))) def test_retro_inside_dot_git_names_the_folder_when_it_cannot_write(self): dot_git = os.path.join(self.proj, ".git") @@ -4085,6 +4087,46 @@ cli.main(["tick"]) self.assertEqual(self.read(self.data, "rules", "user.md"), before) self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi"))) + def test_move_prefers_the_exact_line_when_one_rule_is_a_prefix_of_another(self): # undo review A + self.user_file("- Check logs\n") + self.write(os.path.join(self.data, "rules", "core.md"), "- Check logs in CI\n") + rc, out, _ = self.sisi("rules", "move", "Check logs", "project") + self.assertEqual(rc, 0, out) + self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), "- Check logs\n") + self.assertEqual(self.read(self.data, "rules", "core.md"), "- Check logs in CI\n") + self.assertEqual(self.run_back(out), 1) + self.assertEqual(self.read(self.data, "rules", "user.md"), "- Check logs\n") + + def test_move_runs_the_command_learn_suggests_for_a_text_starting_with_a_dash(self): # undo review B + self.assertEqual(self.sisi("learn", "--level", "user", "- always verify first")[0], 0) + line = self.read(self.data, "rules", "user.md") + rc, out, _ = self.sisi("rules", "move", "- always verify first", "project") + self.assertEqual(rc, 0, out) + self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), line) + self.assertEqual(self.run_back(out), 1) + self.assertEqual(self.read(self.data, "rules", "user.md"), line) + + def test_move_matches_a_line_with_two_spaces_after_the_dash(self): # undo review B + self.user_file("- two spaces after dash [owner 2026-11-20]\n") + rc, out, _ = self.sisi("rules", "move", "two spaces after dash", "project") + self.assertEqual(rc, 0, out) + self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), "- two spaces after dash [owner 2026-11-20]\n") + self.assertEqual(self.read(self.data, "rules", "user.md"), "") + + def test_move_with_a_blocked_store_commit_moves_nothing_and_leaves_no_trace(self): # undo review E + self.assertEqual(self.sisi("learn", "--level", "user", "A user rule that fails to move cleanly")[0], 0) + before_user = self.read(self.data, "rules", "user.md") + lock = self.write(os.path.join(self.data, ".git", "index.lock"), "") + rc, out, _ = self.sisi("rules", "move", "A user rule that fails", "project") + self.assertEqual(rc, 1, out) + self.assertIn("sisi rules move", out) + self.assertIn("Nothing was changed", out) + self.assertEqual(self.read(self.data, "rules", "user.md"), before_user) + self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi", "rules.md"))) + self.assertEqual(subprocess.run(["git", "status", "--porcelain", "--", "rules"], cwd=self.data, capture_output=True, text=True).stdout, "") + os.remove(lock) + self.assertEqual(self.sisi("rules", "move", "A user rule that fails", "project")[0], 0) + def test_organize_moves_an_owner_line_across_levels_but_never_rewords_it(self): mine = "- Words about this one project [owner 2026-11-20]" self.user_file(mine + "\n") @@ -4101,6 +4143,36 @@ cli.main(["tick"]) self.assertIn("owner rule missing or changed", out) self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), mine + "\n") + def test_organize_says_when_identical_rules_from_two_levels_become_one(self): # undo review C + l = "- Shared retro line [retro 2026-11-20]" + self.user_file(l + "\n- Other user rule [retro 2026-11-20]\n") + self.mkdir(self.proj, ".sisi") + self.write(os.path.join(self.proj, ".sisi", "rules.md"), l + "\n") + user_before = self.read(self.data, "rules", "user.md") + proj_before = self.read(self.proj, ".sisi", "rules.md") + ans = self.write(os.path.join(self.tmp, "shared.md"), "## user\n- Other user rule [retro 2026-11-20]\n## project\n## core\n%s\n" % l) + rc, out, _ = self.sisi("rules", "organize", "--record", ans) + self.assertEqual(rc, 0, out) + self.assertIn("both user and project", out) + self.assertNotIn("to move them back", out) + self.assertEqual(self.read(self.data, "rules", "core.md"), l + "\n") + self.assertEqual(self.sisi("rules", "revert")[0], 0) + self.assertEqual(self.read(self.data, "rules", "user.md"), user_before) + self.assertEqual(self.read(self.proj, ".sisi", "rules.md"), proj_before) + + def test_organize_says_when_one_rule_is_filed_at_two_levels(self): # undo review C + l = "- Split owner line [owner 2026-11-20]" + self.user_file(l + "\n") + user_before = self.read(self.data, "rules", "user.md") + ans = self.write(os.path.join(self.tmp, "split.md"), "## user\n## project\n%s\n## core\n%s\n" % (l, l)) + rc, out, _ = self.sisi("rules", "organize", "--record", ans) + self.assertEqual(rc, 0, out) + self.assertIn("two levels", out) + self.assertNotIn("to move them back", out) + self.assertEqual(self.sisi("rules", "revert")[0], 0) + self.assertEqual(self.read(self.data, "rules", "user.md"), user_before) + self.assertFalse(os.path.exists(os.path.join(self.data, "rules", "core.md"))) + def test_the_level_audit_becomes_due_by_a_retro_count(self): self.user_file("- A user rule [retro 2026-11-20]\n") os.makedirs(self.data, exist_ok=True) @@ -4291,6 +4363,17 @@ cli.main(["tick"]) self.assertIn("rules move", help_text) self.assertTrue("sisi learn --level" in self.read(REPO, "canon", "core.md")) + def test_move_to_canon_is_final_and_revert_says_so(self): # undo review D + self.assertEqual(self.sisi("learn", "--level", "core", "Every sisi user should see this line")[0], 0) + rc, out, _ = self.sisi("rules", "move", "Every sisi user", "canon") + self.assertEqual(rc, 0, out) + self.assertIn("final", out) + self.assertEqual(self.read(self.data, "rules", "core.md"), "") + rc, out, _ = self.sisi("rules", "revert") + self.assertEqual(rc, 1) + self.assertIn("final", out) + self.assertEqual(self.read(self.data, "rules", "core.md"), "") + def test_option_edge_cases_are_parsed_or_refused(self): # finding 9 rc, out, _ = self.sisi("learn", "Always check this first", "--means", "check it every time", "--level", "user") self.assertEqual(rc, 0, out) @@ -4416,7 +4499,7 @@ cli.main(["tick"]) def test_the_product_stays_small(self): code = sum(len(self.read(p).splitlines()) for p in glob.glob(os.path.join(REPO, "sisi", "*.py"))) - self.assertLessEqual(code, 2426, "sisi is two loops. If it needs more than this, find the simpler shape.") + self.assertLessEqual(code, 2444, "sisi is two loops. If it needs more than this, find the simpler shape.") rulebook = self.read(REPO, "canon", "core.md") self.assertLess(len(rulebook.splitlines()), 139) self.assertLessEqual(len(rulebook), 10711)