mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-24 21:26:28 +01:00
Compare commits
No commits in common. "e376660ab056c43c4fa10f617ef5385cb24b58a8" and "3f7af48a2b11ea1cf392a6d6de829f55358ce15f" have entirely different histories.
e376660ab0
...
3f7af48a2b
@ -37,8 +37,9 @@ WAKE_MINUTES: Final = 7 * 60
|
||||
# From this day the Anki earner is retired and Automation is paid per tutor
|
||||
# block (``earned_time._policy.AUTOMATION_TUTOR``). The day after the deploy
|
||||
# (0.6.1, 2026-10-09) -- never the deploy day itself (a same-day cut,
|
||||
# 2026-09-26). Confirmed in 0.7.0 (``confirmed_on`` 2026-10-09, kuhy's call
|
||||
# on 2026-10-10), so its penalty bites from this day on.
|
||||
# 2026-09-26). The tutor is still unconfirmed (no ``confirmed_on``), so given
|
||||
# ``first_credits`` it costs nothing -- neither gaming base nor ladder floor
|
||||
# -- until the day after it first pays out.
|
||||
TUTOR_FROM: Final = date(2026, 10, 10)
|
||||
# From this day until TUTOR_FROM the Anki and old Automation earners are
|
||||
# waived: neither penalised nor paid, since both are being retired and the
|
||||
@ -58,7 +59,7 @@ class Rung:
|
||||
first: Shutdown minutes the first unit earns.
|
||||
extra: Each further unit (counted earners) once ``steps`` run out.
|
||||
steps: What the second, third, ... unit earn, in order, when they are
|
||||
not all the same.
|
||||
not all the same (the tutor's 13/13/12/12 split).
|
||||
"""
|
||||
|
||||
first: int
|
||||
@ -94,15 +95,13 @@ LADDER: Final[Mapping[str, Rung]] = MappingProxyType(
|
||||
|
||||
|
||||
# From ``TUTOR_FROM``: Anki's 25 folded into Automation's, which is paid per
|
||||
# 15-minute tutor block. Each block earns the 15 minutes it costs (the fairness
|
||||
# rule; 13/13/12/12 paid 50 for 60 sat), so the rungs sum to 250: doing
|
||||
# everything is still 23:00, doing nothing 18:50.
|
||||
# 15-minute tutor block. Still sums to 240, so doing everything is 23:00.
|
||||
TUTOR_LADDER: Final[Mapping[str, Rung]] = MappingProxyType(
|
||||
{
|
||||
"workout": Rung(110),
|
||||
"leetcode": Rung(50),
|
||||
"reading": Rung(30),
|
||||
"automation": Rung(15, extra=15),
|
||||
"automation": Rung(13, steps=(13, 12, 12)),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@ -204,18 +204,14 @@ AUTOMATION_TUTOR: Final = Earner(
|
||||
extra_gaming_minutes=15,
|
||||
max_units=4,
|
||||
# Pre-ladder values, unused (TUTOR_FROM is not before LADDER_FROM); the
|
||||
# ladder pays 15 per block (``TUTOR_LADDER``).
|
||||
shutdown_minutes=15,
|
||||
extra_shutdown_minutes=15,
|
||||
# ladder pays 13/13/12/12 (``TUTOR_LADDER``).
|
||||
shutdown_minutes=13,
|
||||
extra_shutdown_minutes=13,
|
||||
kind="counted",
|
||||
penalty_from=TUTOR_FROM,
|
||||
ledger=".local/share/automation_tutor/ledger.json",
|
||||
match=tutor_match,
|
||||
missing_ledger_is_no=True,
|
||||
# Confirmed by kuhy on 2026-10-10 before any block had paid out, dated the
|
||||
# day before so the -60 gaming penalty applies on TUTOR_FROM itself
|
||||
# (penalty starts at confirmed_on + 1).
|
||||
confirmed_on=date(2026, 10, 9),
|
||||
)
|
||||
|
||||
# The registry of every day before ``TUTOR_FROM``. Order is the order of
|
||||
|
||||
@ -106,29 +106,21 @@ def test_omitting_first_credits_keeps_0_6_0_on_the_real_registries(
|
||||
assert base_for(day, registry).shutdown_minutes == _head_floor(day, earners)
|
||||
|
||||
|
||||
def _unconfirmed() -> tuple[Earner, ...]:
|
||||
"""The tutor day's registry as it was before 0.7.0 confirmed the tutor."""
|
||||
tutor = replace(AUTOMATION_TUTOR, confirmed_on=None)
|
||||
return (*earners_for(TUTOR_FROM)[:-1], tutor)
|
||||
|
||||
|
||||
def test_a_never_paid_unconfirmed_tutor_spares_the_first_tutor_day() -> None:
|
||||
def test_a_never_paid_tutor_spares_the_first_tutor_day() -> None:
|
||||
assert TUTOR_FROM == LADDER_FROM == date(2026, 10, 10)
|
||||
registry = _unconfirmed()
|
||||
base = base_for(TUTOR_FROM, registry, first_credits=REAL)
|
||||
base = base_for(TUTOR_FROM, first_credits=REAL)
|
||||
assert (base.gaming_minutes, _hhmm(base.shutdown_minutes)) == (240, "19:50")
|
||||
full = resolve(
|
||||
{"workout": 1, "leetcode": 1, "reading": 1, "automation": 4},
|
||||
TUTOR_FROM,
|
||||
registry,
|
||||
first_credits=REAL,
|
||||
)
|
||||
assert (full.gaming_minutes, _hhmm(full.shutdown_minutes)) == (480, "23:00")
|
||||
# Unwired consumer (no first_credits): the tutor is cut from penalty_from.
|
||||
fallback = base_for(TUTOR_FROM, registry)
|
||||
fallback = base_for(TUTOR_FROM)
|
||||
assert (fallback.gaming_minutes, _hhmm(fallback.shutdown_minutes)) == (
|
||||
180,
|
||||
"18:50",
|
||||
"19:00",
|
||||
)
|
||||
|
||||
|
||||
@ -136,24 +128,17 @@ def test_the_floor_waits_for_the_day_after_the_first_block() -> None:
|
||||
paid = REAL | {"automation": TUTOR_FROM}
|
||||
for day, gaming, floor in (
|
||||
(TUTOR_FROM, 240, "19:50"),
|
||||
(TUTOR_FROM + DAY, 180, "18:50"),
|
||||
(TUTOR_FROM + DAY, 180, "19:00"),
|
||||
):
|
||||
base = base_for(day, _unconfirmed(), first_credits=paid)
|
||||
base = base_for(day, first_credits=paid)
|
||||
assert (base.gaming_minutes, _hhmm(base.shutdown_minutes)) == (gaming, floor)
|
||||
|
||||
|
||||
def test_the_confirmed_tutor_with_no_credit_fails_closed_on_the_floor() -> None:
|
||||
# 0.7.0: confirmed the eve, before any block paid out. The real ledgers
|
||||
# of 2026-10-10 give the 5 h base (180 + LeetCode's 60 + reading's 60).
|
||||
assert AUTOMATION_TUTOR.confirmed_on == TUTOR_FROM - DAY
|
||||
base = base_for(TUTOR_FROM, first_credits=REAL)
|
||||
assert (base.gaming_minutes, _hhmm(base.shutdown_minutes)) == (180, "18:50")
|
||||
day = resolve(
|
||||
{"workout": 0, "leetcode": 1, "reading": 1, "automation": 0},
|
||||
TUTOR_FROM,
|
||||
first_credits=REAL,
|
||||
)
|
||||
assert day.gaming_minutes == 300
|
||||
def test_a_confirmed_tutor_with_no_credit_fails_closed_on_the_floor() -> None:
|
||||
confirmed = replace(AUTOMATION_TUTOR, confirmed_on=TUTOR_FROM - DAY)
|
||||
registry = (*earners_for(TUTOR_FROM)[:-1], confirmed)
|
||||
base = base_for(TUTOR_FROM, registry, first_credits=REAL)
|
||||
assert (base.gaming_minutes, _hhmm(base.shutdown_minutes)) == (180, "19:00")
|
||||
|
||||
|
||||
def test_a_pure_bonus_is_always_on_the_ladder() -> None:
|
||||
|
||||
@ -43,8 +43,7 @@ def test_tutor_from_is_the_day_after_the_deploy() -> None:
|
||||
assert date(2026, 10, 10) == TUTOR_FROM
|
||||
assert date(2026, 10, 9) < TUTOR_FROM # never the day it was prepared
|
||||
assert LADDER_FROM <= TUTOR_FROM
|
||||
# Confirmed the eve, so the penalty bites on TUTOR_FROM itself.
|
||||
assert AUTOMATION_TUTOR.confirmed_on == EVE
|
||||
assert AUTOMATION_TUTOR.confirmed_on is None # no real session confirmed yet
|
||||
|
||||
|
||||
def test_registry_switches_on_tutor_from() -> None:
|
||||
@ -65,34 +64,28 @@ def test_all_earners_lists_each_once() -> None:
|
||||
assert AUTOMATION_TUTOR in all_earners()
|
||||
|
||||
|
||||
def test_each_tutor_block_earns_the_15_minutes_it_costs() -> None:
|
||||
# The fairness rule: 13/13/12/12 paid 50 for 60 sat. The extra 10 come
|
||||
# off the floor, so the ladder spans 250 instead of 240.
|
||||
assert sum(r.minutes(4) for r in LADDER.values()) == 240
|
||||
assert sum(r.minutes(4) for r in TUTOR_LADDER.values()) == 250
|
||||
assert [TUTOR_LADDER["automation"].minutes(n) for n in range(5)] == [
|
||||
0,
|
||||
15,
|
||||
30,
|
||||
45,
|
||||
60,
|
||||
]
|
||||
def test_tutor_ladder_still_sums_to_the_old_one() -> None:
|
||||
old = sum(r.minutes(4) for r in LADDER.values())
|
||||
new = sum(r.minutes(4) for r in TUTOR_LADDER.values())
|
||||
assert old == new == 240
|
||||
assert TUTOR_LADDER["automation"].minutes(4) == 50
|
||||
|
||||
|
||||
def test_nothing_done_is_three_hours_and_18_50() -> None:
|
||||
# Confirmed, so the tutor is cut from penalty_from with or without
|
||||
# first_credits (test_maturity_floor.py).
|
||||
assert _day(0) == (180, "18:50")
|
||||
def test_nothing_done_is_three_hours_and_19() -> None:
|
||||
# Without first_credits (an unwired consumer): the tutor is cut from
|
||||
# penalty_from; given them, a never-paid tutor costs nothing
|
||||
# (test_maturity_floor.py).
|
||||
assert _day(0) == (180, "19:00")
|
||||
assert base_for(TUTOR_FROM).gaming_minutes == 180
|
||||
|
||||
|
||||
def test_everything_but_the_tutor() -> None:
|
||||
assert _day(0, **OTHERS) == (420, "22:00")
|
||||
assert _day(0, **OTHERS) == (420, "22:10")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("blocks", "gaming", "shutdown"),
|
||||
[(1, 435, "22:15"), (2, 450, "22:30"), (3, 465, "22:45"), (4, 480, "23:00")],
|
||||
[(1, 435, "22:23"), (2, 450, "22:36"), (3, 465, "22:48"), (4, 480, "23:00")],
|
||||
)
|
||||
def test_each_block_pays_15_gaming_and_its_rung(
|
||||
blocks: int, gaming: int, shutdown: str
|
||||
@ -101,15 +94,15 @@ def test_each_block_pays_15_gaming_and_its_rung(
|
||||
|
||||
|
||||
def test_partial_credit_without_the_others() -> None:
|
||||
assert _day(1) == (195, "19:05")
|
||||
assert _day(2) == (210, "19:20")
|
||||
assert _day(1) == (195, "19:13")
|
||||
assert _day(2) == (210, "19:26")
|
||||
assert _day(4) == (240, "19:50")
|
||||
|
||||
|
||||
def test_a_fifth_block_is_clamped_to_four() -> None:
|
||||
assert _day(5, **OTHERS) == _day(4, **OTHERS) == (480, "23:00")
|
||||
term = resolve({"automation": 5}, TUTOR_FROM).term("automation")
|
||||
assert (term.answer, term.gaming_minutes, term.shutdown_minutes) == (5, 60, 60)
|
||||
assert (term.answer, term.gaming_minutes, term.shutdown_minutes) == (5, 60, 50)
|
||||
|
||||
|
||||
def test_anki_is_neither_penalised_nor_paid_from_tutor_from() -> None:
|
||||
@ -139,7 +132,7 @@ def test_rung_steps_and_extras() -> None:
|
||||
assert rung.second == 13
|
||||
assert Rung(10, extra=5).minutes(3) == 20
|
||||
assert Rung(10, extra=5).second == 5
|
||||
assert extra_shutdown_minutes_for(AUTOMATION_TUTOR, TUTOR_FROM) == 15
|
||||
assert extra_shutdown_minutes_for(AUTOMATION_TUTOR, TUTOR_FROM) == 13
|
||||
|
||||
|
||||
def test_gaming_for_and_max() -> None:
|
||||
@ -157,5 +150,5 @@ def test_gaming_for_and_max() -> None:
|
||||
|
||||
def test_tutor_shutdown_before_the_ladder_uses_its_own_fields() -> None:
|
||||
old = date(2026, 10, 1)
|
||||
assert AUTOMATION_TUTOR.shutdown_for(2, old) == 30
|
||||
assert AUTOMATION_TUTOR.shutdown_for(2, old) == 26
|
||||
assert AUTOMATION_TUTOR.shutdown_for(0, old) == 0
|
||||
|
||||
@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "earned-time"
|
||||
version = "0.7.0"
|
||||
version = "0.6.1"
|
||||
description = "Penalty-then-reward registry: what every gate app earns in gaming time and shutdown time"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = []
|
||||
|
||||
@ -54,19 +54,10 @@ is written as `<FILL IN>`, which the gate rejects until a human fills it.
|
||||
|
||||
## Adding the gate to a repo
|
||||
|
||||
Run this on every new repo right after `git init` (idempotent):
|
||||
|
||||
```bash
|
||||
~/src/utils/scripts/install_repo_contract_gate.sh <repo> # --check to preview
|
||||
```
|
||||
|
||||
It writes the `scripts/check_repo_contract.sh` shim, the pre-commit hook, the
|
||||
CI workflow (skipped when the repo has `.dep-freshness-no-workflow`, i.e. no
|
||||
GitHub Actions), then bootstraps the `## Commands` section and
|
||||
`scripts/test_changed.sh`. It exits 1 while a `<FILL IN>` remains. Never copy
|
||||
`scripts/check_repo_contract.sh` from this repo (it is the real gate, not a shim).
|
||||
The hook only fires on commits touching CLAUDE.md/AGENTS.md/test_changed.sh,
|
||||
so a repo that never got the installer is caught only by `sweep.py`.
|
||||
1. Copy `templates/check_repo_contract.shim.sh` to `scripts/check_repo_contract.sh`
|
||||
(never copy `scripts/check_repo_contract.sh` from this repo).
|
||||
2. Add `templates/pre-commit-snippet.yaml` to `.pre-commit-config.yaml`.
|
||||
3. Copy `templates/repo-contract.yml` to `.github/workflows/`.
|
||||
|
||||
## Tests
|
||||
|
||||
|
||||
@ -1,169 +0,0 @@
|
||||
"""Install the repo-contract gate into a repo and bootstrap its Commands section.
|
||||
|
||||
Usage: python3 -m repo_contract.install REPO [--check] [--no-bootstrap]
|
||||
(or `scripts/install_repo_contract_gate.sh REPO`).
|
||||
|
||||
Why this exists: the gate used to be four manual steps in the README. Nothing
|
||||
ran them for a repo created after the 2026-10-04 rollout (teatr-pw and
|
||||
teatr-pw-pytania were made ad hoc on 2026-10-09 and came out with no
|
||||
`## Commands`, no shim, no hook), so the sweep was the first thing to notice.
|
||||
One idempotent command now does all of it: delegate shim, pre-commit hook,
|
||||
CI workflow (unless the repo opted out of GitHub Actions) and the Commands
|
||||
section plus `scripts/test_changed.sh` through bootstrap.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
if __package__ in (None, ""): # pragma: no cover - plain-script import path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from dep_freshness.install import NO_WORKFLOW_MARKER
|
||||
from repo_contract import bootstrap
|
||||
from repo_contract.check import violations
|
||||
from repo_contract.infer import propose
|
||||
from repo_contract.stacks import detect_stacks
|
||||
|
||||
TEMPLATES = bootstrap.TEMPLATES
|
||||
SHIM = Path("scripts/check_repo_contract.sh")
|
||||
WORKFLOW = Path(".github/workflows/repo-contract.yml")
|
||||
PRECOMMIT = Path(".pre-commit-config.yaml")
|
||||
HOOK_ID = "repo-contract"
|
||||
LOCAL_REPO = " - repo: local"
|
||||
EMPTY_PRECOMMIT = f"repos:\n{LOCAL_REPO}\n hooks:\n"
|
||||
|
||||
|
||||
def _template(name: str) -> str:
|
||||
return (TEMPLATES / name).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _needs_shim(repo: Path) -> bool:
|
||||
"""False for utils itself, where SHIM is the real checker, not a delegate."""
|
||||
if (repo / "repo_contract" / "check.py").is_file():
|
||||
return False
|
||||
target = repo / SHIM
|
||||
return not target.is_file() or target.read_text(encoding="utf-8") != _template(
|
||||
"check_repo_contract.shim.sh"
|
||||
)
|
||||
|
||||
|
||||
def _needs_workflow(repo: Path) -> bool:
|
||||
"""Missing or drifted CI workflow, unless the repo opted out of Actions."""
|
||||
if (repo / NO_WORKFLOW_MARKER).exists():
|
||||
return False
|
||||
target = repo / WORKFLOW
|
||||
return not target.is_file() or target.read_text(encoding="utf-8") != _template(
|
||||
"repo-contract.yml"
|
||||
)
|
||||
|
||||
|
||||
def _needs_hook(repo: Path) -> bool:
|
||||
target = repo / PRECOMMIT
|
||||
return not target.is_file() or f"id: {HOOK_ID}" not in target.read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
def _local_block_end(lines: list[str]) -> int:
|
||||
"""Index just past the LAST `- repo: local` block, or -1 if there is none."""
|
||||
starts = [n for n, line in enumerate(lines) if line.rstrip() == LOCAL_REPO]
|
||||
if not starts:
|
||||
return -1
|
||||
after = [
|
||||
n for n in range(starts[-1] + 1, len(lines)) if lines[n].startswith(" - repo:")
|
||||
]
|
||||
return after[0] if after else len(lines)
|
||||
|
||||
|
||||
def _write_hook(repo: Path) -> None:
|
||||
"""Insert the hook into the LAST local hooks list, keeping comments intact."""
|
||||
target = repo / PRECOMMIT
|
||||
body = target.read_text(encoding="utf-8") if target.is_file() else EMPTY_PRECOMMIT
|
||||
lines = (body if body.endswith("\n") else body + "\n").split("\n")[:-1]
|
||||
cut = _local_block_end(lines)
|
||||
if cut < 0:
|
||||
raise ValueError(
|
||||
f"{target} has no `{LOCAL_REPO}` block to add the hook to; "
|
||||
"add one by hand, then re-run"
|
||||
)
|
||||
block = [
|
||||
ln
|
||||
for ln in _template("pre-commit-snippet.yaml").rstrip("\n").split("\n")
|
||||
if not ln.startswith("#")
|
||||
]
|
||||
lines[cut:cut] = ["", *block]
|
||||
target.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def plan(repo: Path) -> list[str]:
|
||||
"""Which gate pieces are missing or drifted (the Commands section excluded)."""
|
||||
todo = []
|
||||
if _needs_shim(repo):
|
||||
todo.append(str(SHIM))
|
||||
if _needs_workflow(repo):
|
||||
todo.append(str(WORKFLOW))
|
||||
if _needs_hook(repo):
|
||||
todo.append(f"{PRECOMMIT} ({HOOK_ID} hook)")
|
||||
return todo
|
||||
|
||||
|
||||
def install(repo: Path) -> list[str]:
|
||||
"""Write every missing or drifted gate piece. Returns what changed."""
|
||||
done = []
|
||||
if _needs_shim(repo):
|
||||
target = repo / SHIM
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(_template("check_repo_contract.shim.sh"), encoding="utf-8")
|
||||
target.chmod(0o755)
|
||||
done.append(str(SHIM))
|
||||
if _needs_workflow(repo):
|
||||
target = repo / WORKFLOW
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(_template("repo-contract.yml"), encoding="utf-8")
|
||||
done.append(str(WORKFLOW))
|
||||
if _needs_hook(repo):
|
||||
_write_hook(repo)
|
||||
done.append(f"{PRECOMMIT} ({HOOK_ID} hook)")
|
||||
return done
|
||||
|
||||
|
||||
def bootstrap_commands(repo: Path) -> list[str]:
|
||||
"""Write the missing Commands lines and test_changed.sh (never overwrites)."""
|
||||
prop = propose(repo, detect_stacks(repo))
|
||||
doc = bootstrap.doc_path(repo)
|
||||
text = doc.read_text(encoding="utf-8") if doc.is_file() else ""
|
||||
new = bootstrap.missing_lines(prop, text)
|
||||
return bootstrap.apply(repo, doc, text, new, bootstrap.script_plan(repo, prop))
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""CLI entry point; 0 contract satisfied, 1 violations left, 2 not a git repo."""
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("repo", type=Path)
|
||||
parser.add_argument("--check", action="store_true", help="report, change nothing")
|
||||
parser.add_argument("--no-bootstrap", action="store_true", help="gate pieces only")
|
||||
args = parser.parse_args(argv)
|
||||
repo = args.repo.expanduser().resolve()
|
||||
if not (repo / ".git").exists():
|
||||
print(f"install: {repo} is not a git repo", file=sys.stderr)
|
||||
return 2
|
||||
if args.check:
|
||||
for piece in plan(repo):
|
||||
print(f"would write: {piece}")
|
||||
else:
|
||||
for piece in install(repo):
|
||||
print(f"wrote: {piece}")
|
||||
if not args.no_bootstrap:
|
||||
for action in bootstrap_commands(repo):
|
||||
print(f"bootstrap: {action}")
|
||||
found, _ = violations(repo)
|
||||
for problem in found:
|
||||
print(f"repo-contract: {repo.name}: {problem}", file=sys.stderr)
|
||||
return 1 if found else 0
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
sys.exit(main())
|
||||
@ -1,114 +0,0 @@
|
||||
"""The installer writes the shim, hook, workflow and Commands section once."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import stat
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from repo_contract import install as inst
|
||||
from repo_contract.check import violations
|
||||
|
||||
from .conftest import good_repo, write
|
||||
|
||||
|
||||
def python_repo(root: Path) -> Path:
|
||||
"""A python repo with tests and no contract pieces at all."""
|
||||
write(root, "pyproject.toml", "[project]\nname='x'\n")
|
||||
write(root, "tests/test_a.py", "def test_a():\n pass\n")
|
||||
return root
|
||||
|
||||
|
||||
def test_plan_lists_everything_for_a_bare_repo(repo: Path) -> None:
|
||||
assert inst.plan(repo) == [
|
||||
"scripts/check_repo_contract.sh",
|
||||
".github/workflows/repo-contract.yml",
|
||||
".pre-commit-config.yaml (repo-contract hook)",
|
||||
]
|
||||
|
||||
|
||||
def test_install_writes_pieces_and_is_idempotent(repo: Path) -> None:
|
||||
python_repo(repo)
|
||||
done = inst.install(repo)
|
||||
assert len(done) == 3
|
||||
shim = repo / inst.SHIM
|
||||
assert shim.stat().st_mode & stat.S_IXUSR
|
||||
assert "id: repo-contract" in (repo / inst.PRECOMMIT).read_text(encoding="utf-8")
|
||||
assert inst.install(repo) == []
|
||||
assert inst.plan(repo) == []
|
||||
|
||||
|
||||
def test_marker_skips_workflow(repo: Path) -> None:
|
||||
write(repo, ".dep-freshness-no-workflow")
|
||||
inst.install(repo)
|
||||
assert not (repo / inst.WORKFLOW).exists()
|
||||
|
||||
|
||||
def test_utils_itself_is_not_given_a_shim(repo: Path) -> None:
|
||||
write(repo, "repo_contract/check.py")
|
||||
assert inst.install(repo) != []
|
||||
assert not (repo / inst.SHIM).exists()
|
||||
|
||||
|
||||
def test_hook_lands_in_the_last_local_block(repo: Path) -> None:
|
||||
write(
|
||||
repo,
|
||||
inst.PRECOMMIT.as_posix(),
|
||||
"repos:\n - repo: local\n hooks:\n - id: a\n"
|
||||
" - repo: https://example.com/x\n hooks:\n - id: b",
|
||||
)
|
||||
inst.install(repo)
|
||||
lines = (repo / inst.PRECOMMIT).read_text(encoding="utf-8").splitlines()
|
||||
assert lines.index(" - id: repo-contract") < lines.index(
|
||||
" - repo: https://example.com/x"
|
||||
)
|
||||
|
||||
|
||||
def test_hook_needs_a_local_block(repo: Path) -> None:
|
||||
write(repo, inst.PRECOMMIT.as_posix(), "repos:\n - repo: https://example.com/x\n")
|
||||
with pytest.raises(ValueError, match="no ` - repo: local` block"):
|
||||
inst.install(repo)
|
||||
|
||||
|
||||
def test_bootstrap_commands_creates_section_and_script(repo: Path) -> None:
|
||||
python_repo(repo)
|
||||
actions = inst.bootstrap_commands(repo)
|
||||
assert any("test_changed.sh" in a for a in actions)
|
||||
assert "## Commands" in (repo / "CLAUDE.md").read_text(encoding="utf-8")
|
||||
assert inst.bootstrap_commands(repo) == []
|
||||
|
||||
|
||||
def test_main_check_changes_nothing(
|
||||
repo: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
assert inst.main([str(repo), "--check"]) == 1
|
||||
out = capsys.readouterr().out
|
||||
assert "would write: scripts/check_repo_contract.sh" in out
|
||||
assert not (repo / inst.SHIM).exists()
|
||||
|
||||
|
||||
def test_main_installs_and_passes(
|
||||
repo: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
good_repo(repo)
|
||||
assert inst.main([str(repo)]) == 0
|
||||
assert "wrote: scripts/check_repo_contract.sh" in capsys.readouterr().out
|
||||
assert violations(repo)[0] == []
|
||||
|
||||
|
||||
def test_main_no_bootstrap_leaves_violation(repo: Path) -> None:
|
||||
assert inst.main([str(repo), "--no-bootstrap"]) == 1
|
||||
assert not (repo / "CLAUDE.md").exists()
|
||||
|
||||
|
||||
def test_main_rejects_non_repo(tmp_path: Path) -> None:
|
||||
assert inst.main([str(tmp_path)]) == 2
|
||||
|
||||
|
||||
def test_main_reports_bootstrap_actions(
|
||||
repo: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
python_repo(repo)
|
||||
inst.main([str(repo)])
|
||||
assert "bootstrap: created scripts/test_changed.sh" in capsys.readouterr().out
|
||||
@ -1,29 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ============================================================================
|
||||
# Install the repo-contract gate into a repo and bootstrap its CLAUDE.md
|
||||
# `## Commands` section plus scripts/test_changed.sh.
|
||||
#
|
||||
# Run this on EVERY new repo, right after `git init`. Idempotent. Pieces:
|
||||
# scripts/check_repo_contract.sh shim, pre-commit hook, CI workflow (skipped
|
||||
# when the repo has .dep-freshness-no-workflow), Commands section.
|
||||
#
|
||||
# Usage: scripts/install_repo_contract_gate.sh <repo> [--check] [--no-bootstrap]
|
||||
# Exit: 0 contract satisfied | 1 violations left (e.g. <FILL IN>) | 2 not a git repo
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
UTILS_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
readonly UTILS_ROOT
|
||||
|
||||
main() {
|
||||
if [[ $# -lt 1 ]]; then
|
||||
echo "Usage: $(basename "$0") <repo> [--check] [--no-bootstrap]" >&2
|
||||
exit 1
|
||||
fi
|
||||
PYTHONPATH="$UTILS_ROOT${PYTHONPATH:+:$PYTHONPATH}" \
|
||||
python3 -m repo_contract.install "$@"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Loading…
Reference in New Issue
Block a user