diff --git a/Makefile b/Makefile index 7a62559..851fde1 100644 --- a/Makefile +++ b/Makefile @@ -22,8 +22,16 @@ test: $(RUN) python -m unittest discover -s tests -v # scripts/ is release tooling, out of the gate's scope; see README. +COVERAGE = $(RUN) --with coverage==7.17.4 python -m coverage +COVERAGE_RC = --rcfile=scripts/gate-coverage.toml +GATE_COVERAGE = mkdir -p target/coverage/python && rm -f target/coverage/python/.coverage-gate* \ + && $(COVERAGE) run $(COVERAGE_RC) -m unittest discover -s tests -q \ + && $(COVERAGE) combine $(COVERAGE_RC) -q \ + && $(COVERAGE) lcov $(COVERAGE_RC) -q -o target/coverage/python/lcov.info + gate: - $(RUN) ub check -s src --test-command '$(RUN) python -m unittest discover -s tests -q' + $(RUN) ub check -s src --coverage-command '$(GATE_COVERAGE)' \ + --test-command '$(RUN) python -m unittest discover -s tests -q' build: $(UV) build --wheel --python $(PYTHON_VERSION) diff --git a/README.md b/README.md index 6bdab58..a8edc1e 100644 --- a/README.md +++ b/README.md @@ -332,7 +332,9 @@ the mutated copy. Run `make test` for the test suite and `make build-native` to produce the archive for the current machine under `dist/`. `make build` builds the Python -wheel. `make gate` runs this checkout's `ub check` on `src/`. The CI workflow +wheel. `make gate` runs this checkout's `ub check` on `src/`. Its coverage run +also measures the child processes the hook and init tests start +(`scripts/gate-coverage.toml`), so that code counts as covered. The CI workflow runs `make test` and the vendored-tree check below as the `test` job, and `make gate` as the `gate` job, on every pull request and every push to `main`. The gate leaves out `scripts/`, the release tooling. Its one script with real diff --git a/scripts/gate-coverage.toml b/scripts/gate-coverage.toml new file mode 100644 index 0000000..ccf5b97 --- /dev/null +++ b/scripts/gate-coverage.toml @@ -0,0 +1,7 @@ +# Coverage for `make gate`. The hook and init tests run ub in child processes, +# so the gate measures subprocesses and combines their data before the report. +[tool.coverage.run] +patch = ["subprocess"] +parallel = true +source = ["src"] +data_file = "target/coverage/python/.coverage-gate" diff --git a/src/ub_cli/hooks.py b/src/ub_cli/hooks.py index 46cfaa4..d5ab5bb 100644 --- a/src/ub_cli/hooks.py +++ b/src/ub_cli/hooks.py @@ -60,42 +60,62 @@ def hook_path(root: Path) -> Path: return path if path.is_absolute() else root / path -def install_git(root: Path) -> None: +def checked_hook(root: Path) -> Path: + """The pre-push hook path, refused when it is outside the repository or not a plain file.""" + hook = hook_path(root) common = Path(git(root, "rev-parse", "--path-format=absolute", "--git-common-dir")) if not (hook.resolve().is_relative_to(root) or hook.resolve().is_relative_to(common)): raise ValueError("Git hooks directory is outside this repository. Integrate ./.ub/check in that hook manually.") if hook.is_symlink() or (hook.exists() and not hook.is_file()): raise ValueError(f"Cannot wrap a symlink or non-file hook: {hook}") + return hook + + +def refresh_block(hook: Path, original: str) -> None: + """Keep an installed UB block, upgrading the previous release's block.""" + + if original.count(LEGACY_GIT_CHECK) == 1: + write_file(hook, original.replace(LEGACY_GIT_CHECK, GIT_CHECK), 0o755) + return + if original.count(GIT_CHECK) != 1: + raise ValueError(f"Edited UB hook block needs review: {hook}") + hook.chmod(0o755) + + +def wrapped(hook: Path, original: str) -> str: + """The hook with the UB block first. An executable original must be a shell script.""" + + if not (hook.exists() and os.access(hook, os.X_OK)): + return "#!/bin/sh\n" + GIT_CHECK + first, _, rest = original.partition("\n") + interpreter = shlex.split(first[2:]) if first.startswith("#!") else [] + if interpreter and Path(interpreter[0]).name == "env": + interpreter = interpreter[1:] + if not interpreter or Path(interpreter[0]).name not in {"sh", "bash", "dash", "ksh", "zsh"}: + raise ValueError(f"Existing hook is not a supported shell script: {hook}. Add ./.ub/check to it manually.") + # The original still runs at its original path, with its argv and stdin intact. + return first + "\n" + GIT_CHECK + rest + + +def install_git(root: Path) -> None: + hook = checked_hook(root) original = hook.read_text() if hook.exists() else "" if "# ub:begin" in original or "# ub:end" in original: - if original.count(LEGACY_GIT_CHECK) == 1: - write_file(hook, original.replace(LEGACY_GIT_CHECK, GIT_CHECK), 0o755) - return - if original.count(GIT_CHECK) != 1: - raise ValueError(f"Edited UB hook block needs review: {hook}") - hook.chmod(0o755) + refresh_block(hook, original) return backup = hook.with_name("pre-push.ub-original") if backup.exists() or backup.is_symlink(): raise ValueError(f"Existing hook backup needs review: {backup}") - script = "#!/bin/sh\n" + GIT_CHECK - if hook.exists() and os.access(hook, os.X_OK): - first, _, rest = original.partition("\n") - interpreter = shlex.split(first[2:]) if first.startswith("#!") else [] - if interpreter and Path(interpreter[0]).name == "env": - interpreter = interpreter[1:] - if not interpreter or Path(interpreter[0]).name not in {"sh", "bash", "dash", "ksh", "zsh"}: - raise ValueError(f"Existing hook is not a supported shell script: {hook}. Add ./.ub/check to it manually.") - # The original still runs at its original path, with its argv and stdin intact. - script = first + "\n" + GIT_CHECK + rest + script = wrapped(hook, original) if hook.exists(): os.link(hook, backup) write_file(hook, script, 0o755) -def install_agent(root: Path, target: str, timeout: int) -> None: - path = local_file(root, AGENT_FILES[target]) +def stop_groups(path: Path) -> tuple[dict, list]: + """The settings in `path` and their Stop hook groups, created when absent.""" + data = json.loads(path.read_text()) if path.exists() else {} if not isinstance(data, dict): raise ValueError(f"Expected a JSON object in {path}") @@ -105,20 +125,36 @@ def install_agent(root: Path, target: str, timeout: int) -> None: groups = hooks.setdefault("Stop", []) if not isinstance(groups, list): raise ValueError(f"Expected a Stop array in {path}") - command = (f"ub hooks run stop --timeout {timeout} || " - "{ printf '%s\\n' 'UB hook could not start. Ensure ub is installed and on PATH.' >&2; exit 2; }") - handler = {"type": "command", "command": command, "timeout": timeout + 10} + return data, groups + + +def installed_handler(path: Path, groups: list) -> dict | None: + """The existing UB Stop handler, if any. Malformed groups and handlers are refused.""" + for group in groups: if not isinstance(group, dict) or not isinstance(group.get("hooks"), list): raise ValueError(f"Invalid Stop hook group in {path}") for existing in group["hooks"]: if not isinstance(existing, dict): raise ValueError(f"Invalid Stop hook handler in {path}") - existing_command = existing.get("command") - if existing.get("type") == "command" and isinstance(existing_command, str) and existing_command.startswith("ub hooks run stop --timeout "): - if existing != handler: - raise ValueError(f"UB hook already differs in {path}; edit it directly.") - return + command = existing.get("command") + if (existing.get("type") == "command" and isinstance(command, str) + and command.startswith("ub hooks run stop --timeout ")): + return existing + return None + + +def install_agent(root: Path, target: str, timeout: int) -> None: + path = local_file(root, AGENT_FILES[target]) + data, groups = stop_groups(path) + command = (f"ub hooks run stop --timeout {timeout} || " + "{ printf '%s\\n' 'UB hook could not start. Ensure ub is installed and on PATH.' >&2; exit 2; }") + handler = {"type": "command", "command": command, "timeout": timeout + 10} + existing = installed_handler(path, groups) + if existing is not None: + if existing != handler: + raise ValueError(f"UB hook already differs in {path}; edit it directly.") + return groups.append({"hooks": [handler]}) write_file(path, json.dumps(data, indent=2) + "\n") @@ -140,23 +176,27 @@ def install(options) -> int: return 0 +def descendants(root: int) -> set[int]: + """`root` and every process below it, from the system process table.""" + + # int() reads the byte strings directly. + table = subprocess.run(["ps", "-e", "-o", "pid=", "-o", "ppid="], capture_output=True, check=True) + parents = {int(pid): int(parent) for pid, parent in (line.split() for line in table.stdout.splitlines())} + found = {root} + while True: + children = {pid for pid, parent in parents.items() if parent in found} + if not children - found: + return found + found.update(children) + + def terminate_check(process) -> None: """Stop the check and descendants, including tests that start new sessions.""" stopped = set() try: os.killpg(process.pid, signal.SIGSTOP) while True: - # int() reads the byte strings directly. - table = subprocess.run(["ps", "-e", "-o", "pid=", "-o", "ppid="], capture_output=True, check=True) - parents = {int(pid): int(parent) for pid, parent in - (line.split() for line in table.stdout.splitlines())} - descendants = {process.pid} - while True: - children = {pid for pid, parent in parents.items() if parent in descendants} - if not children - descendants: - break - descendants.update(children) - new = descendants - stopped + new = descendants(process.pid) - stopped if not new: break for pid in new: @@ -256,7 +296,7 @@ def run(argv: list[str]) -> int: except SystemExit as exc: return int(exc.code) try: - if getattr(options, "timeout", 1) < 1: + if options.timeout < 1: raise ValueError("--timeout requires a positive integer") if options.command == "install": return install(options) diff --git a/src/ub_cli/project.py b/src/ub_cli/project.py index e96bbea..00bd392 100644 --- a/src/ub_cli/project.py +++ b/src/ub_cli/project.py @@ -26,6 +26,9 @@ """ +COMMAND_FLAGS = ("coverage_command", "test_command", "max_workers") + + def git(root: Path, *args: str) -> str: result = subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True) if result.returncode: @@ -46,13 +49,21 @@ def local_file(root: Path, name: str) -> Path: return path +def appended(text: str, block: str) -> str: + """`block` after `text`, separated by a blank line.""" + + if not text: + return block + return text + ("\n" if text.endswith("\n") else "\n\n") + block + + def managed_block(text: str, body: str, *, markdown: bool) -> str: start, end = (("", "") if markdown else ("# ub:begin", "# ub:end")) block = f"{start}\n{body.rstrip()}\n{end}\n" if start not in text and end not in text: - return text + ("\n\n" if text and not text.endswith("\n") else "\n" if text else "") + block - if text.count(start) != 1 or text.count(end) != 1 or text.index(start) > text.index(end): + return appended(text, block) + if text.count(start) != 1 or text.count(end) != 1 or end in text.split(start, 1)[0]: raise ValueError("Malformed UB markers; repair the ub:begin/ub:end block first.") before, rest = text.split(start, 1) _, after = rest.split(end, 1) @@ -77,38 +88,39 @@ def write_file(path: Path, data: str, mode: int | None = None) -> None: temporary.unlink(missing_ok=True) -def initialize(options) -> None: - from ub_cli.ratchet import ratchet_file, render, scan, tally, toplevel +def check_command(root: Path, options) -> list[str]: + """`ub check` with the options' source roots and commands as literal arguments.""" - root = options.root.resolve() - if not root.is_dir(): - raise ValueError(f"Project root is not a directory: {root}") command = ["ub", "check"] for source in options.source_root: path = (root / source).resolve() if not path.is_relative_to(root) or not path.is_dir(): raise ValueError(f"Source root must be a directory inside the project: {source}") command.extend(["-s", "./" + path.relative_to(root).as_posix()]) - for flag in ("coverage_command", "test_command", "max_workers"): + for flag in COMMAND_FLAGS: value = getattr(options, flag) if value is not None: command.extend(["--" + flag.replace("_", "-"), str(value)]) - check = local_file(root, ".ub/check") + return command + + +def check_script(root: Path, check: Path, options) -> str: + """The .ub/check script. An existing one is kept; explicit options must match it.""" + script = ('#!/bin/sh\nset -eu\n' 'cd -- "$(CDPATH=\'\' cd -- "$(dirname -- "$0")/.." && pwd)"\n' - f'exec {shlex.join(command)} "$@"\n') - customized = options.source_root or any(getattr(options, flag) is not None for flag in - ("coverage_command", "test_command", "max_workers")) - if check.exists(): - if customized and check.read_text() != script: - raise ValueError(".ub/check already differs; edit it directly to change the project commands.") - script = check.read_text() - pending = {check: (script, 0o755)} - top = toplevel(root) - ratchet = top and ratchet_file(top) - if ratchet and not ratchet.exists(): - pending[ratchet] = (render(tally(scan(top)), []), None) - generated = [".ub/check"] + ([os.path.relpath(ratchet, root)] if ratchet else []) + f'exec {shlex.join(check_command(root, options))} "$@"\n') + customized = options.source_root or any(getattr(options, flag) is not None for flag in COMMAND_FLAGS) + if not check.exists(): + return script + if customized and check.read_text() != script: + raise ValueError(".ub/check already differs; edit it directly to change the project commands.") + return check.read_text() + + +def add_instructions(root: Path, pending: dict) -> None: + """Queue the managed blocks for AGENTS.md, CLAUDE.md, and .gitignore.""" + for name in ("AGENTS.md", "CLAUDE.md", ".gitignore"): path = local_file(root, name) text = path.read_text() if path.exists() else "" @@ -117,6 +129,22 @@ def initialize(options) -> None: if path in pending and pending[path] != (content, None): raise ValueError(f"Setup files resolve to the same path: {path}") pending[path] = (content, None) + + +def initialize(options) -> None: + from ub_cli.ratchet import ratchet_file, render, scan, tally, toplevel + + root = options.root.resolve() + if not root.is_dir(): + raise ValueError(f"Project root is not a directory: {root}") + check = local_file(root, ".ub/check") + pending = {check: (check_script(root, check, options), 0o755)} + top = toplevel(root) + ratchet = top and ratchet_file(top) + if ratchet and not ratchet.exists(): + pending[ratchet] = (render(tally(scan(top)), []), None) + generated = [".ub/check"] + ([os.path.relpath(ratchet, root)] if ratchet else []) + add_instructions(root, pending) for path, (data, mode) in pending.items(): write_file(path, data, mode) print(f"Ready: {root / '.ub/check'}") diff --git a/tests/test_project.py b/tests/test_project.py index 5b5cb1f..c3c8f74 100644 --- a/tests/test_project.py +++ b/tests/test_project.py @@ -1,3 +1,5 @@ +import contextlib +import io import json import os from pathlib import Path @@ -21,7 +23,8 @@ def setUp(self): self.bin = Path(temporary.name) / "bin" self.bin.mkdir() self.env = dict(os.environ, PATH=str(self.bin) + os.pathsep + os.environ["PATH"], - PYTHONPATH=str(Path(ub_cli.__file__).resolve().parent.parent)) + # Not resolved: mutation workers link unmutated files to the original tree. + PYTHONPATH=str(Path(ub_cli.__file__).absolute().parent.parent)) self.executable(self.bin / "ub", f"exec {shlex.quote(sys.executable)} -c 'from ub_cli.cli import main; main()' \"$@\"\n") self.git("init", "-q") @@ -413,6 +416,75 @@ def test_a_failing_ps_is_an_error_not_a_partial_kill(self): stop_decision({"cwd": str(self.root)}, 1) +class InstallTests(RepositoryTests): + def run_hooks(self, *args): + from ub_cli.hooks import run + + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = run([*args, *(["--root", str(self.root)] if args[:1] == ("install",) else [])]) + return code, out.getvalue() + err.getvalue() + + def test_usage_errors_and_a_non_executable_check(self): + for args in ((), ("run",)): + with self.subTest(args=args): + self.assertEqual(self.run_hooks(*args)[0], 2) + check = self.initialize() + self.assertEqual(self.run_hooks("install", "--timeout", "0"), + (1, "ub hooks: --timeout requires a positive integer\n")) + check.chmod(0o644) + self.assertEqual(self.run_hooks("install"), (1, "ub hooks: Run ub init at the repository root before installing hooks.\n")) + check.chmod(0o755) + self.assertEqual(self.run_hooks("install", "--timeout", "1")[0], 0) + + def test_refuses_symlinked_hooks_and_stray_markers(self): + self.initialize() + hook = self.root / ".git/hooks/pre-push" + target = self.root / ".git/hooks/hook-target" + target.write_text("#!/bin/sh\n") + hook.symlink_to(target) + self.assertIn("Cannot wrap a symlink", self.run_hooks("install")[1]) + hook.unlink() + self.executable(hook, "# ub:end\n") + self.assertIn("Edited UB hook block needs review", self.run_hooks("install")[1]) + + def test_env_shebang_hooks_are_wrapped(self): + self.initialize() + hook = self.root / ".git/hooks/pre-push" + self.executable(hook, "") + hook.write_text("#!/usr/bin/env bash\necho original\n") + self.assertEqual(self.run_hooks("install")[0], 0) + self.assertIn("# ub:begin", hook.read_text()) + + def test_agent_handler_timeout_and_malformed_groups(self): + self.initialize() + settings = self.root / ".claude/settings.json" + self.assertEqual(self.run_hooks("install", "--target", "claude", "--timeout", "7")[0], 0) + self.assertEqual(json.loads(settings.read_text())["hooks"]["Stop"][0]["hooks"][0]["timeout"], 17) + settings.write_text(json.dumps({"hooks": {"Stop": [{"hooks": "x"}]}})) + self.assertIn("Invalid Stop hook group", self.run_hooks("install", "--target", "claude")[1]) + + +class InitUnitTests(unittest.TestCase): + def test_managed_block_rejects_duplicate_or_reversed_markers(self): + from ub_cli.project import managed_block + + begin, end = "", "" + self.assertEqual(managed_block("a\n", "x", markdown=True), f"a\n\n{begin}\nx\n{end}\n") + self.assertEqual(managed_block("a", "x", markdown=True), f"a\n\n{begin}\nx\n{end}\n") + for text in (f"{begin}{begin}{end}", f"{begin}{end}{end}", f"{end}\n{begin}"): + with self.subTest(text=text), self.assertRaisesRegex(ValueError, "Malformed UB markers"): + managed_block(text, "x", markdown=True) + + def test_max_workers_must_be_positive(self): + from ub_cli.project import run + + with tempfile.TemporaryDirectory() as directory: + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(run(["--root", directory, "--max-workers", "0"]), 1) + self.assertEqual(run(["--root", directory, "--max-workers", "1"]), 0) + + class WriteFileTests(unittest.TestCase): def test_creates_parents_and_rewrites_only_changed_content(self): from ub_cli.project import write_file @@ -423,6 +495,9 @@ def test_creates_parents_and_rewrites_only_changed_content(self): self.assertEqual((path.read_text(), path.stat().st_mode & 0o777), ("one\n", 0o755)) write_file(path, "two\n") self.assertEqual((path.read_text(), path.stat().st_mode & 0o777), ("two\n", 0o755)) + path.chmod(0o644) + write_file(path, "two\n", 0o755) + self.assertEqual(path.stat().st_mode & 0o777, 0o755) class StopDecisionTests(RepositoryTests):