mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-24 19:46:29 +01:00
Compare commits
4 Commits
7f2443ce48
...
67f14588f7
| Author | SHA1 | Date | |
|---|---|---|---|
| 67f14588f7 | |||
| ef244889fd | |||
| d3f01c36e1 | |||
| 8b7105e20c |
9
.github/workflows/shared-gates-tests.yml
vendored
9
.github/workflows/shared-gates-tests.yml
vendored
@ -62,3 +62,12 @@ jobs:
|
||||
--cov=coverage_gaps --cov-branch \
|
||||
--cov-report=term-missing \
|
||||
--cov-fail-under=100
|
||||
|
||||
# gate_stamp.sh is the pre-push gate in every repo. Its tests drive real
|
||||
# pre-commit in throwaway repos, and the hook-id helper runs under
|
||||
# /usr/bin/python3 (the deployment interpreter), hence apt's PyYAML.
|
||||
- name: gate_stamp (step / full --list)
|
||||
run: |
|
||||
sudo apt-get update -q && sudo apt-get install -y python3-yaml
|
||||
python -m pip install --upgrade pre-commit
|
||||
PYTHONPATH=. python -m pytest scripts/tests -q
|
||||
|
||||
@ -10,7 +10,7 @@ overwrite it with `repo_contract/templates/check_repo_contract.shim.sh`.
|
||||
## Commands
|
||||
|
||||
- run: n/a: collection of gates and libraries, no single entry point
|
||||
- test: `PYTHONPATH=. python -m pytest -q coverage_gaps/tests dep_freshness/tests file_length/tests home_paths/tests md_naming/tests repo_contract/tests`
|
||||
- test: `PYTHONPATH=. python -m pytest -q coverage_gaps/tests dep_freshness/tests file_length/tests home_paths/tests md_naming/tests repo_contract/tests scripts/tests`
|
||||
- test-changed: `scripts/test_changed.sh`
|
||||
- lint: `ruff check coverage_gaps repo_contract`
|
||||
- coverage: `PYTHONPATH=. python -m pytest -q repo_contract/tests --cov=repo_contract --cov-branch --cov-report=xml --cov-fail-under=100`
|
||||
|
||||
@ -29,16 +29,8 @@ never a same-day cut):
|
||||
earner name; all of a counted earner's capped units), so doing everything
|
||||
lands exactly on the ceiling. Since 0.6.1 `TUTOR_FROM == LADDER_FROM`, so
|
||||
every real ladder day uses `TUTOR_LADDER` (below); `LADDER`, the pre-tutor
|
||||
split, is never in force on a real day:
|
||||
|
||||
| done | shutdown |
|
||||
|---|---|
|
||||
| nothing | 19:00 |
|
||||
| workout (110) | 20:50 |
|
||||
| + LeetCode (50) | 21:40 |
|
||||
| + reading (30) | 22:10 |
|
||||
| + Anki (25) | 22:35 |
|
||||
| + Automation (25) | 23:00 |
|
||||
split (workout 110, LeetCode 50, reading 30, Anki 25, Automation 25; floor
|
||||
19:00), is never in force on a real day.
|
||||
|
||||
A second workout earns nothing more (`Rung.extra` defaults to 0).
|
||||
Move the alarm (`WAKE_MINUTES = 6 * 60`) and the whole ladder shifts an hour
|
||||
@ -48,6 +40,11 @@ never a same-day cut):
|
||||
The two floors are derived separately (`_resolve._shutdown_floor`), so the
|
||||
ladder cannot move a gaming minute.
|
||||
|
||||
**Unified ladder (0.12.0, `UNIFIED_FROM` 2026-10-18):** each rung pays what
|
||||
its earner pays in gaming (workout 120, LeetCode 60, reading 60, tutor 1/unit
|
||||
to 60), so the floor drops 18:50 -> 18:00 under the same 23:00 ceiling:
|
||||
nothing 3 h / 18:00, workout 5 h / 20:00, +LeetCode 21:00, +reading 22:00.
|
||||
|
||||
**Sick days (0.11.0, `_sick.py`).** `resolve(..., sick=True)` floors the
|
||||
*final* shutdown at 20:00 (`SICK_SHUTDOWN_FLOOR_MINUTES`), capped at the
|
||||
ceiling: 18:50 becomes 20:00, 21:30 stays 21:30 (nothing stacks on the floor).
|
||||
@ -243,7 +240,7 @@ on the day itself is logged and does not count.
|
||||
## Install
|
||||
|
||||
```console
|
||||
pip install --user --break-system-packages --no-deps "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.11.0#subdirectory=earned_time"
|
||||
pip install --user --break-system-packages --no-deps "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.12.0#subdirectory=earned_time"
|
||||
```
|
||||
|
||||
The root `steam-backlog-enforcer.service` sets `HOME=/home/kuhy`, so it imports
|
||||
|
||||
@ -46,6 +46,8 @@ from earned_time._ladder import (
|
||||
SHUTDOWN_CEILING_MINUTES,
|
||||
TUTOR_FROM,
|
||||
TUTOR_LADDER,
|
||||
UNIFIED_FROM,
|
||||
UNIFIED_LADDER,
|
||||
WAKE_MINUTES,
|
||||
Rung,
|
||||
extra_shutdown_minutes_for,
|
||||
@ -106,6 +108,8 @@ __all__ = [
|
||||
"TUTOR_LADDER",
|
||||
"TUTOR_QUOTA_FROM",
|
||||
"TUTOR_QUOTA_MINUTES",
|
||||
"UNIFIED_FROM",
|
||||
"UNIFIED_LADDER",
|
||||
"WAKE_MINUTES",
|
||||
"WORKOUT",
|
||||
"Base",
|
||||
|
||||
@ -9,7 +9,9 @@ frozen ceiling, so the switch never rewrites how an old day resolved. Gaming
|
||||
is not on the ladder.
|
||||
|
||||
From ``TUTOR_FROM`` the rungs are :data:`TUTOR_LADDER`: Anki is retired and
|
||||
its 25 minutes fold into the tutor's, paid per active minute.
|
||||
its 25 minutes fold into the tutor's, paid per active minute. From
|
||||
``UNIFIED_FROM`` they are :data:`UNIFIED_LADDER`: each rung equals its
|
||||
earner's gaming pay.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -47,6 +49,10 @@ TUTOR_FROM: Final = date(2026, 10, 10)
|
||||
# floor rises by exactly what the two could have paid back), so it may land
|
||||
# on its deploy day: 0.5.0 landed 2026-10-09.
|
||||
ANKI_WAIVED_FROM: Final = date(2026, 10, 9)
|
||||
# From this day every rung pays exactly the gaming time its earner pays
|
||||
# (:data:`UNIFIED_LADDER`, 0.12.0). It lowers the floor 18:50 -> 18:00, so it
|
||||
# lands the day after the deploy (2026-10-17), never on it.
|
||||
UNIFIED_FROM: Final = date(2026, 10, 18)
|
||||
_SLEEP_MINUTES: Final = 8 * 60
|
||||
_DAY_MINUTES: Final = 24 * 60
|
||||
|
||||
@ -109,6 +115,19 @@ TUTOR_LADDER: Final[Mapping[str, Rung]] = MappingProxyType(
|
||||
)
|
||||
|
||||
|
||||
# From ``UNIFIED_FROM``: shutdown and gaming pay the same -- workout 120,
|
||||
# LeetCode 60, reading 60, tutor 1 per unit up to 60. The rungs sum to 300:
|
||||
# the ceiling stays 23:00 and the floor drops to 18:00.
|
||||
UNIFIED_LADDER: Final[Mapping[str, Rung]] = MappingProxyType(
|
||||
{
|
||||
"workout": Rung(120),
|
||||
"leetcode": Rung(60),
|
||||
"reading": Rung(60),
|
||||
"tutor": Rung(1, extra=1),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def on_ladder(day: date) -> bool:
|
||||
"""Whether ``day`` resolves shutdown on the sleep ladder."""
|
||||
return day >= LADDER_FROM
|
||||
@ -118,6 +137,8 @@ def ladder_for(day: date) -> Mapping[str, Rung] | None:
|
||||
"""The rungs in force on ``day``; ``None`` before the ladder."""
|
||||
if not on_ladder(day):
|
||||
return None
|
||||
if day >= UNIFIED_FROM:
|
||||
return UNIFIED_LADDER
|
||||
return TUTOR_LADDER if day >= TUTOR_FROM else LADDER
|
||||
|
||||
|
||||
|
||||
@ -14,9 +14,9 @@ from datetime import date, timedelta
|
||||
import pytest
|
||||
|
||||
from earned_time import (
|
||||
TUTOR,
|
||||
EARNERS,
|
||||
LADDER_FROM,
|
||||
TUTOR,
|
||||
TUTOR_FROM,
|
||||
WORKOUT,
|
||||
Earner,
|
||||
|
||||
@ -9,10 +9,10 @@ import pytest
|
||||
|
||||
from earned_time import (
|
||||
AUTOMATION,
|
||||
TUTOR,
|
||||
EARNERS,
|
||||
LADDER,
|
||||
LADDER_FROM,
|
||||
TUTOR,
|
||||
TUTOR_EARNERS,
|
||||
TUTOR_FROM,
|
||||
TUTOR_LADDER,
|
||||
|
||||
@ -54,9 +54,7 @@ def test_minute_rows_sum(tmp_path: Path, key_file: Path) -> None:
|
||||
rows: list[object] = [minute("s", n, _at(18, n)) for n in (1, 2, 3)]
|
||||
rows.append(minute("s", 4, _at(18, 13), minutes=10))
|
||||
assert _units(tmp_path, key_file, rows) == 13
|
||||
assert first_credit_at(
|
||||
TUTOR, _ledger(tmp_path, rows), key_file, DAY
|
||||
) == _at(18, 1)
|
||||
assert first_credit_at(TUTOR, _ledger(tmp_path, rows), key_file, DAY) == _at(18, 1)
|
||||
|
||||
|
||||
def test_legacy_rows_count_15() -> None:
|
||||
|
||||
63
earned_time/earned_time/tests/test_unified.py
Normal file
63
earned_time/earned_time/tests/test_unified.py
Normal file
@ -0,0 +1,63 @@
|
||||
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||
"""The unified ladder (0.12.0): every shutdown rung equals its gaming pay."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
from earned_time import (
|
||||
TUTOR_EARNERS,
|
||||
TUTOR_LADDER,
|
||||
UNIFIED_FROM,
|
||||
UNIFIED_LADDER,
|
||||
ladder_for,
|
||||
resolve,
|
||||
shutdown_ceiling_for,
|
||||
)
|
||||
|
||||
EVE = UNIFIED_FROM - timedelta(days=1)
|
||||
|
||||
|
||||
def _hhmm(minutes: int) -> str:
|
||||
return f"{minutes // 60:02d}:{minutes % 60:02d}"
|
||||
|
||||
|
||||
def _day(day: date, **done: int) -> tuple[int, str]:
|
||||
answers = {e.name: done.get(e.name, 0) for e in TUTOR_EARNERS}
|
||||
out = resolve(answers, day, TUTOR_EARNERS)
|
||||
return out.gaming_minutes, _hhmm(out.shutdown_minutes)
|
||||
|
||||
|
||||
def test_switch_is_the_day_after_the_deploy() -> None:
|
||||
assert date(2026, 10, 18) == UNIFIED_FROM
|
||||
assert ladder_for(EVE) is TUTOR_LADDER # deploy day keeps the old rungs
|
||||
assert ladder_for(UNIFIED_FROM) is UNIFIED_LADDER
|
||||
|
||||
|
||||
def test_each_rung_pays_what_gaming_pays() -> None:
|
||||
for e in TUTOR_EARNERS:
|
||||
units = e.max_units or 1
|
||||
assert UNIFIED_LADDER[e.name].minutes(units) == e.gaming_for(units), e.name
|
||||
assert {n: r.minutes(60) for n, r in UNIFIED_LADDER.items()} == {
|
||||
"workout": 120,
|
||||
"leetcode": 60,
|
||||
"reading": 60,
|
||||
"tutor": 60,
|
||||
}
|
||||
|
||||
|
||||
def test_ceiling_stays_and_floor_drops_to_18() -> None:
|
||||
assert shutdown_ceiling_for(UNIFIED_FROM) == 23 * 60
|
||||
assert _day(UNIFIED_FROM) == (180, "18:00")
|
||||
assert _day(UNIFIED_FROM, workout=1) == (300, "20:00")
|
||||
assert _day(UNIFIED_FROM, workout=2) == (300, "20:00") # 2nd unit pays 0
|
||||
assert _day(UNIFIED_FROM, workout=1, leetcode=1) == (360, "21:00")
|
||||
assert _day(UNIFIED_FROM, workout=1, leetcode=1, reading=1) == (420, "22:00")
|
||||
full = _day(UNIFIED_FROM, workout=1, leetcode=1, reading=1, tutor=60)
|
||||
assert full == (480, "23:00")
|
||||
assert _day(UNIFIED_FROM, tutor=30) == (210, "18:30") # per unit, 1:1
|
||||
|
||||
|
||||
def test_old_days_keep_the_tutor_ladder() -> None:
|
||||
assert _day(EVE) == (180, "18:50")
|
||||
assert _day(EVE, workout=1) == (300, "20:40")
|
||||
@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "earned-time"
|
||||
version = "0.11.0"
|
||||
version = "0.12.0"
|
||||
description = "Penalty-then-reward registry: what every gate app earns in gaming time and shutdown time"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = []
|
||||
|
||||
@ -15,7 +15,19 @@
|
||||
# gate + commit; refuses a dirty tree unless told the gate
|
||||
# saw the working copy (narrow staging leaves other files)
|
||||
# full run the repo's manual-stage hooks (the old pre-push set)
|
||||
# on --all-files, then write; the on-demand heavy gate
|
||||
# on --all-files in ONE call, then write; >60 s in the
|
||||
# bigger repos, so prefer the split form below
|
||||
# full --list print the manual-stage hook ids, one per line
|
||||
# step <hook-id> run one manual-stage hook on --all-files and record
|
||||
# "<HEAD^{tree}> <id>" in $GIT_DIR/gate-steps; once every
|
||||
# id from `full --list` is recorded for the current tree,
|
||||
# write the stamp exactly as `write` does. Each call stays
|
||||
# under the 60 s per-command cap:
|
||||
# for id in $(gate_stamp.sh full --list); do
|
||||
# gate_stamp.sh step "$id"; done # one per call
|
||||
#
|
||||
# Manual-stage ids come from scripts/gate_stamp_hooks.py (PyYAML under
|
||||
# /usr/bin/python3), which parses .pre-commit-config.yaml.
|
||||
#
|
||||
# The heavy suites still run in CI on every push; this only decides whether a
|
||||
# tree may leave the machine, not whether it is fully green.
|
||||
@ -25,9 +37,13 @@ set -euo pipefail
|
||||
|
||||
SCRIPT_NAME="$(basename "$0")"
|
||||
readonly SCRIPT_NAME
|
||||
# Resolved before main() cd's to the toplevel, so a relative $0 still works.
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
readonly SCRIPT_DIR
|
||||
readonly HOOKS_HELPER="$SCRIPT_DIR/gate_stamp_hooks.py"
|
||||
|
||||
usage() {
|
||||
echo "Usage: $SCRIPT_NAME check | write [--dirty-ok] | full"
|
||||
echo "Usage: $SCRIPT_NAME check | write [--dirty-ok] | full [--list] | step <hook-id>"
|
||||
exit 2
|
||||
}
|
||||
|
||||
@ -35,6 +51,10 @@ stamp_path() {
|
||||
printf '%s/gate-stamp\n' "$(git rev-parse --git-dir)"
|
||||
}
|
||||
|
||||
steps_path() {
|
||||
printf '%s/gate-steps\n' "$(git rev-parse --git-dir)"
|
||||
}
|
||||
|
||||
tree_of() {
|
||||
git rev-parse --verify --quiet "$1^{tree}"
|
||||
}
|
||||
@ -70,7 +90,9 @@ cmd_check() {
|
||||
echo " no stamp in $(stamp_path)"
|
||||
fi
|
||||
echo " Either: ~/.claude/scripts/finish_auto.sh (gate + commit + push)"
|
||||
echo " or: scripts/check_gate_stamp.sh full (old pre-push suites, then push again)"
|
||||
echo " or: scripts/check_gate_stamp.sh full --list (manual-stage hook ids), then"
|
||||
echo " scripts/check_gate_stamp.sh step <id> once per id, one call each;"
|
||||
echo " the last passing step stamps the tree, then push again"
|
||||
} >&2
|
||||
exit 1
|
||||
}
|
||||
@ -94,12 +116,75 @@ cmd_write() {
|
||||
fi
|
||||
}
|
||||
|
||||
manual_ids() {
|
||||
/usr/bin/python3 "$HOOKS_HELPER" .pre-commit-config.yaml
|
||||
}
|
||||
|
||||
cmd_full() {
|
||||
if [[ "${1:-}" == "--list" ]]; then
|
||||
manual_ids
|
||||
return 0
|
||||
fi
|
||||
[[ $# -eq 0 ]] || usage
|
||||
echo "gate-stamp: hint: split this into <60 s calls with 'full --list' + 'step <hook-id>'"
|
||||
echo "gate-stamp: running the manual-stage hooks on all files (the old pre-push set)"
|
||||
pre-commit run --hook-stage manual --all-files
|
||||
cmd_write
|
||||
}
|
||||
|
||||
# Refusals exit 2 (usage-class), unlike write's exit 1: nothing was run.
|
||||
step_refuse() {
|
||||
echo "$SCRIPT_NAME step: $*" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
cmd_step() {
|
||||
[[ $# -eq 1 && -n "$1" ]] || usage
|
||||
local hook="$1" ids
|
||||
ids="$(manual_ids)"
|
||||
grep -Fxq -- "$hook" <<<"$ids" \
|
||||
|| step_refuse "'$hook' is not a manual-stage hook (see: $SCRIPT_NAME full --list)"
|
||||
[[ -z "$(git status --porcelain --untracked-files=no)" ]] \
|
||||
|| step_refuse "working tree differs from HEAD — commit first, then run steps."
|
||||
local tree
|
||||
tree="$(tree_of HEAD)"
|
||||
pre-commit run --hook-stage manual "$hook" --all-files
|
||||
[[ -z "$(git status --porcelain --untracked-files=no)" && "$(tree_of HEAD)" == "$tree" ]] \
|
||||
|| step_refuse "'$hook' passed but the tree changed while it ran; not recorded."
|
||||
record_step "$tree" "$hook"
|
||||
local missing id
|
||||
missing="$(missing_steps "$tree" "$ids")"
|
||||
if [[ -z "$missing" ]]; then
|
||||
echo "gate-stamp: every manual-stage hook passed on tree ${tree:0:12}; stamping"
|
||||
cmd_write
|
||||
else
|
||||
echo "gate-stamp: '$hook' recorded for tree ${tree:0:12}; still missing:"
|
||||
while IFS= read -r id; do echo " $id"; done <<<"$missing"
|
||||
fi
|
||||
}
|
||||
|
||||
# Keep only the current tree's records: older trees can never be stamped
|
||||
# again from here, and this bounds the file to one line per manual hook.
|
||||
record_step() {
|
||||
local tree="$1" hook="$2" path kept
|
||||
path="$(steps_path)"
|
||||
kept="$(grep -s -- "^$tree " "$path" || true)"
|
||||
{
|
||||
[[ -n "$kept" ]] && printf '%s\n' "$kept"
|
||||
grep -Fxq -- "$tree $hook" <<<"$kept" || printf '%s %s\n' "$tree" "$hook"
|
||||
} > "$path.tmp"
|
||||
mv -f "$path.tmp" "$path"
|
||||
}
|
||||
|
||||
missing_steps() {
|
||||
local tree="$1" ids="$2" path id
|
||||
path="$(steps_path)"
|
||||
while IFS= read -r id; do
|
||||
[[ -n "$id" ]] || continue
|
||||
grep -Fxqs -- "$tree $id" "$path" || printf '%s\n' "$id"
|
||||
done <<<"$ids"
|
||||
}
|
||||
|
||||
main() {
|
||||
local cmd="${1:-}"
|
||||
[[ -n "$cmd" ]] || usage
|
||||
@ -109,6 +194,7 @@ main() {
|
||||
check) cmd_check "$@" ;;
|
||||
write) cmd_write "$@" ;;
|
||||
full) cmd_full "$@" ;;
|
||||
step) cmd_step "$@" ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
}
|
||||
|
||||
76
scripts/gate_stamp_hooks.py
Executable file
76
scripts/gate_stamp_hooks.py
Executable file
@ -0,0 +1,76 @@
|
||||
#!/usr/bin/python3
|
||||
"""Print the manual-stage hook ids of a .pre-commit-config.yaml, one per line.
|
||||
|
||||
Used by gate_stamp.sh (`full --list`, `step <id>`) so the heavy gate can be
|
||||
split into one hook per call. A hook is manual-stage when its `stages` list
|
||||
contains `manual`, or when it has no `stages` key and the top-level
|
||||
`default_stages` includes `manual`. A missing `default_stages` means "every
|
||||
stage" to pre-commit, so those hooks count too: otherwise `step` could stamp a
|
||||
tree that `full` (`--hook-stage manual`) would have run more hooks on.
|
||||
|
||||
Ids are de-duplicated in first-seen order: `pre-commit run <id>` already runs
|
||||
every hook sharing that id, so one step covers them all.
|
||||
|
||||
Limitation: `stages` declared only in a remote repo's .pre-commit-hooks.yaml
|
||||
manifest is invisible here; set it in the config to have it counted.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
MANUAL = "manual"
|
||||
|
||||
|
||||
def _as_list(value: Any) -> list[str]:
|
||||
"""Normalise a YAML `stages`-like value to a list of strings."""
|
||||
if value is None:
|
||||
return []
|
||||
if isinstance(value, str):
|
||||
return [value]
|
||||
return [str(item) for item in value]
|
||||
|
||||
|
||||
def manual_hook_ids(config: dict[str, Any]) -> list[str]:
|
||||
"""Return the ids that `pre-commit run --hook-stage manual` would run."""
|
||||
default_has_manual = "default_stages" not in config or MANUAL in _as_list(
|
||||
config.get("default_stages")
|
||||
)
|
||||
ids: list[str] = []
|
||||
for repo in config.get("repos") or []:
|
||||
for hook in repo.get("hooks") or []:
|
||||
if "stages" in hook:
|
||||
is_manual = MANUAL in _as_list(hook["stages"])
|
||||
else:
|
||||
is_manual = default_has_manual
|
||||
hook_id = str(hook.get("id", ""))
|
||||
if is_manual and hook_id and hook_id not in ids:
|
||||
ids.append(hook_id)
|
||||
return ids
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
"""Entry point: `gate_stamp_hooks.py <path-to-.pre-commit-config.yaml>`."""
|
||||
if len(argv) != 1:
|
||||
sys.stderr.write("usage: gate_stamp_hooks.py <.pre-commit-config.yaml>\n")
|
||||
return 2
|
||||
path = Path(argv[0])
|
||||
try:
|
||||
config = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
||||
except (OSError, yaml.YAMLError) as exc:
|
||||
sys.stderr.write(f"gate_stamp_hooks: cannot read {path}: {exc}\n")
|
||||
return 1
|
||||
if not isinstance(config, dict):
|
||||
sys.stderr.write(f"gate_stamp_hooks: {path} is not a mapping\n")
|
||||
return 1
|
||||
for hook_id in manual_hook_ids(config):
|
||||
sys.stdout.write(f"{hook_id}\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
201
scripts/tests/test_gate_stamp.py
Normal file
201
scripts/tests/test_gate_stamp.py
Normal file
@ -0,0 +1,201 @@
|
||||
"""gate_stamp.sh step / full --list: the heavy gate split into <60 s calls.
|
||||
|
||||
Each test builds a throwaway git repo whose manual-stage hooks are
|
||||
`language: system` with `entry: true` / `entry: false`, so pre-commit runs
|
||||
offline in well under a second and the only thing under test is the stamp
|
||||
bookkeeping. Every hook is `always_run` -- a hook with no matching files is
|
||||
"Skipped" with exit 0, which would let `entry: false` pass.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parent.parent / "gate_stamp.sh"
|
||||
|
||||
CONFIG = """\
|
||||
default_stages: [pre-commit]
|
||||
repos:
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: ok-a
|
||||
name: ok a
|
||||
entry: "true"
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
stages: [manual]
|
||||
- id: ok-b
|
||||
name: ok b
|
||||
entry: "true"
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
stages: [pre-push, manual]
|
||||
- id: bad
|
||||
name: bad
|
||||
entry: "false"
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
stages: [manual]
|
||||
- id: commit-only
|
||||
name: commit only
|
||||
entry: "true"
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
"""
|
||||
|
||||
|
||||
def _git(repo: Path, *args: str) -> str:
|
||||
return subprocess.run(
|
||||
["git", *args], cwd=repo, check=True, capture_output=True, text=True
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
def _gate(repo: Path, *args: str) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run(
|
||||
["bash", str(SCRIPT), *args],
|
||||
cwd=repo,
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def _make_repo(path: Path, config: str) -> Path:
|
||||
path.mkdir()
|
||||
_git(path, "init", "-q", "-b", "main")
|
||||
_git(path, "config", "user.name", "t")
|
||||
_git(path, "config", "user.email", "t@example.invalid")
|
||||
(path / ".pre-commit-config.yaml").write_text(config, encoding="utf-8")
|
||||
(path / "f.txt").write_text("x\n", encoding="utf-8")
|
||||
_git(path, "add", ".")
|
||||
_git(path, "commit", "-q", "-m", "init")
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo(tmp_path: Path) -> Path:
|
||||
return _make_repo(tmp_path / "r", CONFIG)
|
||||
|
||||
|
||||
def _git_dir(repo: Path) -> Path:
|
||||
return (repo / _git(repo, "rev-parse", "--git-dir")).resolve()
|
||||
|
||||
|
||||
def _tree(repo: Path) -> str:
|
||||
return _git(repo, "rev-parse", "HEAD^{tree}")
|
||||
|
||||
|
||||
def test_full_list_prints_manual_ids_only(repo: Path) -> None:
|
||||
res = _gate(repo, "full", "--list")
|
||||
assert res.returncode == 0, res.stderr
|
||||
assert res.stdout.splitlines() == ["ok-a", "ok-b", "bad"]
|
||||
|
||||
|
||||
def test_list_counts_unstaged_hooks_when_default_stages_is_absent(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
# pre-commit treats a missing default_stages as "every stage", so a hook
|
||||
# without `stages` runs under --hook-stage manual and must be a step too.
|
||||
config = CONFIG.replace("default_stages: [pre-commit]\n", "")
|
||||
r = _make_repo(tmp_path / "nodefault", config)
|
||||
res = _gate(r, "full", "--list")
|
||||
assert res.stdout.splitlines() == ["ok-a", "ok-b", "bad", "commit-only"]
|
||||
|
||||
|
||||
def test_list_counts_unstaged_hooks_when_default_stages_has_manual(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
config = CONFIG.replace("[pre-commit]", "[pre-commit, manual]")
|
||||
r = _make_repo(tmp_path / "withmanual", config)
|
||||
res = _gate(r, "full", "--list")
|
||||
assert "commit-only" in res.stdout.splitlines()
|
||||
|
||||
|
||||
def test_step_records_and_reports_missing_ids(repo: Path) -> None:
|
||||
res = _gate(repo, "step", "ok-a")
|
||||
assert res.returncode == 0, res.stdout + res.stderr
|
||||
steps = (_git_dir(repo) / "gate-steps").read_text(encoding="utf-8")
|
||||
assert f"{_tree(repo)} ok-a" in steps.splitlines()
|
||||
assert "ok-b" in res.stdout
|
||||
assert "bad" in res.stdout
|
||||
assert not (_git_dir(repo) / "gate-stamp").exists()
|
||||
|
||||
|
||||
def test_rerunning_a_step_does_not_duplicate_its_record(repo: Path) -> None:
|
||||
_gate(repo, "step", "ok-a")
|
||||
_gate(repo, "step", "ok-a")
|
||||
steps = (_git_dir(repo) / "gate-steps").read_text(encoding="utf-8")
|
||||
assert steps.splitlines().count(f"{_tree(repo)} ok-a") == 1
|
||||
|
||||
|
||||
def test_a_failing_step_records_nothing(repo: Path) -> None:
|
||||
res = _gate(repo, "step", "bad")
|
||||
assert res.returncode != 0
|
||||
steps = _git_dir(repo) / "gate-steps"
|
||||
assert not steps.exists() or "bad" not in steps.read_text(encoding="utf-8")
|
||||
assert not (_git_dir(repo) / "gate-stamp").exists()
|
||||
|
||||
|
||||
def test_stamp_appears_only_after_every_manual_id_passes(tmp_path: Path) -> None:
|
||||
config = CONFIG.replace('entry: "false"', 'entry: "true"')
|
||||
r = _make_repo(tmp_path / "allgreen", config)
|
||||
stamp = _git_dir(r) / "gate-stamp"
|
||||
for hook in ("ok-a", "ok-b"):
|
||||
assert _gate(r, "step", hook).returncode == 0
|
||||
assert not stamp.exists()
|
||||
res = _gate(r, "step", "bad")
|
||||
assert res.returncode == 0, res.stdout + res.stderr
|
||||
assert stamp.read_text(encoding="utf-8").split()[0] == _tree(r)
|
||||
assert "recorded tree" in res.stdout
|
||||
assert _gate(r, "check").returncode == 0
|
||||
|
||||
|
||||
def test_step_on_a_dirty_tree_is_refused(repo: Path) -> None:
|
||||
(repo / "f.txt").write_text("changed\n", encoding="utf-8")
|
||||
res = _gate(repo, "step", "ok-a")
|
||||
assert res.returncode == 2
|
||||
assert "differs from HEAD" in res.stderr
|
||||
assert not (_git_dir(repo) / "gate-steps").exists()
|
||||
|
||||
|
||||
def test_step_with_an_unknown_id_is_refused(repo: Path) -> None:
|
||||
for hook in ("nope", "commit-only"):
|
||||
res = _gate(repo, "step", hook)
|
||||
assert res.returncode == 2
|
||||
assert "not a manual-stage hook" in res.stderr
|
||||
assert not (_git_dir(repo) / "gate-steps").exists()
|
||||
|
||||
|
||||
def test_step_without_an_id_is_refused(repo: Path) -> None:
|
||||
res = _gate(repo, "step")
|
||||
assert res.returncode == 2
|
||||
|
||||
|
||||
def test_step_in_a_linked_worktree_uses_its_own_git_dir(repo: Path) -> None:
|
||||
wt = repo.parent / "wt"
|
||||
_git(repo, "worktree", "add", "-q", str(wt))
|
||||
res = _gate(wt, "step", "ok-a")
|
||||
assert res.returncode == 0, res.stdout + res.stderr
|
||||
assert (repo / ".git/worktrees/wt/gate-steps").exists()
|
||||
assert not (repo / ".git/gate-steps").exists()
|
||||
|
||||
|
||||
def test_full_hints_at_step(repo: Path) -> None:
|
||||
res = _gate(repo, "full")
|
||||
assert "step" in res.stdout.splitlines()[0]
|
||||
assert res.returncode != 0 # `bad` fails, so no stamp
|
||||
assert not (_git_dir(repo) / "gate-stamp").exists()
|
||||
|
||||
|
||||
def test_check_failure_mentions_list_and_step(repo: Path) -> None:
|
||||
res = _gate(repo, "check")
|
||||
assert res.returncode == 1
|
||||
assert "full --list" in res.stderr
|
||||
assert "step <id>" in res.stderr
|
||||
Loading…
Reference in New Issue
Block a user