Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions scripts/gate-coverage.toml
Original file line number Diff line number Diff line change
@@ -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"
118 changes: 79 additions & 39 deletions src/ub_cli/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand All @@ -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")

Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
72 changes: 50 additions & 22 deletions src/ub_cli/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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 = (("<!-- ub:begin -->", "<!-- ub: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)
Expand All @@ -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 ""
Expand All @@ -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'}")
Expand Down
Loading
Loading