diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f712d78..83cb5d8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,9 +62,6 @@ jobs: - name: Supply-chain workflow tests run: bash tests/supply-chain.test.sh - - name: Merge train tests - run: python3 -m unittest discover -s tests -p "test_*.py" - # Fixture caller of the reusable supply-chain scan, on the real event: this repository scans itself # with the same file its consumers call. supply-chain: diff --git a/.github/zizmor.yml b/.github/zizmor.yml index 84a62d3..f50cb2f 100644 --- a/.github/zizmor.yml +++ b/.github/zizmor.yml @@ -6,5 +6,5 @@ rules: # Keyed by line number: update these when lines are added above them in ci.yml. - ci.yml:22 - ci.yml:31 - - ci.yml:74 - - ci.yml:81 + - ci.yml:71 + - ci.yml:78 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a60b85 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/README.md b/README.md index b092ed0..776dbab 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,11 @@ # ci-shared -Reusable GitHub Actions workflows and a merge-train script shared by the Contrast3D repositories. +Reusable GitHub Actions workflows shared by the maintainers' repositories. -Status: in progress. The design is in `specs/next-ci-reliability` of -`naindev-contrast3d/contrast3d-platform`. Licensed under MIT. +Status: in progress. The design is kept in the maintainers' own repository. Licensed under MIT. + +Tooling that is specific to one organisation (CI reports, a standards audit, a merge train) is not +here: it lives in a private repository, because it works on that organisation's own repositories. ## Contents @@ -30,81 +32,6 @@ Status: in progress. The design is in `specs/next-ci-reliability` of (no base commit, base not fetchable, empty diff, global pattern matched) every area is reported as changed. Skipped jobs must be declared in the gate's `allowed-skipped`. -- `train/automerge.py` (available): the merge train. It is not a workflow: a scheduled task on the - owner's desktop runs it with `gh`. One cycle goes over every repository of a JSON list - (`train/repos.example.json`), and per repository merges at most one pull request labelled - `automerge` whose gate check is green (plus the `ci-ok/` seal when `require_seal` is set) and - whose head contains the base branch. A stale head gets the base merged in through the API, without - force-push; a conflict gets `needs-human` and loses `automerge`. `merge_method` (`merge`, - `squash` or `rebase`, default `merge`) follows what each repository allows. Each cycle it also - logs once any workflow run that has been queued longer than `queue_alert_minutes` (default 30): - a runner that is offline or saturated otherwise holds jobs for up to 24 hours before they fail. - The runs already reported are remembered in `queue-alerts.json` beside the configuration. - After every merge it comments `` on the pull request, so a merge made - around the train can be counted, and it writes a `heartbeat:` line (repositories, labelled pull - requests, version of the script) at most once an hour as proof of life. - `--dry-run` changes nothing. - Tests: `python3 -m unittest discover -s tests`. - -- `train/install.ps1` (available): installs the train as the scheduled task `CI train`, every two - minutes, from `D:\Development\Tools\ci-train` (a copy of `automerge.py`, a `repos.json` created from - the example only if missing, and `train.log`). Run it from a normal PowerShell window of the owner's - session; `-Remove` retires the task. - -- `report/ci_report.py` (available): the CI health report. Per repository and period it prints the - failure rate of conclusive runs, the share of failures caused by the infrastructure (a job that - never reached its steps, or the shared preflight) and not the code, the median duration and the - median queue time, followed by a snapshot of today: runners online, offline and busy, queued runs - and open pull requests. Use it to plan from the current state, not from memory: - `py -3 report/ci_report.py --config train/repos.json --repo naindev-contrast3d/contrast-hub --days 7`. - For the repositories of `--config` (the shared train) the snapshot also counts the pull requests - merged outside the train since `--train-since`, and `--train-dir D:\Development\Tools\ci-train` - adds a section on the installed train: age of its log (silent after 90 minutes) and whether its - script differs from the one in `ci-shared` main. - -- `report/weekly_report.py` (available): the weekly report to a file. It runs `ci_report.py` over every - private repository of the organisation that is not archived and writes `ci-report-.md` (and - `latest.md`) to `--out-dir`. When the week deviates, with a failure rate above 25 % over at least - five runs, a p90 wait for a runner above five minutes, or more than a fifth of the failures caused by - the infrastructure, the deviations go at the top of the report and one toast is raised through - `--notify`; a healthy week raises nothing. The thresholds are options. `report/install-weekly-report.ps1` - registers it as the task `CI weekly report` (Mondays 08:00), from a normal PowerShell window of the - owner's session. - -- `report/runner_watch.py` (available): the runner watchdog. The report says how the queue behaved - over a period; this says that it is wrong now. Run from a scheduled task every few minutes - (`py -3 report/runner_watch.py --org naindev-contrast3d --notify `), it reads - the runners of the organisation and of each private repository, plus the queued runs, and raises one - toast per finding: a runner offline for `--offline-min` minutes (default 10; GitHub does not say - since when, so the first sighting is remembered in a state file) or a run queued for `--queue-min` - (default 15). A finding is reported once and again only after it has cleared; `--ignore NAME` mutes - a runner that is offline on purpose; an unreadable answer is skipped, never reported. Exit code 1 - when it reported something. `report/install-runner-watch.ps1` registers it as the scheduled task - `CI runner watch` (every five minutes, hidden, the owner's `gh` login, toasts through - `workstation-maintenance\notify.ps1`); run it from a normal PowerShell window of the owner's - session, with `-Ignore ` for a runner that is offline on purpose, and `-Remove` to retire it. - `--until 2026-10-14T11:00` ends the period in the past, so a baseline can be reproduced after later - changes; `--limit` raises the number of runs read per repository (default 300). - -- `standards/audit.py` (available): audits every repository of the organisation against - `standards/standards.json` and prints each deviation as `error`, `warning` or `info`: branch - deletion after merge, Dependabot, CODEOWNERS, secret scanning and a recognised license on public - repositories, a CI that calls the shared gate pinned by a full SHA with a `# vX.Y.Z` comment, too - many leftover branches, the organisation's two-factor requirement, Dependabot alerts that are off - or open past their deadline (critical 7, high 30, medium 90 days, only when a fix exists), - writable deploy keys, webhooks without a secret, an unprotected default branch on public - repositories, and an organisation that does not restrict actions to a list pinned by SHA. The - audit only reports; the owner changes keys, webhooks and two-factor. An exception names a - repository and a rule, gives a reason and expires; an expired one is itself an error. - `py -3 standards/audit.py [--fail-on error]`, or `report/ci_report.py --audit` to append it to the - weekly report. - -- `standards/bootstrap.py` (available): applies the organisation's repository settings to a new - repository: branch deletion after merge, secret scanning and push protection where they are free, - Dependabot alerts and security updates, and the `automerge` and `needs-human` labels the merge - train uses. A dry run by default; `--apply` makes the changes. - `py -3 standards/bootstrap.py owner/name [--apply]`. - ## Rules - No secrets, no business logic and no repository-specific values: everything comes in as an input. diff --git a/report/__pycache__/ci_report.cpython-312.pyc b/report/__pycache__/ci_report.cpython-312.pyc deleted file mode 100644 index 2d5d361..0000000 Binary files a/report/__pycache__/ci_report.cpython-312.pyc and /dev/null differ diff --git a/report/ci_report.py b/report/ci_report.py deleted file mode 100644 index 25838dc..0000000 --- a/report/ci_report.py +++ /dev/null @@ -1,619 +0,0 @@ -"""Weekly CI health report: failure rate by cause, durations, queue time and a snapshot of today. - - py -3 ci_report.py --repo owner/name --repo owner/other --days 7 - py -3 ci_report.py --config ..\\train\\repos.json --days 30 --output report.md - -Per repository, over the period: conclusive runs (success or failure) of one workflow, how many -failed, which share of those failures was the infrastructure and not the code, the median duration -and the median time a run waited for its first job to start. Cancelled runs are counted apart, never -as failures. The snapshot reports what is true now (runners, queue, open pull requests), because a -plan made from remembered state is how stale diagnoses happen. - -A failed run counts as infrastructure only when every failed job never reached its own steps -(`Set up job`, a job with no steps) or is the shared runner preflight. Anything else is code. -""" - -from __future__ import annotations - -import argparse -import datetime as dt -import hashlib -import importlib.util -import json -import statistics -import subprocess -import sys -from collections.abc import Callable -from dataclasses import dataclass, field -from pathlib import Path - -RUN_FIELDS = "databaseId,conclusion,status,workflowName,createdAt,startedAt,updatedAt,event,headBranch" -INFRA_STEPS = ("Set up job", "Complete job") -# The comment the merge train writes on every pull request it merges (train/automerge.py). -TRAIN_MARK = "" -TRAIN_SILENT_AFTER_MIN = 90 # the train writes a heartbeat every 60 minutes - - -def text_version(text: str) -> str: - """A short fingerprint of a script, the same for LF and CRLF copies (as in the train).""" - return hashlib.sha256(text.replace("\r\n", "\n").encode("utf-8")).hexdigest()[:12] - - -def run_gh(command: list[str]) -> str: - # Every command is built in this file from fixed words and GitHub's own numbers. - no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0) - return subprocess.run( - command, check=True, capture_output=True, text=True, creationflags=no_window - ).stdout - - -class Github: - """The few GitHub reads the report needs, over the `gh` command line.""" - - def __init__(self, run: Callable[[list[str]], str] = run_gh): - self._run = run - - def runs(self, repo: str, limit: int) -> list[dict]: - out = self._run( - [ - "gh", - "run", - "list", - "--repo", - repo, - "--limit", - str(limit), - "--json", - RUN_FIELDS, - ] - ) - return json.loads(out or "[]") - - def jobs(self, repo: str, run_id: int) -> list[dict]: - out = self._run( - ["gh", "run", "view", str(run_id), "--repo", repo, "--json", "jobs"] - ) - return json.loads(out or "{}").get("jobs", []) - - def job_timings(self, repo: str, run_id: int) -> list[dict]: - """The jobs of a run with `created_at` (when each became ready) and `started_at`: the - difference is the time it waited for a runner. `gh run view` does not give the former.""" - try: - out = self._run( - ["gh", "api", f"repos/{repo}/actions/runs/{run_id}/jobs?per_page=100"] - ) - except subprocess.CalledProcessError: - return [] # the run is gone or unreadable: no figure is better than a wrong one - return json.loads(out or "{}").get("jobs", []) - - def runners(self, repo: str) -> list[dict]: - try: - out = self._run(["gh", "api", f"repos/{repo}/actions/runners"]) - except subprocess.CalledProcessError: - return [] # no permission to list runners, or none registered - return json.loads(out or "{}").get("runners", []) - - def queued_runs(self, repo: str) -> list[dict]: - out = self._run( - [ - "gh", - "run", - "list", - "--repo", - repo, - "--status", - "queued", - "--json", - "databaseId,createdAt", - "--limit", - "50", - ] - ) - return json.loads(out or "[]") - - def merged_prs(self, repo: str, limit: int) -> list[dict]: - out = self._run( - [ - "gh", - "pr", - "list", - "--repo", - repo, - "--state", - "merged", - "--limit", - str(limit), - "--json", - "number,mergedAt,comments", - ] - ) - return json.loads(out or "[]") - - def file_text(self, repo: str, path: str) -> str | None: - try: - return self._run( - [ - "gh", - "api", - "-H", - "Accept: application/vnd.github.raw+json", - f"repos/{repo}/contents/{path}", - ] - ) - except subprocess.CalledProcessError: - return None - - def open_prs(self, repo: str) -> list[dict]: - out = self._run( - [ - "gh", - "pr", - "list", - "--repo", - repo, - "--state", - "open", - "--json", - "number,labels,createdAt", - "--limit", - "100", - ] - ) - return json.loads(out or "[]") - - -@dataclass -class RepoStats: - repo: str - conclusive: int = 0 - failed: int = 0 - cancelled: int = 0 - infra_failures: int = 0 - median_duration_s: float | None = None - median_queue_s: float | None = None - runners_online: int = 0 - runners_busy: int = 0 - runners_offline: int = 0 - queued_now: int = 0 - oldest_queued_min: int | None = None - open_prs: int = 0 - automerge_prs: int = 0 - # Only for repositories served by the shared merge train; None elsewhere. - merged_total: int | None = None - merged_by_hand: int | None = None - # Time each job of the sampled runs waited for a runner (created_at to started_at). - jobs_sampled: int = 0 - job_wait_median_s: float | None = None - job_wait_p90_s: float | None = None - job_wait_max_s: float | None = None - # (job name, median wait in seconds, jobs seen), the three that waited longest. - slowest_jobs: list[tuple[str, float, int]] = field(default_factory=list) - - @property - def fail_rate(self) -> float | None: - return self.failed / self.conclusive if self.conclusive else None - - @property - def infra_share(self) -> float | None: - return self.infra_failures / self.failed if self.failed else None - - -def classify_failure(jobs: list[dict]) -> str: - """'infra' when every failed job never reached its own steps, otherwise 'code'.""" - failed = [j for j in jobs if j.get("conclusion") == "failure"] - if not failed: - return "code" - return "infra" if all(_is_infra(j) for j in failed) else "code" - - -def _is_infra(job: dict) -> bool: - if "preflight" in (job.get("name") or "").lower(): - return True - failed_steps = [ - s["name"] for s in job.get("steps", []) if s.get("conclusion") == "failure" - ] - return not failed_steps or failed_steps[0] in INFRA_STEPS - - -def _parse(moment: str) -> dt.datetime: - return dt.datetime.fromisoformat(moment) - - -def job_waits(timings: list[dict]) -> list[tuple[str, float]]: - """(job name, seconds it waited for a runner) for the jobs that actually started.""" - waits = [] - for item in timings: - if item.get("conclusion") == "skipped": - continue - created, started = item.get("created_at"), item.get("started_at") - if not created or not started: - continue - seconds = (_parse(started) - _parse(created)).total_seconds() - waits.append((item.get("name") or "unnamed job", max(seconds, 0))) - return waits - - -def percentile(values: list[float], pct: int) -> float | None: - """Nearest-rank percentile; None for no values.""" - if not values: - return None - ordered = sorted(values) - rank = max(1, -(-len(ordered) * pct // 100)) # ceil without floats - return ordered[min(rank, len(ordered)) - 1] - - -def parse_moment(text: str) -> dt.datetime: - """A date, or a date and time, read as UTC.""" - moment = dt.datetime.fromisoformat(text) - return moment if moment.tzinfo else moment.replace(tzinfo=dt.UTC) - - -def collect( - gh, - repo: str, - workflow: str, - days: int, - now: dt.datetime, - sample: int = 30, - until: dt.datetime | None = None, - limit: int = 300, - train_repos: frozenset[str] | set[str] = frozenset(), - train_since: dt.datetime | None = None, -) -> RepoStats: - """Metrics for runs created in the `days` before `until` (default `now`). - - The snapshot (runners, queue, pull requests) is always about `now`. - """ - end = until or now - since = end - dt.timedelta(days=days) - runs = [ - r - for r in gh.runs(repo, limit) - if r.get("workflowName") == workflow and since <= _parse(r["createdAt"]) <= end - ] - conclusive = [r for r in runs if r.get("conclusion") in ("success", "failure")] - stats = RepoStats(repo=repo) - stats.conclusive = len(conclusive) - stats.cancelled = sum(1 for r in runs if r.get("conclusion") == "cancelled") - - for r in conclusive: - if r["conclusion"] != "failure": - continue - stats.failed += 1 - if classify_failure(gh.jobs(repo, r["databaseId"])) == "infra": - stats.infra_failures += 1 - - durations = [ - (_parse(r["updatedAt"]) - _parse(r["startedAt"])).total_seconds() - for r in conclusive - ] - if durations: - stats.median_duration_s = statistics.median(durations) - - waits = [] - for r in sorted(conclusive, key=lambda item: item["createdAt"], reverse=True)[ - :sample - ]: - starts = [ - j["startedAt"] for j in gh.jobs(repo, r["databaseId"]) if j.get("startedAt") - ] - if starts: - first = min(_parse(s) for s in starts) - waits.append((first - _parse(r["createdAt"])).total_seconds()) - if waits: - stats.median_queue_s = statistics.median(waits) - - by_job: dict[str, list[float]] = {} - for r in sorted(conclusive, key=lambda item: item["createdAt"], reverse=True)[ - :sample - ]: - for name, seconds in job_waits(gh.job_timings(repo, r["databaseId"])): - by_job.setdefault(name, []).append(seconds) - every = [seconds for group in by_job.values() for seconds in group] - if every: - stats.jobs_sampled = len(every) - stats.job_wait_median_s = statistics.median(every) - stats.job_wait_p90_s = percentile(every, 90) - stats.job_wait_max_s = max(every) - ranked = sorted( - ((n, statistics.median(g), len(g)) for n, g in by_job.items()), - key=lambda item: (-item[1], item[0]), - ) - stats.slowest_jobs = ranked[:3] - - for runner in gh.runners(repo): - if runner.get("status") == "online": - stats.runners_online += 1 - stats.runners_busy += 1 if runner.get("busy") else 0 - else: - stats.runners_offline += 1 - - queue = gh.queued_runs(repo) - stats.queued_now = len(queue) - if queue: - stats.oldest_queued_min = int( - max((now - _parse(q["createdAt"])).total_seconds() for q in queue) // 60 - ) - - prs = gh.open_prs(repo) - stats.open_prs = len(prs) - stats.automerge_prs = sum( - 1 - for p in prs - if "automerge" in {label["name"] for label in p.get("labels", [])} - ) - - if repo in train_repos: - floor = max(since, train_since) if train_since else since - merged = [ - m for m in gh.merged_prs(repo, 200) if floor <= _parse(m["mergedAt"]) <= end - ] - stats.merged_total = len(merged) - stats.merged_by_hand = sum( - 1 - for m in merged - if not any( - TRAIN_MARK in (c.get("body") or "") for c in m.get("comments", []) - ) - ) - return stats - - -@dataclass -class TrainHealth: - log_age_min: ( - int | None - ) # minutes since the log was last written; None without a log - silent: bool # no log line for too long - copy: str # current, stale, missing or unknown - installed_version: str | None = None - repository_version: str | None = None - - -def train_health( - train_dir: Path, - gh, - now: dt.datetime, - repo: str = "naindev-contrast3d/ci-shared", -) -> TrainHealth: - """Is the installed train alive and is it the script of `ci-shared` main?""" - train_dir = Path(train_dir) - script = train_dir / "automerge.py" - log = train_dir / "train.log" - - age = None - if log.exists(): - modified = dt.datetime.fromtimestamp(log.stat().st_mtime, dt.UTC) - age = int((now - modified).total_seconds() // 60) - silent = age is not None and age > TRAIN_SILENT_AFTER_MIN - - if not script.exists(): - return TrainHealth(age, silent, "missing") - installed = text_version(script.read_text(encoding="utf-8")) - published = gh.file_text(repo, "train/automerge.py") - if published is None: - return TrainHealth(age, silent, "unknown", installed_version=installed) - current = text_version(published) - return TrainHealth( - age, silent, "current" if installed == current else "stale", installed, current - ) - - -def render_train(health: TrainHealth) -> str: - lines = ["## Merge train", ""] - if health.copy == "missing": - lines.append("- Installed copy not found (the train is not installed here).") - return "\n".join(lines) - if health.log_age_min is None: - lines.append("- No log yet.") - elif health.silent: - lines.append( - f"- Warning: no log line for {health.log_age_min} min " - f"(the train writes a heartbeat every 60 minutes)." - ) - else: - lines.append(f"- Last log activity {health.log_age_min} min ago.") - if health.copy == "current": - lines.append("- The installed script matches ci-shared main.") - elif health.copy == "stale": - lines.append( - f"- Warning: the installed script differs from ci-shared main " - f"(installed {health.installed_version}, repository {health.repository_version})." - ) - else: - lines.append("- Could not read the script of ci-shared main to compare.") - return "\n".join(lines) - - -def fmt_duration(seconds: float | None) -> str: - if seconds is None: - return "-" - total = round(seconds) - if total < 60: - return f"{total}s" - if total < 3600: - return f"{total // 60}m{total % 60:02d}s" - return f"{total // 3600}h{(total % 3600) // 60:02d}m" - - -def _pct(value: float | None) -> str: - return "-" if value is None else f"{round(value * 100)}%" - - -def render( - stats: list[RepoStats], - days: int, - now: dt.datetime, - until: dt.datetime | None = None, -) -> str: - end = until or now - since = (end - dt.timedelta(days=days)).strftime("%Y-%m-%d") - lines = [ - "# CI health report", - "", - ( - f"Period: {since} to {end.strftime('%Y-%m-%d')} ({days} days). " - "Conclusive runs only; cancelled runs are not failures." - + ( - f" The snapshot is about now ({now.strftime('%Y-%m-%d %H:%M')} UTC)." - if until - else "" - ) - ), - "", - "| Repository | Runs | Failed | Fail rate | Infra share | Median duration | Median queue |", - "| --- | ---: | ---: | ---: | ---: | ---: | ---: |", - ] - for s in stats: - lines.append( - f"| {s.repo} | {s.conclusive} | {s.failed} | {_pct(s.fail_rate)} | {_pct(s.infra_share)}" - f" | {fmt_duration(s.median_duration_s)} | {fmt_duration(s.median_queue_s)} |" - ) - if any(s.jobs_sampled for s in stats): - lines += [ - "", - "## Queue time per job", - "", - "Time each job of the most recent runs waited for a runner, from the moment it was " - "ready to the moment it started. A job waits when every runner slot is taken, so a " - "high figure with few runners online asks for more slots; one with plenty of idle " - "runners points at the runner service instead.", - "", - "| Repository | Jobs | Median wait | p90 | Max | Slowest to start | Runners online |", - "| --- | ---: | ---: | ---: | ---: | --- | ---: |", - ] - for s in stats: - slowest = ", ".join( - f"{name} ({fmt_duration(wait)})" for name, wait, _ in s.slowest_jobs[:1] - ) - lines.append( - f"| {s.repo} | {s.jobs_sampled} | {fmt_duration(s.job_wait_median_s)}" - f" | {fmt_duration(s.job_wait_p90_s)} | {fmt_duration(s.job_wait_max_s)}" - f" | {slowest or '-'} | {s.runners_online} |" - ) - lines += ["", "## Snapshot", ""] - for s in stats: - lines.append(f"### {s.repo}") - if s.runners_online or s.runners_offline: - lines.append( - f"- Runners: {s.runners_online} online ({s.runners_busy} busy), {s.runners_offline} offline" - ) - else: - lines.append("- Runners: none registered (GitHub-hosted)") - oldest = ( - f" (oldest {s.oldest_queued_min} min)" - if s.oldest_queued_min is not None - else "" - ) - lines.append(f"- Queued now: {s.queued_now}{oldest}") - lines.append( - f"- Open pull requests: {s.open_prs} ({s.automerge_prs} labelled automerge)" - ) - if s.merged_by_hand is not None: - lines.append( - f"- Merged outside the train: {s.merged_by_hand} of {s.merged_total}" - ) - lines.append("") - return "\n".join(lines) - - -def load_audit(): - """The standards audit module, found beside this report (`../standards/audit.py`).""" - path = Path(__file__).resolve().parent.parent / "standards" / "audit.py" - spec = importlib.util.spec_from_file_location("standards_audit", path) - module = importlib.util.module_from_spec(spec) - sys.modules["standards_audit"] = module # dataclasses look the module up by name - spec.loader.exec_module(module) - return module - - -def audit_section(audit_text: str) -> str: - """The audit report as a section of this one: its title becomes a second-level heading.""" - lines = audit_text.split("\n") - if lines and lines[0] == "# Standards audit": - lines[0] = "## Standards audit" - return "\n".join(lines) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument( - "--repo", action="append", default=[], help="owner/name; repeatable" - ) - parser.add_argument("--config", help="train repos.json: its repositories are added") - parser.add_argument("--days", type=int, default=7) - parser.add_argument("--workflow", default="CI") - parser.add_argument( - "--until", - help="end of the period, UTC (2026-10-14 or 2026-10-14T11:00); default now. " - "Use it to reproduce a baseline after later changes.", - ) - parser.add_argument( - "--limit", - type=int, - default=300, - help="runs read per repository (gh allows up to 1000)", - ) - parser.add_argument( - "--audit", - action="store_true", - help="append the standards audit of the organisation", - ) - parser.add_argument( - "--train-dir", - help="folder of the installed merge train (automerge.py and train.log): adds its health", - ) - parser.add_argument( - "--train-since", - help="UTC date the shared train started serving the repositories of --config; " - "earlier merges are not counted as made around it", - ) - parser.add_argument("--output", help="write the report here instead of printing it") - args = parser.parse_args(argv) - - repos = list(args.repo) - train_repos: set[str] = set() - if args.config: - data = json.loads(Path(args.config).read_text(encoding="utf-8")) - train_repos = {entry["repo"] for entry in data.get("repos", [])} - repos += sorted(train_repos) - if not repos: - print("give at least one --repo or a --config", file=sys.stderr) - return 2 - - now = dt.datetime.now(dt.UTC) - gh = Github() - until = parse_moment(args.until) if args.until else None - train_since = parse_moment(args.train_since) if args.train_since else None - stats = [ - collect( - gh, - repo, - args.workflow, - args.days, - now, - until=until, - limit=args.limit, - train_repos=train_repos, - train_since=train_since, - ) - for repo in repos - ] - text = render(stats, args.days, now, until=until) - if args.train_dir: - text += "\n\n" + render_train(train_health(Path(args.train_dir), gh, now)) - if args.audit: - audit = load_audit() - standard_path = Path(audit.__file__).with_name("standards.json") - text += "\n\n" + audit_section( - audit.render(audit.run(standard_path, now=now), now) - ) - if args.output: - Path(args.output).write_text(text + "\n", encoding="utf-8") - else: - print(text) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/report/install-runner-watch.ps1 b/report/install-runner-watch.ps1 deleted file mode 100644 index 9a3c4e8..0000000 --- a/report/install-runner-watch.ps1 +++ /dev/null @@ -1,78 +0,0 @@ -# Installs the runner watchdog on the desktop: every five minutes, one cycle of runner_watch.py, and a -# Windows toast when a runner of the organisation is offline or a run waits too long for one. Run it -# from a normal PowerShell window of the owner's session: scheduled tasks created from a sandboxed -# or elevated shell can be private to that shell. -# -# powershell -NoProfile -ExecutionPolicy Bypass -File report\install-runner-watch.ps1 -# powershell -NoProfile -ExecutionPolicy Bypass -File report\install-runner-watch.ps1 -Remove -# -# The scripts are copied to $Destination, so the task does not depend on which branch a checkout is -# on; run this again after runner_watch.py changes. The task uses the owner's `gh` login; nothing -# else is stored. State lives in $Destination\runner-watch.json. -param( - [string]$Organisation = 'naindev-contrast3d', - [string]$Destination = 'D:\Development\Tools\ci-train\watch', - [string]$Notify = 'D:\Development\Tools\workstation-maintenance\notify.ps1', - # Runners that are offline on purpose and must never raise a toast. - [string[]]$Ignore = @(), - [int]$OfflineMinutes = 10, - [int]$QueueMinutes = 15, - [switch]$Remove -) - -$ErrorActionPreference = 'Stop' -$taskName = 'CI runner watch' - -if ($Remove) { - Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue - Write-Host "Task '$taskName' removed. Files in $Destination are left in place." - exit 0 -} - -if (-not (Get-Command gh -ErrorAction SilentlyContinue)) { throw 'gh is not installed' } -gh auth status *> $null -if ($LASTEXITCODE -ne 0) { throw 'gh is not signed in: run gh auth login' } -if (-not (Test-Path $Notify)) { throw "notify.ps1 not found at $Notify (pass -Notify)" } - -# The real pythonw.exe, not the `pyw` launcher (see train\install.ps1 for why). -$python = (py -3 -c "import sys;print(sys.executable)") -$pythonw = Join-Path (Split-Path $python) 'pythonw.exe' -if (-not (Test-Path $pythonw)) { throw "pythonw.exe not found at $pythonw" } - -New-Item -ItemType Directory -Force -Path $Destination | Out-Null -foreach ($file in 'runner_watch.py', 'ci_report.py') { - Copy-Item -Force (Join-Path $PSScriptRoot $file) (Join-Path $Destination $file) -} -$script = Join-Path $Destination 'runner_watch.py' -$state = Join-Path $Destination 'runner-watch.json' - -$arguments = "`"$script`" --org $Organisation --notify `"$Notify`" --state `"$state`"" + - " --offline-min $OfflineMinutes --queue-min $QueueMinutes" -foreach ($name in $Ignore) { $arguments += " --ignore `"$name`"" } - -# pythonw: no console window flashing every five minutes. No -WorkingDirectory (see the train). -$action = New-ScheduledTaskAction -Execute $pythonw -Argument $arguments -$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) ` - -RepetitionInterval (New-TimeSpan -Minutes 5) -$settings = New-ScheduledTaskSettingsSet ` - -MultipleInstances IgnoreNew ` - -ExecutionTimeLimit (New-TimeSpan -Minutes 3) ` - -AllowStartIfOnBatteries ` - -DontStopIfGoingOnBatteries ` - -StartWhenAvailable -$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" ` - -LogonType Interactive -RunLevel Limited - -Register-ScheduledTask ` - -TaskName $taskName ` - -Action $action ` - -Trigger $trigger ` - -Settings $settings ` - -Principal $principal ` - -Description "Toast when a runner of $Organisation is offline for $OfflineMinutes min or a run is queued for $QueueMinutes min." ` - -Force | Out-Null - -Write-Host "Task '$taskName' installed: every 5 minutes." -Write-Host " State: $state" -Write-Host " Try now: py -3 `"$script`" --org $Organisation --state `"$state`"" -Write-Host " Remove: report\install-runner-watch.ps1 -Remove" diff --git a/report/install-weekly-report.ps1 b/report/install-weekly-report.ps1 deleted file mode 100644 index 363c043..0000000 --- a/report/install-weekly-report.ps1 +++ /dev/null @@ -1,69 +0,0 @@ -# Installs the weekly CI report on the desktop: every Monday at 08:00 it writes the report of the -# organisation to a file and raises a Windows toast only when the week deviates. Run it from a normal -# PowerShell window of the owner's session: scheduled tasks created from a sandboxed or elevated shell -# can be private to that shell. -# -# powershell -NoProfile -ExecutionPolicy Bypass -File report\install-weekly-report.ps1 -# powershell -NoProfile -ExecutionPolicy Bypass -File report\install-weekly-report.ps1 -Remove -# -# The scripts are copied to $Destination, so the task does not depend on which branch a checkout is on; -# run this again after weekly_report.py changes. The task uses the owner's `gh` login; nothing else is -# stored. Reports land in $Destination\reports as ci-report-.md, with a copy as latest.md. -param( - [string]$Organisation = 'naindev-contrast3d', - [string]$Destination = 'D:\Development\Tools\ci-train\weekly', - [string]$Notify = 'D:\Development\Tools\workstation-maintenance\notify.ps1', - [switch]$Remove -) - -$ErrorActionPreference = 'Stop' -$taskName = 'CI weekly report' - -if ($Remove) { - Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue - Write-Host "Task '$taskName' removed. Files in $Destination are left in place." - exit 0 -} - -if (-not (Get-Command gh -ErrorAction SilentlyContinue)) { throw 'gh is not installed' } -gh auth status *> $null -if ($LASTEXITCODE -ne 0) { throw 'gh is not signed in: run gh auth login' } -if (-not (Test-Path $Notify)) { throw "notify.ps1 not found at $Notify (pass -Notify)" } - -# The real pythonw.exe, not the `pyw` launcher (see train\install.ps1 for why). -$python = (py -3 -c "import sys;print(sys.executable)") -$pythonw = Join-Path (Split-Path $python) 'pythonw.exe' -if (-not (Test-Path $pythonw)) { throw "pythonw.exe not found at $pythonw" } - -New-Item -ItemType Directory -Force -Path $Destination | Out-Null -foreach ($file in 'weekly_report.py', 'runner_watch.py', 'ci_report.py') { - Copy-Item -Force (Join-Path $PSScriptRoot $file) (Join-Path $Destination $file) -} -$script = Join-Path $Destination 'weekly_report.py' -$reports = Join-Path $Destination 'reports' - -$arguments = "`"$script`" --org $Organisation --out-dir `"$reports`" --notify `"$Notify`"" -$action = New-ScheduledTaskAction -Execute $pythonw -Argument $arguments -$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday -At 8:00 -$settings = New-ScheduledTaskSettingsSet ` - -MultipleInstances IgnoreNew ` - -ExecutionTimeLimit (New-TimeSpan -Minutes 15) ` - -AllowStartIfOnBatteries ` - -DontStopIfGoingOnBatteries ` - -StartWhenAvailable -$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" ` - -LogonType Interactive -RunLevel Limited - -Register-ScheduledTask ` - -TaskName $taskName ` - -Action $action ` - -Trigger $trigger ` - -Settings $settings ` - -Principal $principal ` - -Description "Writes the CI report of $Organisation to a file every Monday and toasts when the week deviates." ` - -Force | Out-Null - -Write-Host "Task '$taskName' installed: every Monday at 08:00 (or at the next start if the desktop was off)." -Write-Host " Reports: $reports" -Write-Host " Try now: py -3 `"$script`" --org $Organisation --out-dir `"$reports`"" -Write-Host " Remove: report\install-weekly-report.ps1 -Remove" diff --git a/report/runner_watch.py b/report/runner_watch.py deleted file mode 100644 index eafcc28..0000000 --- a/report/runner_watch.py +++ /dev/null @@ -1,257 +0,0 @@ -"""Runner watchdog: a toast when a self-hosted runner is offline or a run waits too long in the queue. - - py -3 runner_watch.py --org naindev-contrast3d --notify D:\\...\\notify.ps1 - -Run it from a scheduled task every few minutes. Each cycle reads, over `gh`, the runners of the -organisation and of every private repository in it, plus the runs still queued. It reports a runner -that has been seen offline for `--offline-min` minutes (GitHub does not say since when, so the first -sighting is remembered in the state file) and a run queued for `--queue-min` minutes. Every finding -is reported once, and again only after it has gone away and come back. An unreadable answer is -skipped, never reported: a watchdog that cries wolf on a network blip gets muted. - -The report in this folder (`ci_report.py`) says how the queue behaved over a period; this says that -it is wrong now. -""" - -from __future__ import annotations - -import argparse -import datetime as dt -import json -import subprocess -import sys -from collections.abc import Callable -from dataclasses import dataclass -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import ci_report # same folder; its Github class does the `gh` reads - -STAMP = "%Y-%m-%dT%H:%M:%SZ" -OFFLINE_MIN = 10 -QUEUE_MIN = 15 - - -@dataclass -class Alert: - key: str - title: str - body: str - - -class Github(ci_report.Github): - """The reads of the report plus the two the watchdog needs at organisation scope.""" - - def org_runners(self, org: str) -> list[dict]: - out = self._run(["gh", "api", f"orgs/{org}/actions/runners?per_page=100"]) - return json.loads(out or "{}").get("runners", []) - - def org_repos(self, org: str) -> list[dict]: - out = self._run( - [ - "gh", - "repo", - "list", - org, - "--limit", - "100", - "--json", - "name,visibility,isArchived", - ] - ) - return json.loads(out or "[]") - - -def collect(gh, org: str) -> dict: - """What GitHub says now: (scope, runner name, status) and (repository, run id, created at).""" - runners: list[tuple[str, str, str]] = [] - queued: list[tuple[str, int, str]] = [] - try: - for runner in gh.org_runners(org): - runners.append((org, runner["name"], runner["status"])) - except subprocess.CalledProcessError: - pass - try: - repos = gh.org_repos(org) - except subprocess.CalledProcessError: - repos = [] - for repo in repos: - if repo.get("isArchived") or repo.get("visibility") != "PRIVATE": - continue - scope = f"{org}/{repo['name']}" - try: - for runner in gh.runners(scope): - runners.append((scope, runner["name"], runner["status"])) - except subprocess.CalledProcessError: - pass - try: - for item in gh.queued_runs(scope): - queued.append((scope, item["databaseId"], item["createdAt"])) - except subprocess.CalledProcessError: - pass - return {"runners": runners, "queued": queued} - - -def _moment(text: str) -> dt.datetime: - return dt.datetime.fromisoformat(text.replace("Z", "+00:00")) - - -def evaluate( - snapshot: dict, - state: dict, - now: dt.datetime, - offline_min: int = OFFLINE_MIN, - queue_min: int = QUEUE_MIN, - ignore=frozenset(), -) -> tuple[list[Alert], dict]: - """The alerts that are new now, and the state to keep for the next cycle.""" - alerted = set(state.get("alerted", [])) - seen_offline = dict(state.get("offline_since", {})) - new_offline: dict[str, str] = {} - active: set[str] = set() - alerts: list[Alert] = [] - - for scope, name, status in snapshot["runners"]: - if name in ignore or status == "online": - continue - key = f"{scope}/{name}" - since = seen_offline.get(key) or now.strftime(STAMP) - new_offline[key] = since - minutes = int((now - _moment(since)).total_seconds() // 60) - if minutes < offline_min: - continue - alert_key = f"offline:{key}" - active.add(alert_key) - if alert_key not in alerted: - alerts.append( - Alert( - alert_key, - "Runner offline", - f"{name} ({scope}) has been offline for {minutes} min.", - ) - ) - - for scope, run_id, created in snapshot["queued"]: - minutes = int((now - _moment(created)).total_seconds() // 60) - if minutes < queue_min: - continue - alert_key = f"queue:{scope}/{run_id}" - active.add(alert_key) - if alert_key not in alerted: - alerts.append( - Alert( - alert_key, - "CI run waiting for a runner", - f"A run of {scope} has been queued for {minutes} min.", - ) - ) - - kept = sorted((alerted & active) | {a.key for a in alerts}) - return alerts, {"offline_since": new_offline, "alerted": kept} - - -def notify( - alerts: list[Alert], notify_path: str, runner: Callable[[list[str]], object] -) -> None: - """One toast per alert through the desktop's own `notify.ps1`; a failing toast never raises.""" - for alert in alerts: - command = [ - "powershell.exe", - "-NoProfile", - "-ExecutionPolicy", - "Bypass", - "-File", - notify_path, - "-Title", - alert.title, - "-Body", - alert.body, - ] - try: - runner(command) - except (OSError, subprocess.SubprocessError): - pass - - -def load_state(path: Path) -> dict: - try: - data = json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError): - return {} - return data if isinstance(data, dict) else {} - - -def save_state(path: Path, state: dict) -> None: - scratch = path.with_name(path.name + ".tmp") - scratch.write_text( - json.dumps(state, indent=1, sort_keys=True), encoding="utf-8", newline="\n" - ) - scratch.replace(path) - - -def _run_hidden(command: list[str]) -> None: - no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0) - subprocess.run(command, check=False, capture_output=True, creationflags=no_window) - - -def run( - gh, - org: str, - state_path: Path, - now: dt.datetime, - *, - notify_path: str | None, - offline_min: int = OFFLINE_MIN, - queue_min: int = QUEUE_MIN, - ignore=frozenset(), - runner: Callable[[list[str]], object] = _run_hidden, -) -> list[Alert]: - alerts, state = evaluate( - collect(gh, org), load_state(state_path), now, offline_min, queue_min, ignore - ) - if notify_path: - notify(alerts, notify_path, runner) - save_state(state_path, state) - return alerts - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--org", required=True, help="the organisation to watch") - parser.add_argument( - "--state", help="JSON remembered between cycles (default: beside this file)" - ) - parser.add_argument( - "--notify", help="path of notify.ps1: one toast per new finding" - ) - parser.add_argument("--offline-min", type=int, default=OFFLINE_MIN) - parser.add_argument("--queue-min", type=int, default=QUEUE_MIN) - parser.add_argument( - "--ignore", - action="append", - default=[], - help="a runner name never reported; repeatable", - ) - args = parser.parse_args(argv) - state = ( - Path(args.state) - if args.state - else Path(__file__).resolve().with_name("runner-watch.json") - ) - alerts = run( - Github(), - args.org, - state, - dt.datetime.now(dt.UTC), - notify_path=args.notify, - offline_min=args.offline_min, - queue_min=args.queue_min, - ignore=frozenset(args.ignore), - ) - for alert in alerts: - print(f"{alert.title}: {alert.body}") - return 1 if alerts else 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/report/weekly_report.py b/report/weekly_report.py deleted file mode 100644 index 021bce4..0000000 --- a/report/weekly_report.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Weekly CI report to a file, with a toast only when the week deviates. - - py -3 weekly_report.py --org naindev-contrast3d --out-dir D:\\...\\reports --notify D:\\...\\notify.ps1 - -Run it from a scheduled task once a week. It reads, over `gh`, every private repository of the -organisation that is not archived and writes `ci-report-.md` (and a copy as `latest.md`) in the -format of `ci_report.py`: failure rate by cause, durations, queue time per job and a snapshot of today. -A week that deviates (a failure rate, a queue or an infrastructure share above its threshold) puts the -deviations at the top of the report and raises one toast; a healthy week raises nothing, because a -notification that always fires is one nobody reads. An unreadable repository is skipped and said in the -report, never fatal. -""" - -from __future__ import annotations - -import argparse -import datetime as dt -import subprocess -import sys -from collections.abc import Callable -from pathlib import Path -from typing import NamedTuple - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import ci_report -import runner_watch - -FAIL_RATE_MAX = 0.25 -WAIT_P90_MAX_S = 300 -INFRA_SHARE_MAX = 0.2 -MIN_RUNS = 5 # below this, a rate is noise -MIN_FAILURES = 3 # below this, an infrastructure share is noise - - -class Result(NamedTuple): - path: Path - deviations: list[str] - - -def find_deviations( - stats: list[ci_report.RepoStats], - fail_rate_max: float = FAIL_RATE_MAX, - wait_p90_max: float = WAIT_P90_MAX_S, - infra_share_max: float = INFRA_SHARE_MAX, - min_runs: int = MIN_RUNS, -) -> list[str]: - """One sentence per repository and finding that is over its threshold.""" - found: list[str] = [] - for s in stats: - rate = s.fail_rate - if rate is not None and s.conclusive >= min_runs and rate > fail_rate_max: - found.append( - f"{s.repo}: {ci_report._pct(rate)} of the runs failed ({s.failed} of {s.conclusive})" - ) - if s.job_wait_p90_s is not None and s.job_wait_p90_s > wait_p90_max: - found.append( - f"{s.repo}: the p90 wait for a runner was {ci_report.fmt_duration(s.job_wait_p90_s)}" - ) - share = s.infra_share - if share is not None and s.failed >= MIN_FAILURES and share > infra_share_max: - found.append( - f"{s.repo}: {s.infra_failures} of {s.failed} failures were the infrastructure" - ) - return found - - -def collect_all(gh, org: str, days: int, now: dt.datetime, limit: int): - """Stats of every private, non-archived repository; the unreadable ones are named apart.""" - stats: list[ci_report.RepoStats] = [] - skipped: list[str] = [] - for repo in gh.org_repos(org): - if repo.get("isArchived") or repo.get("visibility") != "PRIVATE": - continue - scope = f"{org}/{repo['name']}" - try: - stats.append(ci_report.collect(gh, scope, "CI", days, now, limit=limit)) - except (subprocess.CalledProcessError, ValueError, KeyError) as exc: - skipped.append(f"{scope}: {type(exc).__name__}") - return stats, skipped - - -def run( - gh, - org: str, - out_dir: Path, - now: dt.datetime, - *, - days: int = 7, - limit: int = 300, - notify_path: str | None = None, - fail_rate_max: float = FAIL_RATE_MAX, - wait_p90_max: float = WAIT_P90_MAX_S, - infra_share_max: float = INFRA_SHARE_MAX, - runner: Callable[[list[str]], object] = runner_watch._run_hidden, -) -> Result: - stats, skipped = collect_all(gh, org, days, now, limit) - deviations = find_deviations(stats, fail_rate_max, wait_p90_max, infra_share_max) - text = ci_report.render(stats, days, now) - head = "" - if deviations: - head = "## Deviations\n\n" + "\n".join(f"- {d}" for d in deviations) + "\n\n" - if skipped: - head += "## Not read\n\n" + "\n".join(f"- {s}" for s in skipped) + "\n\n" - if head: - first, _, rest = text.partition("\n\n") - text = first + "\n\n" + head + rest - out_dir.mkdir(parents=True, exist_ok=True) - path = out_dir / f"ci-report-{now.strftime('%Y-%m-%d')}.md" - path.write_text(text, encoding="utf-8", newline="\n") - (out_dir / "latest.md").write_text(text, encoding="utf-8", newline="\n") - if deviations and notify_path: - shown = "; ".join(deviations[:3]) + (" ..." if len(deviations) > 3 else "") - runner_watch.notify( - [ - runner_watch.Alert( - f"weekly:{now.strftime('%Y-%m-%d')}", - f"CI weekly report: {len(deviations)} deviation(s)", - shown, - ) - ], - notify_path, - runner, - ) - return Result(path, deviations) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--org", required=True) - parser.add_argument( - "--out-dir", - help="where the reports go (default: a reports folder beside this file)", - ) - parser.add_argument("--days", type=int, default=7) - parser.add_argument( - "--limit", type=int, default=300, help="runs read per repository" - ) - parser.add_argument( - "--notify", help="path of notify.ps1: one toast when the week deviates" - ) - parser.add_argument("--fail-rate-max", type=float, default=FAIL_RATE_MAX) - parser.add_argument( - "--wait-p90-max", type=float, default=WAIT_P90_MAX_S, help="seconds" - ) - parser.add_argument("--infra-share-max", type=float, default=INFRA_SHARE_MAX) - args = parser.parse_args(argv) - out_dir = ( - Path(args.out_dir) - if args.out_dir - else Path(__file__).resolve().with_name("reports") - ) - result = run( - runner_watch.Github(), - args.org, - out_dir, - dt.datetime.now(dt.UTC), - days=args.days, - limit=args.limit, - notify_path=args.notify, - fail_rate_max=args.fail_rate_max, - wait_p90_max=args.wait_p90_max, - infra_share_max=args.infra_share_max, - ) - print(f"report: {result.path}") - for deviation in result.deviations: - print(f"deviation: {deviation}") - return 1 if result.deviations else 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/standards/audit.py b/standards/audit.py deleted file mode 100644 index d43f966..0000000 --- a/standards/audit.py +++ /dev/null @@ -1,483 +0,0 @@ -"""Audit the repositories of an organisation against a written standard. - - py -3 audit.py # print the deviations - py -3 audit.py --fail-on error # exit 1 when there is an error (for a CI step) - -The standard is `standards.json` beside this script: thresholds, the severity of each rule and the -exceptions. An exception names a repository and a rule, says why, and expires; an expired exception -stops silencing the rule and is itself an error, so "on purpose" cannot turn into "forgotten". -Severities: `error` breaks a guarantee, `warning` is hygiene, `info` is an observation. - -Rules (per repository unless noted): delete-branch-on-merge, dependabot-config, codeowners, -secret-scanning (public repositories, where it is free), license (public repositories), -has-ci, shared-gate, gate-pin (the shared gate is pinned by a full commit SHA with a vX.Y.Z comment, -which is what online zizmor verifies), topic-branches, dependabot-alerts (off) and -dependabot-overdue (an open alert with a patched version past its deadline, 7/30/90 days for -critical/high/medium, `dependency_deadline_days` overrides), deploy-key-write, webhook-secret, -branch-protection (public repositories, where it is free), and for the organisation org-2fa, -org-2fa-method and actions-allowlist (actions restricted to a list and pinned by SHA). The audit -only reports: deploy keys, webhooks and two-factor are the owner's to change. Archived -repositories are skipped. -""" - -from __future__ import annotations - -import argparse -import datetime as dt -import json -import re -import subprocess -import sys -from collections.abc import Callable -from dataclasses import dataclass -from pathlib import Path - -SEVERITIES = ("error", "warning", "info") -GATE_REFERENCE = "naindev-contrast3d/ci-shared/.github/workflows/" -GOOD_PIN = re.compile(r"@[0-9a-f]{40}\s+#\s+v\d+\.\d+\.\d+\b") - -DEFAULT_SEVERITY = { - "delete-branch-on-merge": "error", - "dependabot-config": "error", - "license": "error", - "gate-pin": "error", - "org-2fa": "error", - "exception-expired": "error", - "codeowners": "warning", - "secret-scanning": "warning", - "has-ci": "warning", - "shared-gate": "warning", - "topic-branches": "warning", - "org-2fa-method": "warning", - "dependabot-alerts": "warning", - "dependabot-overdue": "warning", - "branch-protection": "warning", - "deploy-key-write": "warning", - "webhook-secret": "info", - "actions-allowlist": "warning", -} - -# Days an open alert with a patched version may stay open, by severity (spec org-security-baseline -# FR1). `dependency_deadline_days` in the standard overrides it; a missing severity has no deadline. -DEFAULT_DEADLINE_DAYS = {"critical": 7, "high": 30, "medium": 90} - - -class StandardError(ValueError): - """The standard file cannot be used.""" - - -@dataclass(frozen=True) -class Finding: - repo: str - rule: str - severity: str - message: str - - -def run_gh(command: list[str]) -> str: - # Every command is built in this file from fixed words and names GitHub returned. - no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0) - return subprocess.run( - command, - check=True, - capture_output=True, - text=True, - encoding="utf-8", - creationflags=no_window, - ).stdout - - -class Github: - """The reads the audit needs, over the `gh` command line.""" - - def __init__(self, run: Callable[[list[str]], str] = run_gh): - self._run = run - - def org(self, org: str) -> dict: - return json.loads(self._run(["gh", "api", f"orgs/{org}"]) or "{}") - - def org_repos(self, org: str) -> list[dict]: - out = self._run( - [ - "gh", - "api", - f"orgs/{org}/repos?per_page=100&type=all", - "--paginate", - "--slurp", - ] - ) - listed = json.loads(out or "[]") - if listed and isinstance(listed[0], list): # --slurp returns one array per page - listed = [item for page in listed for item in page] - repos = [] - for entry in listed: - # The list endpoint omits settings such as delete_branch_on_merge: read each one. - detail = json.loads( - self._run(["gh", "api", f"repos/{org}/{entry['name']}"]) or "{}" - ) - repos.append(detail if isinstance(detail, dict) and detail else entry) - return repos - - def file_text(self, full_name: str, path: str) -> str | None: - try: - return self._run( - [ - "gh", - "api", - "-H", - "Accept: application/vnd.github.raw+json", - f"repos/{full_name}/contents/{path}", - ] - ) - except subprocess.CalledProcessError: - return None - - def dir_names(self, full_name: str, path: str) -> list[str]: - try: - out = self._run(["gh", "api", f"repos/{full_name}/contents/{path}"]) - except subprocess.CalledProcessError: - return [] - listing = json.loads(out or "[]") - return [item["name"] for item in listing] if isinstance(listing, list) else [] - - def branches(self, full_name: str) -> list[str]: - out = self._run( - [ - "gh", - "api", - f"repos/{full_name}/branches?per_page=100", - "--paginate", - "--jq", - ".[].name", - ] - ) - return [line.strip() for line in out.splitlines() if line.strip()] - - def insecure_two_factor_members(self, org: str) -> list[str]: - try: - out = self._run(["gh", "api", f"orgs/{org}/members?filter=2fa_insecure"]) - except subprocess.CalledProcessError: - return [] # needs organisation owner rights - return [member["login"] for member in json.loads(out or "[]")] - - def org_actions_permissions(self, org: str) -> dict: - try: - return json.loads(self._run(["gh", "api", f"orgs/{org}/actions/permissions"]) or "{}") - except subprocess.CalledProcessError: - return {} # needs organisation owner rights - - def dependabot_alerts(self, full_name: str) -> list[dict] | None: - """Open alerts, or None when Dependabot alerts are disabled or cannot be read.""" - try: - out = self._run( - [ - "gh", - "api", - f"repos/{full_name}/dependabot/alerts?state=open&per_page=100", - "--paginate", - "--slurp", - ] - ) - except subprocess.CalledProcessError: - return None - pages = json.loads(out or "[]") - return [item for page in pages for item in page] if pages and isinstance(pages[0], list) else pages - - def branch_protected(self, full_name: str, branch: str) -> bool: - try: - self._run(["gh", "api", f"repos/{full_name}/branches/{branch}/protection"]) - except subprocess.CalledProcessError: - return False - return True - - def deploy_keys(self, full_name: str) -> list[dict]: - try: - return json.loads(self._run(["gh", "api", f"repos/{full_name}/keys"]) or "[]") - except subprocess.CalledProcessError: - return [] - - def hooks(self, full_name: str) -> list[dict]: - try: - return json.loads(self._run(["gh", "api", f"repos/{full_name}/hooks"]) or "[]") - except subprocess.CalledProcessError: - return [] - - -def validate_standard(standard: dict) -> None: - for rule, severity in standard.get("severity", {}).items(): - if severity not in SEVERITIES: - raise StandardError( - f"severity of {rule} must be one of {', '.join(SEVERITIES)}" - ) - for item in standard.get("exceptions", []): - for key in ("repo", "rule", "reason", "expires"): - if not item.get(key): - raise StandardError(f"every exception needs `{key}`: {item}") - try: - dt.date.fromisoformat(item["expires"]) - except ValueError as exc: - raise StandardError( - f"`expires` must be a date (YYYY-MM-DD): {item}" - ) from exc - - -def audit(gh, standard: dict, now: dt.datetime) -> list[Finding]: - validate_standard(standard) - org = standard["organisation"] - today = now.date() - severity = {**DEFAULT_SEVERITY, **standard.get("severity", {})} - exceptions = standard.get("exceptions", []) - active = { - (item["repo"], item["rule"]) - for item in exceptions - if dt.date.fromisoformat(item["expires"]) >= today - } - findings: list[Finding] = [] - - def add(repo: str, rule: str, message: str, level: str | None = None) -> None: - if (repo, rule) in active: - return - findings.append(Finding(repo, rule, level or severity[rule], message)) - - for item in exceptions: - if dt.date.fromisoformat(item["expires"]) < today: - findings.append( - Finding( - item["repo"], - "exception-expired", - severity["exception-expired"], - f"the exception for `{item['rule']}` expired on {item['expires']} " - f"({item['reason']}); decide again", - ) - ) - - info = gh.org(org) - if not info.get("two_factor_requirement_enabled"): - add( - org, - "org-2fa", - "the organisation does not require two-factor authentication", - ) - insecure = gh.insecure_two_factor_members(org) - if insecure: - add( - org, - "org-2fa-method", - "members with an insecure second factor: " + ", ".join(insecure), - ) - permissions = gh.org_actions_permissions(org) - if permissions and ( - permissions.get("allowed_actions") != "selected" - or not permissions.get("sha_pinning_required") - ): - add( - org, - "actions-allowlist", - "actions are not restricted to a list or not pinned by SHA " - f"(allowed_actions={permissions.get('allowed_actions')}, " - f"sha_pinning_required={bool(permissions.get('sha_pinning_required'))})", - ) - - for repo in gh.org_repos(org): - if repo.get("archived"): - continue - full = repo["full_name"] - public = not repo.get("private", True) - _audit_repo(gh, standard, repo, full, public, now, add) - return findings - - -def _audit_security(gh, standard: dict, full: str, now: dt.datetime, add) -> None: - deadlines = {**DEFAULT_DEADLINE_DAYS, **standard.get("dependency_deadline_days", {})} - alerts = gh.dependabot_alerts(full) - if alerts is None: - add(full, "dependabot-alerts", "Dependabot alerts are disabled or cannot be read") - for item in alerts or []: - patched = (item.get("security_vulnerability") or {}).get("first_patched_version") - level = (item.get("security_advisory") or {}).get("severity") - if not patched or level not in deadlines: - continue # nothing to upgrade to yet, or a severity without a deadline - opened = dt.datetime.fromisoformat(item["created_at"].replace("Z", "+00:00")) - age = (now - opened).days - if age > deadlines[level]: - package = ((item.get("dependency") or {}).get("package") or {}).get("name", "?") - add( - full, - "dependabot-overdue", - f"{level} alert on `{package}` open {age} days, a fix exists " - f"(deadline {deadlines[level]} days)", - ) - for key in gh.deploy_keys(full): - if not key.get("read_only", True): - add(full, "deploy-key-write", f"deploy key `{key.get('title', '?')}` can write") - for hook in gh.hooks(full): - if hook.get("active") and not (hook.get("config") or {}).get("secret"): - add(full, "webhook-secret", "an active webhook has no secret (the URL is the credential)") - - -def _audit_repo( - gh, standard: dict, repo: dict, full: str, public: bool, now: dt.datetime, add -) -> None: - if not repo.get("delete_branch_on_merge"): - add( - full, - "delete-branch-on-merge", - "merged branches are not deleted automatically", - ) - - workflow_names = [ - name - for name in gh.dir_names(full, ".github/workflows") - if name.endswith((".yml", ".yaml")) - ] - if not workflow_names: - add(full, "has-ci", "no GitHub Actions workflow") - - has_dependabot = any( - gh.file_text(full, f".github/dependabot.{ext}") is not None - for ext in ("yml", "yaml") - ) - if not has_dependabot: - add( - full, - "dependabot-config", - "no .github/dependabot.yml", - "error" if workflow_names else "warning", - ) - - if not any( - gh.file_text(full, path) is not None - for path in (".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS") - ): - add(full, "codeowners", "no CODEOWNERS file") - - if public: - security = repo.get("security_and_analysis") or {} - scanning = (security.get("secret_scanning") or {}).get("status") == "enabled" - protection = (security.get("secret_scanning_push_protection") or {}).get( - "status" - ) == "enabled" - if not (scanning and protection): - add( - full, - "secret-scanning", - "secret scanning or push protection is off (free on public repositories)", - ) - spdx = (repo.get("license") or {}).get("spdx_id") - if spdx in (None, "NOASSERTION"): - add(full, "license", "GitHub does not recognise the license") - branch = repo.get("default_branch", "main") - if not gh.branch_protected(full, branch): - add( - full, - "branch-protection", - f"`{branch}` is not protected (free on public repositories)", - ) - - _audit_security(gh, standard, full, now, add) - _audit_gate(gh, workflow_names, full, add) - - limit = standard.get("max_topic_branches", 8) - topics = [b for b in gh.branches(full) if b != repo.get("default_branch", "main")] - if len(topics) > limit: - add( - full, - "topic-branches", - f"{len(topics)} branches besides the default one (limit {limit})", - ) - - -def _audit_gate(gh, workflow_names: list[str], full: str, add) -> None: - if not workflow_names: - return - references = [] - for name in workflow_names: - text = gh.file_text(full, f".github/workflows/{name}") or "" - references += [ - line - for line in text.splitlines() - if GATE_REFERENCE in line - and "uses:" in line - and not line.lstrip().startswith("#") - ] - if not references: - add(full, "shared-gate", "no workflow calls the shared gate of ci-shared") - return - if not all(GOOD_PIN.search(line) for line in references): - add( - full, - "gate-pin", - "the shared workflow must be pinned by a full commit SHA with a `# vX.Y.Z` comment", - ) - - -def exit_code(findings: list[Finding], fail_on: str | None) -> int: - if fail_on is None: - return 0 - levels = {"error": ("error",), "warning": ("error", "warning")}[fail_on] - return 1 if any(f.severity in levels for f in findings) else 0 - - -def render(findings: list[Finding], now: dt.datetime) -> str: - counts = { - level: sum(1 for f in findings if f.severity == level) for level in SEVERITIES - } - parts = [f"{counts['error']} error{'s' if counts['error'] != 1 else ''}"] - parts.append(f"{counts['warning']} warning{'s' if counts['warning'] != 1 else ''}") - if counts["info"]: - parts.append(f"{counts['info']} info") - lines = [ - "# Standards audit", - "", - f"{now.strftime('%Y-%m-%d')}: {', '.join(parts)}.", - "", - ] - if not findings: - lines.append("No deviations from the standard.") - return "\n".join(lines) - order = {level: index for index, level in enumerate(SEVERITIES)} - for repo in sorted({f.repo for f in findings}): - lines.append(f"### {repo}") - for f in sorted( - (x for x in findings if x.repo == repo), - key=lambda x: (order[x.severity], x.rule), - ): - lines.append(f"- {f.severity} `{f.rule}`: {f.message}") - lines.append("") - return "\n".join(lines) - - -def run( - standard_path: Path | str, gh=None, now: dt.datetime | None = None -) -> list[Finding]: - standard = json.loads(Path(standard_path).read_text(encoding="utf-8")) - return audit(gh or Github(), standard, now or dt.datetime.now(dt.UTC)) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument( - "--standard", default=str(Path(__file__).with_name("standards.json")) - ) - parser.add_argument( - "--fail-on", choices=("error", "warning"), help="exit 1 from this severity" - ) - parser.add_argument("--output", help="write the report here instead of printing it") - args = parser.parse_args(argv) - - now = dt.datetime.now(dt.UTC) - try: - findings = run(args.standard, now=now) - except StandardError as exc: - print(f"standard error: {exc}", file=sys.stderr) - return 2 - text = render(findings, now) - if args.output: - Path(args.output).write_text(text + "\n", encoding="utf-8") - else: - print(text) - return exit_code(findings, args.fail_on) - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/standards/bootstrap.py b/standards/bootstrap.py deleted file mode 100644 index 3d2ac89..0000000 --- a/standards/bootstrap.py +++ /dev/null @@ -1,226 +0,0 @@ -"""Apply the organisation's repository settings to a new repository. - - py -3 bootstrap.py owner/name # show what would change (dry run, the default) - py -3 bootstrap.py owner/name --apply # make the changes - -The settings come from the standards audit (audit.py): branch deletion after merge, secret -scanning and push protection where they are free (public repositories), Dependabot alerts and -security updates, and the two labels the merge train uses. Nothing is changed without --apply, and a -setting that already follows the standard is left alone. -""" - -from __future__ import annotations - -import argparse -import json -import os -import re -import subprocess -import sys -import tempfile -from collections.abc import Callable -from dataclasses import dataclass - -LABELS = { - "automerge": ( - "0E8A16", - "The merge train merges this pull request when its checks pass", - ), - "needs-human": ( - "D93F0B", - "A person must resolve this before the merge train retries", - ), -} -REPO_PATTERN = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$") - - -class BootstrapError(ValueError): - """The repository cannot be bootstrapped.""" - - -@dataclass(frozen=True) -class Change: - setting: str - current: str - wanted: str - - -def run_gh(command: list[str]) -> str: - # Every command is built in this file from fixed words and the repository name given. - no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0) - return subprocess.run( - command, - check=True, - capture_output=True, - text=True, - encoding="utf-8", - creationflags=no_window, - ).stdout - - -class Github: - def __init__(self, run: Callable[[list[str]], str] = run_gh): - self._run = run - - def repo(self, full_name: str) -> dict: - return json.loads(self._run(["gh", "api", f"repos/{full_name}"]) or "{}") - - def labels(self, full_name: str) -> list[str]: - out = self._run( - [ - "gh", - "api", - f"repos/{full_name}/labels?per_page=100", - "--paginate", - "--slurp", - ] - ) - listed = json.loads(out or "[]") - if listed and isinstance(listed[0], list): - listed = [item for page in listed for item in page] - return [item["name"] for item in listed] - - def alerts_enabled(self, full_name: str) -> bool: - try: - self._run(["gh", "api", f"repos/{full_name}/vulnerability-alerts"]) - except subprocess.CalledProcessError: - return False - return True - - def security_fixes_enabled(self, full_name: str) -> bool: - try: - out = self._run( - [ - "gh", - "api", - f"repos/{full_name}/automated-security-fixes", - "--jq", - ".enabled", - ] - ) - except subprocess.CalledProcessError: - return False - return out.strip() == "true" - - def patch_repo(self, full_name: str, fields: dict) -> None: - with tempfile.NamedTemporaryFile( - "w", suffix=".json", delete=False, encoding="utf-8" - ) as handle: - json.dump(fields, handle) - path = handle.name - try: - self._run( - ["gh", "api", "-X", "PATCH", f"repos/{full_name}", "--input", path] - ) - finally: - os.unlink(path) - - def create_label( - self, full_name: str, name: str, color: str, description: str - ) -> None: - self._run( - [ - "gh", - "api", - "-X", - "POST", - f"repos/{full_name}/labels", - "-f", - f"name={name}", - "-f", - f"color={color}", - "-f", - f"description={description}", - ] - ) - - def enable_alerts(self, full_name: str) -> None: - self._run(["gh", "api", "-X", "PUT", f"repos/{full_name}/vulnerability-alerts"]) - - def enable_security_fixes(self, full_name: str) -> None: - self._run( - ["gh", "api", "-X", "PUT", f"repos/{full_name}/automated-security-fixes"] - ) - - -def plan(gh, full_name: str) -> list[Change]: - repo = gh.repo(full_name) - if repo.get("archived"): - raise BootstrapError(f"{full_name} is archived") - changes: list[Change] = [] - if not repo.get("delete_branch_on_merge"): - changes.append(Change("delete_branch_on_merge", "off", "on")) - if not repo.get("private", True): - security = repo.get("security_and_analysis") or {} - for key in ("secret_scanning", "secret_scanning_push_protection"): - if (security.get(key) or {}).get("status") != "enabled": - changes.append(Change(key, "off", "on")) - existing = set(gh.labels(full_name)) - for name in LABELS: - if name not in existing: - changes.append(Change(f"label:{name}", "missing", "created")) - if not gh.alerts_enabled(full_name): - changes.append(Change("vulnerability_alerts", "off", "on")) - if not gh.security_fixes_enabled(full_name): - changes.append(Change("automated_security_fixes", "off", "on")) - return changes - - -def apply(gh, full_name: str, changes: list[Change], dry_run: bool) -> None: - if dry_run: - return - fields: dict = {} - security: dict = {} - for change in changes: - if change.setting == "delete_branch_on_merge": - fields["delete_branch_on_merge"] = True - elif change.setting in ("secret_scanning", "secret_scanning_push_protection"): - security[change.setting] = {"status": "enabled"} - if security: - fields["security_and_analysis"] = security - if fields: - gh.patch_repo(full_name, fields) - for change in changes: - if change.setting.startswith("label:"): - name = change.setting.removeprefix("label:") - color, description = LABELS[name] - gh.create_label(full_name, name, color, description) - elif change.setting == "vulnerability_alerts": - gh.enable_alerts(full_name) - elif change.setting == "automated_security_fixes": - gh.enable_security_fixes(full_name) - - -def render(changes: list[Change], full_name: str, dry_run: bool) -> str: - mode = "dry run: nothing changed" if dry_run else "applied" - lines = [f"# Bootstrap of {full_name} ({mode})", ""] - if not changes: - lines.append(f"{full_name} already follows the standard.") - for change in changes: - lines.append(f"- {change.setting}: {change.current} -> {change.wanted}") - return "\n".join(lines) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("repo", help="owner/name") - parser.add_argument( - "--apply", action="store_true", help="make the changes (default: dry run)" - ) - args = parser.parse_args(argv) - if not REPO_PATTERN.match(args.repo): - print("repo must look like owner/name", file=sys.stderr) - return 2 - gh = Github() - try: - changes = plan(gh, args.repo) - except BootstrapError as exc: - print(f"bootstrap error: {exc}", file=sys.stderr) - return 2 - apply(gh, args.repo, changes, dry_run=not args.apply) - print(render(changes, args.repo, dry_run=not args.apply)) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/standards/standards.json b/standards/standards.json deleted file mode 100644 index bc42174..0000000 --- a/standards/standards.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "organisation": "naindev-contrast3d", - "max_topic_branches": 8, - "severity": {}, - "exceptions": [ - { - "repo": "naindev-contrast3d/contrast-hub", - "rule": "shared-gate", - "reason": "its own `sello` job is the aggregate check and publishes the ci-ok seal (spec 365, ADR-0092)", - "expires": "2027-04-01" - }, - { - "repo": "naindev-contrast3d/ci-shared", - "rule": "shared-gate", - "reason": "it is the source of the gate and calls it by a local path in its own CI", - "expires": "2027-04-01" - }, - { - "repo": "naindev-contrast3d/.github", - "rule": "has-ci", - "reason": "the organisation profile repository holds only a README and community files", - "expires": "2027-04-01" - }, - { - "repo": "naindev-contrast3d/.github", - "rule": "dependabot-config", - "reason": "no workflows and no dependencies to update", - "expires": "2027-04-01" - }, - { - "repo": "naindev-contrast3d/.github", - "rule": "license", - "reason": "the organisation profile repository is documentation, not reusable code", - "expires": "2027-04-01" - }, - { - "repo": "naindev-contrast3d/dse", - "rule": "shared-gate", - "reason": "the session 'dse github move' is building its own CI; adoption is T23 of next-ci-reliability", - "expires": "2026-11-15" - } - ] -} diff --git a/tests/test_audit.py b/tests/test_audit.py deleted file mode 100644 index e3f71cb..0000000 --- a/tests/test_audit.py +++ /dev/null @@ -1,526 +0,0 @@ -"""Tests for standards/audit.py: each rule, the exceptions, the severities and the rendering.""" - -from __future__ import annotations - -import datetime as dt -import json -import subprocess -import sys -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "standards")) - -import audit - -ORG = "naindev-contrast3d" -NOW = dt.datetime(2026, 10, 14, 12, 0, 0, tzinfo=dt.UTC) -GOOD_PIN = ( - " uses: naindev-contrast3d/ci-shared/.github/workflows/gate.yml" - "@150de5008682330747ba6880f1649b388858c206 # v0.1.0\n" -) - - -def repo( - name, *, private=True, delete_branch=True, spdx="MIT", scanning=True, archived=False -): - status = "enabled" if scanning else "disabled" - return { - "name": name, - "full_name": f"{ORG}/{name}", - "private": private, - "visibility": "private" if private else "public", - "archived": archived, - "default_branch": "main", - "delete_branch_on_merge": delete_branch, - "allow_merge_commit": True, - "allow_squash_merge": True, - "allow_rebase_merge": True, - "license": {"spdx_id": spdx} if spdx else None, - "security_and_analysis": { - "secret_scanning": {"status": status}, - "secret_scanning_push_protection": {"status": status}, - }, - } - - -class FakeGithub: - def __init__( - self, - repos, - files=None, - dirs=None, - branches=None, - two_fa=True, - insecure=(), - alerts=None, - protected=True, - keys=None, - hooks=None, - actions=None, - ): - self._repos = repos - self._files = files or {} - self._dirs = dirs or {} - self._branches = branches or {} - self._two_fa = two_fa - self._insecure = list(insecure) - self._alerts = alerts or {} - self._protected = protected - self._keys = keys or {} - self._hooks = hooks or {} - self._actions = ( - {"allowed_actions": "selected", "sha_pinning_required": True} - if actions is None - else actions - ) - - def org(self, org): - return {"two_factor_requirement_enabled": self._two_fa} - - def org_actions_permissions(self, org): - return self._actions - - def dependabot_alerts(self, full_name): - return self._alerts.get(full_name, []) - - def branch_protected(self, full_name, branch): - return self._protected - - def deploy_keys(self, full_name): - return self._keys.get(full_name, []) - - def hooks(self, full_name): - return self._hooks.get(full_name, []) - - def org_repos(self, org): - return self._repos - - def file_text(self, full_name, path): - return self._files.get((full_name, path)) - - def dir_names(self, full_name, path): - return self._dirs.get((full_name, path), []) - - def branches(self, full_name): - return self._branches.get(full_name, ["main"]) - - def insecure_two_factor_members(self, org): - return self._insecure - - -def good_files(name): - full = f"{ORG}/{name}" - return ( - { - (full, ".github/dependabot.yml"): "version: 2\n", - (full, ".github/CODEOWNERS"): "* @Nain9Dev\n", - (full, ".github/workflows/ci.yml"): "jobs:\n gate:\n" + GOOD_PIN, - }, - {(full, ".github/workflows"): ["ci.yml"]}, - ) - - -def standard(**overrides): - base = { - "organisation": ORG, - "max_topic_branches": 8, - "severity": {}, - "exceptions": [], - } - base.update(overrides) - return base - - -def clean_world(**kw): - files, dirs = good_files("app") - return FakeGithub([repo("app")], files, dirs, **kw) - - -def rules(findings, name="app"): - return {f.rule for f in findings if f.repo == f"{ORG}/{name}"} - - -class Rules(unittest.TestCase): - def test_a_repository_that_follows_the_standard_has_no_findings(self): - self.assertEqual(audit.audit(clean_world(), standard(), NOW), []) - - def test_branch_deletion_after_merge_must_be_on(self): - files, dirs = good_files("app") - gh = FakeGithub([repo("app", delete_branch=False)], files, dirs) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual(rules(findings), {"delete-branch-on-merge"}) - self.assertEqual(findings[0].severity, "error") - - def test_dependabot_is_an_error_when_the_repository_has_workflows(self): - files, dirs = good_files("app") - del files[(f"{ORG}/app", ".github/dependabot.yml")] - findings = audit.audit(FakeGithub([repo("app")], files, dirs), standard(), NOW) - self.assertEqual(rules(findings), {"dependabot-config"}) - self.assertEqual(findings[0].severity, "error") - - def test_codeowners_is_a_warning_and_any_of_the_three_places_counts(self): - files, dirs = good_files("app") - del files[(f"{ORG}/app", ".github/CODEOWNERS")] - findings = audit.audit(FakeGithub([repo("app")], files, dirs), standard(), NOW) - self.assertEqual( - (rules(findings), findings[0].severity), ({"codeowners"}, "warning") - ) - files[(f"{ORG}/app", "docs/CODEOWNERS")] = "* @x\n" - self.assertEqual( - audit.audit(FakeGithub([repo("app")], files, dirs), standard(), NOW), [] - ) - - def test_a_public_repository_must_have_secret_scanning_and_push_protection(self): - files, dirs = good_files("pub") - gh = FakeGithub([repo("pub", private=False, scanning=False)], files, dirs) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual( - (rules(findings, "pub"), findings[0].severity), - ({"secret-scanning"}, "warning"), - ) - - def test_a_private_repository_is_not_asked_for_paid_secret_scanning(self): - files, dirs = good_files("app") - gh = FakeGithub([repo("app", private=True, scanning=False)], files, dirs) - self.assertEqual(audit.audit(gh, standard(), NOW), []) - - def test_a_public_repository_needs_a_license_github_recognises(self): - files, dirs = good_files("pub") - for spdx in ("NOASSERTION", None): - with self.subTest(spdx=spdx): - gh = FakeGithub([repo("pub", private=False, spdx=spdx)], files, dirs) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual( - (rules(findings, "pub"), findings[0].severity), - ({"license"}, "error"), - ) - - def test_a_private_repository_may_have_no_license(self): - files, dirs = good_files("app") - gh = FakeGithub([repo("app", spdx=None)], files, dirs) - self.assertEqual(audit.audit(gh, standard(), NOW), []) - - def test_a_repository_without_workflows_is_flagged(self): - files, _ = good_files("app") - files.pop((f"{ORG}/app", ".github/workflows/ci.yml")) - gh = FakeGithub([repo("app")], files, {}) - self.assertIn("has-ci", rules(audit.audit(gh, standard(), NOW))) - - def test_the_shared_gate_pin_must_be_a_full_sha_with_a_version_comment(self): - bad_pins = { - "branch name": "@5b96639ee3e06da9f4ab7603c59fd818643ade6c # main\n", - "no comment": "@150de5008682330747ba6880f1649b388858c206\n", - "short sha": "@150de50 # v0.1.0\n", - "moving tag": "@v0 # v0\n", - } - for label, pin in bad_pins.items(): - with self.subTest(label): - files, dirs = good_files("app") - files[(f"{ORG}/app", ".github/workflows/ci.yml")] = ( - " uses: naindev-contrast3d/ci-shared/.github/workflows/gate.yml" - + pin - ) - findings = audit.audit( - FakeGithub([repo("app")], files, dirs), standard(), NOW - ) - self.assertEqual( - (rules(findings), findings[0].severity), ({"gate-pin"}, "error") - ) - - def test_a_commented_reference_is_documentation_not_a_call(self): - files, dirs = good_files("app") - files[(f"{ORG}/app", ".github/workflows/ci.yml")] = ( - "# example:\n" - "# uses: naindev-contrast3d/ci-shared/.github/workflows/gate.yml@\n" - "jobs:\n test:\n runs-on: x\n" - ) - findings = audit.audit(FakeGithub([repo("app")], files, dirs), standard(), NOW) - self.assertEqual(rules(findings), {"shared-gate"}) - - def test_a_ci_that_does_not_call_the_shared_gate_is_a_warning(self): - files, dirs = good_files("app") - files[(f"{ORG}/app", ".github/workflows/ci.yml")] = ( - "jobs:\n test:\n runs-on: x\n" - ) - findings = audit.audit(FakeGithub([repo("app")], files, dirs), standard(), NOW) - self.assertEqual( - (rules(findings), findings[0].severity), ({"shared-gate"}, "warning") - ) - - def test_too_many_topic_branches_is_a_warning_with_the_count(self): - files, dirs = good_files("app") - names = ["main"] + [f"feat/{i}" for i in range(12)] - gh = FakeGithub([repo("app")], files, dirs, branches={f"{ORG}/app": names}) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual(rules(findings), {"topic-branches"}) - self.assertIn("12", findings[0].message) - - def test_archived_repositories_are_skipped(self): - gh = FakeGithub([repo("old", delete_branch=False, archived=True)]) - self.assertEqual(audit.audit(gh, standard(), NOW), []) - - def test_the_organisation_must_require_two_factor_authentication(self): - findings = audit.audit(clean_world(two_fa=False), standard(), NOW) - org_findings = [f for f in findings if f.repo == ORG] - self.assertEqual( - ([f.rule for f in org_findings], org_findings[0].severity), - (["org-2fa"], "error"), - ) - - def test_members_with_an_insecure_second_factor_are_a_warning(self): - findings = audit.audit(clean_world(insecure=["david"]), standard(), NOW) - org_findings = [f for f in findings if f.repo == ORG] - self.assertEqual( - ([f.rule for f in org_findings], org_findings[0].severity), - (["org-2fa-method"], "warning"), - ) - self.assertIn("david", org_findings[0].message) - - -def alert(severity, days_old, patched="1.2.3", package="left-pad"): - created = NOW - dt.timedelta(days=days_old) - return { - "created_at": created.isoformat().replace("+00:00", "Z"), - "dependency": {"package": {"name": package}}, - "security_advisory": {"severity": severity}, - "security_vulnerability": { - "first_patched_version": {"identifier": patched} if patched else None - }, - } - - -class SecurityRules(unittest.TestCase): - def world(self, **kw): - files, dirs = good_files("app") - return FakeGithub([repo("app")], files, dirs, **kw) - - def test_disabled_dependabot_alerts_are_a_warning(self): - gh = self.world(alerts={f"{ORG}/app": None}) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual(rules(findings), {"dependabot-alerts"}) - self.assertEqual(findings[0].severity, "warning") - - def test_an_alert_inside_its_deadline_is_not_a_finding(self): - gh = self.world(alerts={f"{ORG}/app": [alert("critical", 6), alert("high", 29)]}) - self.assertEqual(audit.audit(gh, standard(), NOW), []) - - def test_an_alert_past_its_deadline_names_the_package_and_the_age(self): - gh = self.world(alerts={f"{ORG}/app": [alert("critical", 9, package="happy-dom")]}) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual(rules(findings), {"dependabot-overdue"}) - self.assertIn("happy-dom", findings[0].message) - self.assertIn("9 days", findings[0].message) - - def test_an_alert_without_a_patched_version_is_never_overdue(self): - gh = self.world(alerts={f"{ORG}/app": [alert("high", 400, patched=None)]}) - self.assertEqual(audit.audit(gh, standard(), NOW), []) - - def test_the_deadlines_come_from_the_standard(self): - gh = self.world(alerts={f"{ORG}/app": [alert("medium", 20)]}) - std = standard(dependency_deadline_days={"medium": 10}) - self.assertEqual(rules(audit.audit(gh, std, NOW)), {"dependabot-overdue"}) - - def test_a_public_repository_must_protect_its_default_branch(self): - files, dirs = good_files("lib") - gh = FakeGithub([repo("lib", private=False)], files, dirs, protected=False) - self.assertEqual(rules(audit.audit(gh, standard(), NOW), "lib"), {"branch-protection"}) - - def test_a_private_repository_is_not_asked_for_paid_branch_protection(self): - self.assertEqual(audit.audit(self.world(protected=False), standard(), NOW), []) - - def test_a_writable_deploy_key_is_listed_by_title_without_key_material(self): - key = {"title": "release-tags", "read_only": False, "key": "ssh-ed25519 AAAA"} - gh = self.world(keys={f"{ORG}/app": [key, {"title": "ro", "read_only": True}]}) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual(rules(findings), {"deploy-key-write"}) - self.assertIn("release-tags", findings[0].message) - self.assertNotIn("AAAA", findings[0].message) - self.assertEqual(len(findings), 1) - - def test_a_webhook_without_a_secret_is_an_observation(self): - hook = {"active": True, "config": {"url": "https://discord.com/api/webhooks/x"}} - gh = self.world(hooks={f"{ORG}/app": [hook]}) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual(rules(findings), {"webhook-secret"}) - self.assertEqual(findings[0].severity, "info") - self.assertNotIn("discord.com/api", findings[0].message) - - def test_a_webhook_with_a_secret_is_fine(self): - hook = {"active": True, "config": {"url": "https://x.example/h", "secret": "********"}} - self.assertEqual( - audit.audit(self.world(hooks={f"{ORG}/app": [hook]}), standard(), NOW), [] - ) - - def test_actions_must_be_restricted_and_pinned_by_sha(self): - gh = self.world(actions={"allowed_actions": "all", "sha_pinning_required": False}) - findings = audit.audit(gh, standard(), NOW) - self.assertEqual({f.rule for f in findings}, {"actions-allowlist"}) - self.assertEqual(len(findings), 1) - - def test_unreadable_actions_permissions_are_skipped(self): - self.assertEqual(audit.audit(self.world(actions={}), standard(), NOW), []) - - -class Exceptions(unittest.TestCase): - def finding_world(self): - files, dirs = good_files("app") - return FakeGithub([repo("app", delete_branch=False)], files, dirs) - - def exception(self, expires): - return { - "repo": f"{ORG}/app", - "rule": "delete-branch-on-merge", - "reason": "kept on purpose", - "expires": expires, - } - - def test_a_valid_exception_silences_the_rule_for_that_repository(self): - std = standard(exceptions=[self.exception("2027-01-01")]) - self.assertEqual(audit.audit(self.finding_world(), std, NOW), []) - - def test_an_expired_exception_stops_applying_and_is_itself_a_finding(self): - std = standard(exceptions=[self.exception("2026-10-01")]) - found = {f.rule: f for f in audit.audit(self.finding_world(), std, NOW)} - self.assertEqual(set(found), {"delete-branch-on-merge", "exception-expired"}) - self.assertEqual(found["exception-expired"].severity, "error") - - def test_an_exception_for_another_repository_or_rule_changes_nothing(self): - other = dict(self.exception("2027-01-01"), repo=f"{ORG}/elsewhere") - std = standard( - exceptions=[other, dict(self.exception("2027-01-01"), rule="codeowners")] - ) - self.assertEqual( - rules(audit.audit(self.finding_world(), std, NOW)), - {"delete-branch-on-merge"}, - ) - - def test_an_exception_without_reason_or_date_is_rejected(self): - for bad in ( - {"repo": "a/b", "rule": "x"}, - {"repo": "a/b", "rule": "x", "reason": "r"}, - ): - with self.subTest(bad=bad), self.assertRaises(audit.StandardError): - audit.validate_standard(standard(exceptions=[bad])) - - -class Severity(unittest.TestCase): - def test_the_standard_can_change_the_severity_of_a_rule(self): - files, dirs = good_files("app") - gh = FakeGithub([repo("app", delete_branch=False)], files, dirs) - findings = audit.audit( - gh, standard(severity={"delete-branch-on-merge": "warning"}), NOW - ) - self.assertEqual(findings[0].severity, "warning") - - def test_an_unknown_severity_is_rejected(self): - with self.assertRaises(audit.StandardError): - audit.validate_standard(standard(severity={"codeowners": "fatal"})) - - def test_the_exit_code_follows_fail_on(self): - warning = [audit.Finding("o/a", "codeowners", "warning", "m")] - error = [audit.Finding("o/a", "license", "error", "m")] - self.assertEqual(audit.exit_code(warning, "error"), 0) - self.assertEqual(audit.exit_code(error, "error"), 1) - self.assertEqual(audit.exit_code(warning, "warning"), 1) - self.assertEqual(audit.exit_code([], "warning"), 0) - self.assertEqual(audit.exit_code(error, None), 0) - - -class Rendering(unittest.TestCase): - def test_findings_are_grouped_by_repository_and_ordered_by_severity(self): - findings = [ - audit.Finding("o/b", "codeowners", "warning", "no CODEOWNERS"), - audit.Finding("o/a", "license", "error", "license not recognised"), - audit.Finding("o/a", "codeowners", "warning", "no CODEOWNERS"), - ] - text = audit.render(findings, NOW) - self.assertLess(text.index("### o/a"), text.index("### o/b")) - self.assertLess( - text.index("license not recognised"), text.index("no CODEOWNERS") - ) - self.assertIn("- error `license`: license not recognised", text) - - def test_no_findings_says_so(self): - self.assertIn("No deviations", audit.render([], NOW)) - - def test_the_summary_counts_by_severity(self): - findings = [ - audit.Finding("o/a", "license", "error", "m"), - audit.Finding("o/a", "codeowners", "warning", "m"), - audit.Finding("o/b", "codeowners", "warning", "m"), - ] - self.assertIn("1 error, 2 warnings", audit.render(findings, NOW)) - - -class RealCommands(unittest.TestCase): - def setUp(self): - self.commands = [] - self.outputs = {} - self.errors = {} - self.gh = audit.Github(self.fake_run) - - def fake_run(self, command): - self.commands.append(command) - key = " ".join(command) - for needle, error in self.errors.items(): - if needle in key: - raise subprocess.CalledProcessError(1, command, stderr=error) - for needle, output in self.outputs.items(): - if needle in key: - return output - return "[]" - - def test_a_missing_file_reads_as_none(self): - self.errors["contents/.github/CODEOWNERS"] = "HTTP 404" - self.assertIsNone(self.gh.file_text(f"{ORG}/app", ".github/CODEOWNERS")) - - def test_a_file_is_read_through_the_raw_contents_media_type(self): - self.outputs["contents/.github/dependabot.yml"] = "version: 2\n" - self.assertEqual( - self.gh.file_text(f"{ORG}/app", ".github/dependabot.yml"), "version: 2\n" - ) - self.assertIn("application/vnd.github.raw+json", " ".join(self.commands[0])) - - def test_a_missing_directory_is_empty(self): - self.errors["contents/.github/workflows"] = "HTTP 404" - self.assertEqual(self.gh.dir_names(f"{ORG}/app", ".github/workflows"), []) - - def test_the_repositories_are_listed_with_the_fields_the_rules_read(self): - self.outputs["orgs/" + ORG + "/repos"] = json.dumps([repo("app")]) - self.assertEqual(self.gh.org_repos(ORG)[0]["name"], "app") - - def test_insecure_two_factor_members_are_listed_by_login(self): - self.outputs["2fa_insecure"] = json.dumps([{"login": "david"}]) - self.assertEqual(self.gh.insecure_two_factor_members(ORG), ["david"]) - - def test_disabled_dependabot_alerts_read_as_none(self): - self.errors["dependabot/alerts"] = "Dependabot alerts are disabled" - self.assertIsNone(self.gh.dependabot_alerts(f"{ORG}/app")) - - def test_open_alerts_are_flattened_across_pages(self): - self.outputs["dependabot/alerts"] = json.dumps([[{"a": 1}], [{"a": 2}]]) - self.assertEqual(self.gh.dependabot_alerts(f"{ORG}/app"), [{"a": 1}, {"a": 2}]) - self.assertIn("state=open", " ".join(self.commands[0])) - - def test_an_unprotected_branch_reads_as_false(self): - self.errors["branches/main/protection"] = "Branch not protected" - self.assertFalse(self.gh.branch_protected(f"{ORG}/app", "main")) - - def test_a_protected_branch_reads_as_true(self): - self.outputs["branches/main/protection"] = "{}" - self.assertTrue(self.gh.branch_protected(f"{ORG}/app", "main")) - - def test_keys_and_hooks_that_cannot_be_read_are_empty(self): - self.errors["/keys"] = "HTTP 403" - self.errors["/hooks"] = "HTTP 403" - self.assertEqual(self.gh.deploy_keys(f"{ORG}/app"), []) - self.assertEqual(self.gh.hooks(f"{ORG}/app"), []) - - def test_actions_permissions_that_cannot_be_read_are_empty(self): - self.errors["actions/permissions"] = "HTTP 403" - self.assertEqual(self.gh.org_actions_permissions(ORG), {}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_automerge.py b/tests/test_automerge.py deleted file mode 100644 index e6d22fb..0000000 --- a/tests/test_automerge.py +++ /dev/null @@ -1,612 +0,0 @@ -"""Tests for train/automerge.py: the decision rules, the cycle and the real `gh` commands.""" - -from __future__ import annotations - -import datetime as dt -import json -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "train")) - -import automerge as train - -REPO = "naindev-contrast3d/example" -SHA = "a" * 40 - - -def pr( - number=1, - sha=SHA, - labels=("automerge",), - draft=False, - base="main", - mergeable="MERGEABLE", -): - return { - "number": number, - "headRefOid": sha, - "baseRefName": base, - "isDraft": draft, - "mergeable": mergeable, - "labels": [{"name": name} for name in labels], - } - - -class FakeGithub: - """Records every call; answers from plain dictionaries.""" - - def __init__( - self, - prs=None, - gate_ok=True, - sealed=True, - behind=0, - update_result="updated", - fail_repos=(), - merge_error=False, - queue=None, - queue_error=False, - comment_error=False, - ): - self.comment_error = comment_error - self.comments = [] - self.prs = prs or [] - self.queue = queue or {} - self.queue_error = queue_error - self.gate_ok = gate_ok - self.sealed_shas = sealed - self.behind = behind - self.update_result = update_result - self.fail_repos = set(fail_repos) - self.merge_error = merge_error - self.calls = [] - - def _answer(self, value, sha): - return value(sha) if callable(value) else value - - def open_prs(self, repo, label): - self.calls.append(("open_prs", repo)) - if repo in self.fail_repos: - raise subprocess.CalledProcessError(1, ["gh"], stderr="boom") - return self.prs.get(repo, []) if isinstance(self.prs, dict) else self.prs - - def queued_runs(self, repo): - if self.queue_error: - raise subprocess.CalledProcessError(1, ["gh"], stderr="queue boom") - return self.queue.get(repo, []) - - def gate_green(self, repo, sha, check_name): - return self._answer(self.gate_ok, sha) - - def sealed(self, repo, sha): - return self._answer(self.sealed_shas, sha) - - def behind_by(self, repo, base, sha): - return self._answer(self.behind, sha) - - def merge(self, repo, number, sha, method): - self.calls.append(("merge", repo, number, sha, method)) - if self.merge_error: - raise subprocess.CalledProcessError(1, ["gh"], stderr="not allowed") - - def comment(self, repo, number, body): - if self.comment_error: - raise subprocess.CalledProcessError(1, ["gh"], stderr="comment boom") - self.comments.append((repo, number, body)) - - def update_branch(self, repo, number, sha): - self.calls.append(("update", repo, number, sha)) - return self.update_result - - def flag_needs_human(self, repo, number, label, needs_label): - self.calls.append(("flag", repo, number, label, needs_label)) - - def mutations(self): - return [c for c in self.calls if c[0] != "open_prs"] - - -def run(gh, repos=None, dry_run=False, alerts=None, now=None, heartbeat=None): - logs = [] - settings = train.Settings() - configs = repos or [train.RepoConfig(repo=REPO)] - code = train.run_cycle( - gh, - configs, - settings, - dry_run=dry_run, - log=logs.append, - alerts=alerts, - now=now, - heartbeat=heartbeat, - ) - return code, logs - - -NOW = dt.datetime(2026, 10, 14, 13, 0, 0, tzinfo=dt.UTC) - - -class MergeMark(unittest.TestCase): - """The train marks what it merges, so a merge made around it can be counted (FR13).""" - - def test_a_merged_pull_request_gets_the_train_mark_with_its_head(self): - gh = FakeGithub(prs=[pr(7)]) - run(gh) - self.assertEqual(len(gh.comments), 1) - repo, number, body = gh.comments[0] - self.assertEqual((repo, number), (REPO, 7)) - self.assertIn(train.MERGE_MARK, body) - self.assertIn(SHA[:12], body) - - def test_nothing_is_marked_in_a_dry_run_or_when_the_merge_is_refused(self): - dry = FakeGithub(prs=[pr(7)]) - run(dry, dry_run=True) - refused = FakeGithub(prs=[pr(7)], merge_error=True) - run(refused) - self.assertEqual((dry.comments, refused.comments), ([], [])) - - def test_a_failing_comment_is_logged_and_does_not_undo_or_fail_the_merge(self): - gh = FakeGithub(prs=[pr(7)], comment_error=True) - code, logs = run(gh) - self.assertEqual(code, 0) - self.assertEqual(gh.mutations(), [("merge", REPO, 7, SHA, "merge")]) - self.assertTrue(any("mark failed" in line for line in logs)) - - -class HeartbeatLine(unittest.TestCase): - """A line at least once an hour proves the train is alive and says which script it runs (FR14).""" - - def state(self): - return Path(tempfile.mkdtemp()) / "heartbeat.json" - - def test_the_first_cycle_logs_a_heartbeat_with_counts_and_the_script_version(self): - gh = FakeGithub(prs=[pr(1), pr(2, "b" * 40)], behind=2) - _, logs = run(gh, heartbeat=train.Heartbeat(self.state()), now=NOW) - line = next(item for item in logs if "heartbeat" in item) - self.assertIn("1 repositories", line) - self.assertIn("2 labelled pull requests", line) - self.assertIn(train.script_version(), line) - - def test_no_second_heartbeat_within_the_hour_but_one_after_it(self): - path = self.state() - gh = FakeGithub(prs=[]) - _, first = run(gh, heartbeat=train.Heartbeat(path), now=NOW) - _, soon = run( - gh, heartbeat=train.Heartbeat(path), now=NOW + dt.timedelta(minutes=59) - ) - _, later = run( - gh, heartbeat=train.Heartbeat(path), now=NOW + dt.timedelta(minutes=61) - ) - counts = [ - sum("heartbeat" in item for item in logs) for logs in (first, soon, later) - ] - self.assertEqual(counts, [1, 0, 1]) - - def test_a_dry_run_does_not_write_the_heartbeat_state(self): - path = self.state() - run(FakeGithub(prs=[]), dry_run=True, heartbeat=train.Heartbeat(path), now=NOW) - self.assertFalse(path.exists()) - - def test_the_script_version_is_the_same_for_lf_and_crlf_copies(self): - text = "a\nb\n" - self.assertEqual( - train.text_version(text), train.text_version(text.replace("\n", "\r\n")) - ) - self.assertNotEqual(train.text_version(text), train.text_version(text + "c\n")) - - -def queued(run_id, minutes_ago, branch="feat/x", workflow="CI"): - created = NOW - dt.timedelta(minutes=minutes_ago) - return { - "databaseId": run_id, - "createdAt": created.strftime("%Y-%m-%dT%H:%M:%SZ"), - "headBranch": branch, - "workflowName": workflow, - } - - -class QueueAlert(unittest.TestCase): - def state_path(self): - return Path(tempfile.mkdtemp()) / "queue-alerts.json" - - def test_a_run_queued_longer_than_the_threshold_is_logged_with_its_details(self): - gh = FakeGithub(queue={REPO: [queued(77, 45, branch="feat/y", workflow="CI")]}) - _, logs = run(gh, alerts=train.QueueAlerts(self.state_path()), now=NOW) - line = next(item for item in logs if "queued" in item) - for part in (REPO, "77", "feat/y", "CI", "45"): - self.assertIn(part, line) - - def test_a_younger_run_is_not_logged(self): - gh = FakeGithub(queue={REPO: [queued(78, 5)]}) - _, logs = run(gh, alerts=train.QueueAlerts(self.state_path()), now=NOW) - self.assertFalse(any("queued" in item for item in logs)) - - def test_the_same_run_is_logged_only_once_even_across_restarts(self): - path = self.state_path() - gh = FakeGithub(queue={REPO: [queued(79, 60)]}) - _, first = run(gh, alerts=train.QueueAlerts(path), now=NOW) - _, again = run(gh, alerts=train.QueueAlerts(path), now=NOW) - self.assertEqual(sum("queued" in item for item in first), 1) - self.assertEqual(sum("queued" in item for item in again), 0) - - def test_runs_that_left_the_queue_are_forgotten(self): - path = self.state_path() - run( - FakeGithub(queue={REPO: [queued(80, 60)]}), - alerts=train.QueueAlerts(path), - now=NOW, - ) - run(FakeGithub(queue={REPO: []}), alerts=train.QueueAlerts(path), now=NOW) - self.assertNotIn("80", path.read_text(encoding="utf-8")) - - def test_a_dry_run_logs_but_does_not_remember(self): - path = self.state_path() - gh = FakeGithub(queue={REPO: [queued(81, 60)]}) - _, logs = run(gh, dry_run=True, alerts=train.QueueAlerts(path), now=NOW) - self.assertTrue(any("queued" in item for item in logs)) - self.assertFalse(path.exists()) - - def test_the_alert_works_even_when_the_repository_has_no_open_pull_requests(self): - gh = FakeGithub(prs=[], queue={REPO: [queued(82, 90)]}) - _, logs = run(gh, alerts=train.QueueAlerts(self.state_path()), now=NOW) - self.assertTrue(any("82" in item for item in logs)) - - def test_a_failing_queue_query_is_logged_and_does_not_stop_the_merge(self): - gh = FakeGithub(prs=[pr(3)], queue_error=True) - code, logs = run(gh, alerts=train.QueueAlerts(self.state_path()), now=NOW) - self.assertEqual(code, 0) - self.assertTrue(any("queue check failed" in item for item in logs)) - self.assertEqual(gh.mutations(), [("merge", REPO, 3, SHA, "merge")]) - - def test_without_an_alerts_object_nothing_is_checked(self): - gh = FakeGithub(queue={REPO: [queued(83, 90)]}) - _, logs = run(gh) - self.assertEqual(logs, []) - - def test_the_threshold_comes_from_the_settings(self): - gh = FakeGithub(queue={REPO: [queued(84, 10)]}) - logs = [] - train.run_cycle( - gh, - [train.RepoConfig(repo=REPO)], - train.Settings(queue_alert_minutes=5), - dry_run=False, - log=logs.append, - alerts=train.QueueAlerts(self.state_path()), - now=NOW, - ) - self.assertTrue(any("84" in item for item in logs)) - - -class DecisionRules(unittest.TestCase): - def cfg(self, **kw): - return train.RepoConfig(repo=REPO, **kw) - - def classify(self, pull, gh=None, **kw): - return train.classify( - pull, self.cfg(**kw), train.Settings(), gh or FakeGithub() - ) - - def test_a_sealed_green_up_to_date_pull_request_is_ready(self): - self.assertEqual(self.classify(pr())[0], "ready") - - def test_missing_label_draft_and_other_base_are_skipped(self): - self.assertEqual(self.classify(pr(labels=()))[0], "skip") - self.assertEqual(self.classify(pr(draft=True))[0], "skip") - self.assertEqual(self.classify(pr(base="develop"))[0], "skip") - - def test_unknown_mergeability_is_skipped_and_a_conflict_is_flagged(self): - self.assertEqual(self.classify(pr(mergeable="UNKNOWN"))[0], "skip") - self.assertEqual(self.classify(pr(mergeable="CONFLICTING"))[0], "conflict") - - def test_a_red_or_missing_gate_is_skipped(self): - state, reason = self.classify(pr(), FakeGithub(gate_ok=False)) - self.assertEqual(state, "skip") - self.assertIn("gate", reason) - - def test_the_seal_is_required_only_when_configured(self): - no_seal = FakeGithub(sealed=False) - self.assertEqual(self.classify(pr(), no_seal)[0], "ready") - state, reason = self.classify(pr(), no_seal, require_seal=True) - self.assertEqual(state, "skip") - self.assertIn("seal", reason) - - def test_a_head_that_misses_main_is_stale(self): - state, reason = self.classify(pr(), FakeGithub(behind=3)) - self.assertEqual(state, "stale") - self.assertIn("3", reason) - - def test_a_red_stale_pull_request_is_not_stale_but_skipped(self): - self.assertEqual( - self.classify(pr(), FakeGithub(behind=3, gate_ok=False))[0], "skip" - ) - - -class Cycle(unittest.TestCase): - def test_a_ready_pull_request_is_merged_at_its_exact_head(self): - gh = FakeGithub(prs=[pr(7)]) - code, _ = run(gh) - self.assertEqual(code, 0) - self.assertEqual(gh.mutations(), [("merge", REPO, 7, SHA, "merge")]) - - def test_the_merge_method_of_the_repository_is_used(self): - gh = FakeGithub(prs=[pr(7)]) - configs = [train.RepoConfig(repo=REPO, merge_method="squash")] - run(gh, repos=configs) - self.assertEqual(gh.mutations(), [("merge", REPO, 7, SHA, "squash")]) - - def test_only_the_oldest_ready_pull_request_is_merged_per_cycle(self): - gh = FakeGithub(prs=[pr(9, "b" * 40), pr(4, "c" * 40)]) - _, logs = run(gh) - self.assertEqual(gh.mutations(), [("merge", REPO, 4, "c" * 40, "merge")]) - self.assertTrue(any("#9" in line and "waits" in line for line in logs)) - - def test_a_stale_pull_request_gets_main_merged_in_and_is_not_merged(self): - gh = FakeGithub(prs=[pr(3)], behind=2) - run(gh) - self.assertEqual(gh.mutations(), [("update", REPO, 3, SHA)]) - - def test_a_ready_pull_request_is_merged_before_any_stale_one_is_updated(self): - def behind(sha): - return 0 if sha == "c" * 40 else 2 - - gh = FakeGithub(prs=[pr(2, "b" * 40), pr(5, "c" * 40)], behind=behind) - run(gh) - self.assertEqual(gh.mutations(), [("merge", REPO, 5, "c" * 40, "merge")]) - - def test_only_one_stale_pull_request_is_updated_per_cycle(self): - gh = FakeGithub(prs=[pr(2, "b" * 40), pr(5, "c" * 40)], behind=2) - run(gh) - self.assertEqual(gh.mutations(), [("update", REPO, 2, "b" * 40)]) - - def test_a_conflicting_pull_request_is_flagged_and_never_merged(self): - gh = FakeGithub(prs=[pr(6, mergeable="CONFLICTING")]) - run(gh) - self.assertEqual( - gh.mutations(), [("flag", REPO, 6, "automerge", "needs-human")] - ) - - def test_a_conflict_found_while_updating_the_branch_is_flagged(self): - gh = FakeGithub(prs=[pr(8)], behind=1, update_result="conflict") - run(gh) - self.assertEqual( - gh.mutations(), - [("update", REPO, 8, SHA), ("flag", REPO, 8, "automerge", "needs-human")], - ) - - def test_a_dry_run_changes_nothing(self): - gh = FakeGithub(prs=[pr(1), pr(2, "b" * 40, mergeable="CONFLICTING")], behind=0) - _, logs = run(gh, dry_run=True) - self.assertEqual(gh.mutations(), []) - self.assertTrue(any("dry run" in line for line in logs)) - - def test_a_failing_repository_does_not_stop_the_others(self): - gh = FakeGithub(prs={"o/working": [pr(1)]}, fail_repos={"o/broken"}) - configs = [ - train.RepoConfig(repo="o/broken"), - train.RepoConfig(repo="o/working"), - ] - code, logs = run(gh, repos=configs) - self.assertEqual(code, 1) - self.assertEqual(gh.mutations(), [("merge", "o/working", 1, SHA, "merge")]) - self.assertTrue(any("o/broken" in line and "failed" in line for line in logs)) - - def test_a_refused_merge_is_logged_and_reported(self): - gh = FakeGithub(prs=[pr(1)], merge_error=True) - code, logs = run(gh) - self.assertEqual(code, 1) - self.assertTrue(any("merge refused" in line for line in logs)) - - def test_no_open_pull_requests_is_a_quiet_success(self): - code, logs = run(FakeGithub(prs=[])) - self.assertEqual(code, 0) - self.assertEqual(logs, []) - - -class Config(unittest.TestCase): - def write(self, data): - directory = tempfile.mkdtemp() - path = Path(directory) / "repos.json" - path.write_text( - data if isinstance(data, str) else json.dumps(data), encoding="utf-8" - ) - return path - - def test_defaults_apply_to_a_minimal_entry(self): - settings, repos = train.load_config(self.write({"repos": [{"repo": "o/r"}]})) - self.assertEqual(settings.label, "automerge") - self.assertEqual(settings.needs_human_label, "needs-human") - self.assertEqual(repos[0].gate_check, "Gate / Gate") - self.assertFalse(repos[0].require_seal) - self.assertEqual(repos[0].base, "main") - self.assertEqual(repos[0].merge_method, "merge") - self.assertEqual(settings.queue_alert_minutes, 30) - - def test_the_queue_alert_threshold_can_be_set_and_must_be_a_positive_integer(self): - settings, _ = train.load_config( - self.write({"queue_alert_minutes": 10, "repos": [{"repo": "o/r"}]}) - ) - self.assertEqual(settings.queue_alert_minutes, 10) - for bad in (0, -5, "10", 1.5, True): - with self.subTest(bad=bad), self.assertRaises(train.ConfigError): - train.load_config( - self.write({"queue_alert_minutes": bad, "repos": [{"repo": "o/r"}]}) - ) - - def test_overrides_are_read(self): - _, repos = train.load_config( - self.write( - { - "repos": [ - { - "repo": "o/r", - "gate_check": "CI gate", - "require_seal": True, - "base": "trunk", - } - ], - } - ) - ) - self.assertEqual( - (repos[0].gate_check, repos[0].require_seal, repos[0].base), - ("CI gate", True, "trunk"), - ) - - def test_invalid_configuration_is_rejected(self): - for bad in ( - "not json", - {"repos": []}, - {"repos": [{"gate_check": "x"}]}, - {"repos": [{"repo": "no-slash"}]}, - {"repos": [{"repo": "o/r", "require_seal": "yes"}]}, - {"repos": [{"repo": "o/r", "merge_method": "fast-forward"}]}, - ): - with self.subTest(bad=bad), self.assertRaises(train.ConfigError): - train.load_config(self.write(bad)) - - -class RealGithubCommands(unittest.TestCase): - """The commands are built from fixed words plus GitHub's own numbers and shas.""" - - def setUp(self): - self.commands = [] - self.outputs = {} - self.errors = {} - self.gh = train.Github(self.fake_run) - - def fake_run(self, command): - self.commands.append(command) - key = " ".join(command) - for needle, error in self.errors.items(): - if needle in key: - raise subprocess.CalledProcessError(1, command, stderr=error) - for needle, output in self.outputs.items(): - if needle in key: - return output - return "" - - def test_the_merge_method_is_read_from_the_configuration(self): - directory = tempfile.mkdtemp() - path = Path(directory) / "repos.json" - path.write_text( - json.dumps({"repos": [{"repo": "o/r", "merge_method": "squash"}]}), - encoding="utf-8", - ) - _, repos = train.load_config(path) - self.assertEqual(repos[0].merge_method, "squash") - - def test_each_merge_method_maps_to_its_gh_flag(self): - for method in ("merge", "squash", "rebase"): - with self.subTest(method=method): - self.commands.clear() - self.gh.merge(REPO, 5, SHA, method) - self.assertIn(f"--{method}", self.commands[0]) - self.assertIn("--match-head-commit", self.commands[0]) - - def test_merge_pins_the_head_commit_and_makes_a_merge_commit(self): - self.gh.merge(REPO, 5, SHA, "merge") - self.assertEqual( - self.commands[0], - [ - "gh", - "pr", - "merge", - "5", - "--repo", - REPO, - "--merge", - "--match-head-commit", - SHA, - ], - ) - - def test_comment_posts_the_body_on_the_pull_request(self): - self.gh.comment(REPO, 9, f"{train.MERGE_MARK}\nMerged") - self.assertEqual( - self.commands[0][:7], ["gh", "pr", "comment", "9", "--repo", REPO, "--body"] - ) - self.assertIn(train.MERGE_MARK, self.commands[0][7]) - - def test_queued_runs_asks_for_queued_status_and_parses_json(self): - self.outputs["run list"] = json.dumps([queued(5, 40)]) - runs = self.gh.queued_runs(REPO) - self.assertEqual(runs[0]["databaseId"], 5) - command = self.commands[0] - self.assertEqual(command[:4], ["gh", "run", "list", "--repo"]) - self.assertIn("queued", command) - self.assertIn("databaseId,createdAt,headBranch,workflowName", command) - - def test_open_prs_filters_by_label_and_parses_json(self): - self.outputs["pr list"] = json.dumps([pr(2)]) - self.assertEqual(self.gh.open_prs(REPO, "automerge")[0]["number"], 2) - self.assertIn("--label", self.commands[0]) - self.assertIn("automerge", self.commands[0]) - - def test_gate_is_green_only_when_every_run_of_that_name_succeeded(self): - runs = { - "check_runs": [ - {"name": "Gate / Gate", "status": "completed", "conclusion": "success"}, - {"name": "Other", "status": "completed", "conclusion": "failure"}, - ] - } - self.outputs["check-runs"] = json.dumps(runs) - self.assertTrue(self.gh.gate_green(REPO, SHA, "Gate / Gate")) - runs["check_runs"].append( - {"name": "Gate / Gate", "status": "completed", "conclusion": "failure"} - ) - self.outputs["check-runs"] = json.dumps(runs) - self.assertFalse(self.gh.gate_green(REPO, SHA, "Gate / Gate")) - - def test_gate_is_not_green_when_missing_or_still_running(self): - self.outputs["check-runs"] = json.dumps({"check_runs": []}) - self.assertFalse(self.gh.gate_green(REPO, SHA, "Gate / Gate")) - self.outputs["check-runs"] = json.dumps( - { - "check_runs": [ - {"name": "Gate / Gate", "status": "in_progress", "conclusion": None} - ] - } - ) - self.assertFalse(self.gh.gate_green(REPO, SHA, "Gate / Gate")) - - def test_the_seal_is_a_tag_that_either_exists_or_not(self): - self.assertTrue(self.gh.sealed(REPO, SHA)) - self.errors["git/ref/tags"] = "Not Found" - self.assertFalse(self.gh.sealed(REPO, SHA)) - - def test_behind_by_reads_the_compare_endpoint(self): - self.outputs["compare"] = json.dumps({"behind_by": 4}) - self.assertEqual(self.gh.behind_by(REPO, "main", SHA), 4) - self.assertIn(f"repos/{REPO}/compare/main...{SHA}", self.commands[0]) - - def test_update_branch_pins_the_expected_head(self): - self.assertEqual(self.gh.update_branch(REPO, 3, SHA), "updated") - self.assertIn(f"expected_head_sha={SHA}", self.commands[0]) - self.assertIn("PUT", self.commands[0]) - - def test_update_branch_reports_a_merge_conflict_and_raises_on_other_errors(self): - self.errors["update-branch"] = ( - "gh: merge conflict between base and head (HTTP 422)" - ) - self.assertEqual(self.gh.update_branch(REPO, 3, SHA), "conflict") - self.errors["update-branch"] = "gh: Resource not accessible (HTTP 403)" - with self.assertRaises(subprocess.CalledProcessError): - self.gh.update_branch(REPO, 3, SHA) - - def test_flagging_creates_the_label_if_needed_then_swaps_labels(self): - self.errors["label create"] = "already exists" - self.gh.flag_needs_human(REPO, 6, "automerge", "needs-human") - edit = self.commands[-1] - self.assertEqual(edit[:5], ["gh", "pr", "edit", "6", "--repo"]) - self.assertIn("--add-label", edit) - self.assertIn("needs-human", edit) - self.assertIn("--remove-label", edit) - self.assertIn("automerge", edit) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py deleted file mode 100644 index b20a044..0000000 --- a/tests/test_bootstrap.py +++ /dev/null @@ -1,203 +0,0 @@ -"""Tests for standards/bootstrap.py: the plan of settings for a new repository and its application.""" - -from __future__ import annotations - -import json -import subprocess -import sys -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "standards")) - -import bootstrap - -REPO = "naindev-contrast3d/new-app" - - -def settings(**overrides): - base = { - "private": True, - "archived": False, - "delete_branch_on_merge": False, - "security_and_analysis": { - "secret_scanning": {"status": "disabled"}, - "secret_scanning_push_protection": {"status": "disabled"}, - }, - } - base.update(overrides) - return base - - -class FakeGithub: - def __init__(self, repo=None, labels=(), alerts=False, fixes=False): - self._repo = repo or settings() - self._labels = list(labels) - self._alerts = alerts - self._fixes = fixes - self.calls = [] - - def repo(self, full_name): - return self._repo - - def labels(self, full_name): - return self._labels - - def alerts_enabled(self, full_name): - return self._alerts - - def security_fixes_enabled(self, full_name): - return self._fixes - - def patch_repo(self, full_name, fields): - self.calls.append(("patch", fields)) - - def create_label(self, full_name, name, color, description): - self.calls.append(("label", name)) - - def enable_alerts(self, full_name): - self.calls.append(("alerts",)) - - def enable_security_fixes(self, full_name): - self.calls.append(("fixes",)) - - -def names(changes): - return {c.setting for c in changes} - - -class Plan(unittest.TestCase): - def test_a_fresh_private_repository_needs_branch_deletion_labels_and_security_updates( - self, - ): - changes = bootstrap.plan(FakeGithub(), REPO) - self.assertEqual( - names(changes), - { - "delete_branch_on_merge", - "label:automerge", - "label:needs-human", - "vulnerability_alerts", - "automated_security_fixes", - }, - ) - - def test_secret_scanning_is_asked_for_only_on_public_repositories(self): - public = FakeGithub(settings(private=False)) - self.assertIn("secret_scanning", names(bootstrap.plan(public, REPO))) - self.assertIn( - "secret_scanning_push_protection", names(bootstrap.plan(public, REPO)) - ) - self.assertNotIn("secret_scanning", names(bootstrap.plan(FakeGithub(), REPO))) - - def test_settings_already_in_place_are_not_planned(self): - done = settings(delete_branch_on_merge=True) - gh = FakeGithub( - done, labels=["automerge", "needs-human"], alerts=True, fixes=True - ) - self.assertEqual(bootstrap.plan(gh, REPO), []) - - def test_an_archived_repository_is_refused(self): - with self.assertRaises(bootstrap.BootstrapError): - bootstrap.plan(FakeGithub(settings(archived=True)), REPO) - - def test_every_change_says_what_it_is_now_and_what_it_will_be(self): - change = next( - c - for c in bootstrap.plan(FakeGithub(), REPO) - if c.setting == "delete_branch_on_merge" - ) - self.assertEqual((change.current, change.wanted), ("off", "on")) - - -class Apply(unittest.TestCase): - def test_nothing_changes_without_apply(self): - gh = FakeGithub() - bootstrap.apply(gh, REPO, bootstrap.plan(gh, REPO), dry_run=True) - self.assertEqual(gh.calls, []) - - def test_apply_makes_each_planned_change_once(self): - gh = FakeGithub() - bootstrap.apply(gh, REPO, bootstrap.plan(gh, REPO), dry_run=False) - kinds = [call[0] for call in gh.calls] - self.assertEqual(sorted(kinds), ["alerts", "fixes", "label", "label", "patch"]) - patch = next(call for call in gh.calls if call[0] == "patch") - self.assertEqual(patch[1], {"delete_branch_on_merge": True}) - - def test_public_security_settings_go_in_one_patch(self): - gh = FakeGithub(settings(private=False, delete_branch_on_merge=True)) - bootstrap.apply(gh, REPO, bootstrap.plan(gh, REPO), dry_run=False) - patch = next(call for call in gh.calls if call[0] == "patch") - self.assertEqual( - patch[1], - { - "security_and_analysis": { - "secret_scanning": {"status": "enabled"}, - "secret_scanning_push_protection": {"status": "enabled"}, - } - }, - ) - - -class Rendering(unittest.TestCase): - def test_the_plan_is_printed_as_a_list_and_says_when_nothing_is_needed(self): - text = bootstrap.render(bootstrap.plan(FakeGithub(), REPO), REPO, dry_run=True) - self.assertIn("dry run", text.lower()) - self.assertIn("delete_branch_on_merge: off -> on", text) - done = FakeGithub( - settings(delete_branch_on_merge=True), - labels=["automerge", "needs-human"], - alerts=True, - fixes=True, - ) - self.assertIn( - "already follows", - bootstrap.render(bootstrap.plan(done, REPO), REPO, dry_run=True), - ) - - -class RealCommands(unittest.TestCase): - def setUp(self): - self.commands = [] - self.outputs = {} - self.errors = {} - self.gh = bootstrap.Github(self.fake_run) - - def fake_run(self, command): - self.commands.append(command) - key = " ".join(command) - for needle, error in self.errors.items(): - if needle in key: - raise subprocess.CalledProcessError(1, command, stderr=error) - for needle, output in self.outputs.items(): - if needle in key: - return output - return "" - - def test_alerts_are_enabled_when_the_endpoint_answers_and_not_when_it_is_404(self): - self.assertTrue(self.gh.alerts_enabled(REPO)) - self.errors["vulnerability-alerts"] = "HTTP 404" - self.assertFalse(self.gh.alerts_enabled(REPO)) - - def test_labels_are_read_by_name(self): - self.outputs["labels"] = json.dumps([{"name": "automerge"}, {"name": "bug"}]) - self.assertEqual(self.gh.labels(REPO), ["automerge", "bug"]) - - def test_the_repository_is_patched_with_a_json_body(self): - self.gh.patch_repo(REPO, {"delete_branch_on_merge": True}) - command = self.commands[0] - self.assertIn("PATCH", command) - self.assertIn("--input", command) - - def test_security_updates_and_alerts_use_their_endpoints(self): - self.gh.enable_alerts(REPO) - self.gh.enable_security_fixes(REPO) - joined = [" ".join(c) for c in self.commands] - self.assertTrue(any("PUT" in c and "vulnerability-alerts" in c for c in joined)) - self.assertTrue( - any("PUT" in c and "automated-security-fixes" in c for c in joined) - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ci_report.py b/tests/test_ci_report.py deleted file mode 100644 index 2b229cc..0000000 --- a/tests/test_ci_report.py +++ /dev/null @@ -1,549 +0,0 @@ -"""Tests for report/ci_report.py: failure classification, the metrics and the rendered report.""" - -from __future__ import annotations - -import datetime as dt -import json -import subprocess -import sys -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "report")) - -import ci_report as report - -REPO = "naindev-contrast3d/example" -NOW = dt.datetime(2026, 10, 14, 12, 0, 0, tzinfo=dt.UTC) - - -def iso(minutes_ago: float, seconds: int = 0) -> str: - moment = NOW - dt.timedelta(minutes=minutes_ago) + dt.timedelta(seconds=seconds) - return moment.strftime("%Y-%m-%dT%H:%M:%SZ") - - -def run(run_id, conclusion, created_min_ago, duration_s, name="CI", status="completed"): - return { - "databaseId": run_id, - "conclusion": conclusion, - "status": status, - "workflowName": name, - "createdAt": iso(created_min_ago), - "startedAt": iso(created_min_ago), - "updatedAt": iso(created_min_ago, duration_s), - "event": "pull_request", - "headBranch": "feat/x", - } - - -def job(name, conclusion, started_after_s, failed_step=None): - steps = [{"name": failed_step, "conclusion": "failure"}] if failed_step else [] - return { - "name": name, - "conclusion": conclusion, - "startedAt": started_after_s, - "steps": steps, - } - - -class FakeGithub: - def __init__(self, runs, jobs, runners=None, queued=None, prs=None): - self._runs = runs - self._jobs = jobs # run id -> list of (name, conclusion, delay_s, failed_step) - self._runners = runners if runners is not None else [] - self._queued = queued or [] - self._prs = prs or [] - - def runs(self, repo, limit): - return self._runs - - def jobs(self, repo, run_id): - created = next(r for r in self._runs if r["databaseId"] == run_id)["createdAt"] - base = dt.datetime.fromisoformat(created) - out = [] - for name, conclusion, delay, failed_step in self._jobs.get(run_id, []): - started = (base + dt.timedelta(seconds=delay)).strftime( - "%Y-%m-%dT%H:%M:%SZ" - ) - out.append(job(name, conclusion, started, failed_step)) - return out - - def job_timings(self, repo, run_id): - return getattr(self, "timings", {}).get(run_id, []) - - def runners(self, repo): - return self._runners - - def queued_runs(self, repo): - return self._queued - - def open_prs(self, repo): - return self._prs - - def merged_prs(self, repo, limit): - return getattr(self, "merged", []) - - def file_text(self, repo, path): - return getattr(self, "files", {}).get((repo, path)) - - -def sample_github(): - runs = [ - run(1, "success", 60, 300), - run(2, "success", 120, 600), - run(3, "failure", 180, 120), # a real test failure - run(4, "failure", 240, 60), # the runner could not start the job - run(5, "cancelled", 300, 30), - run(6, "skipped", 360, 0), - run(7, "success", 60 * 24 * 10, 300), # older than the window - run(8, "success", 70, 100, name="Other"), # another workflow - ] - jobs = { - 1: [("Verify", "success", 30, None)], - 2: [("Verify", "success", 10, None)], - 3: [("Verify", "success", 90, None), ("Tests", "failure", 95, "Pruebas")], - 4: [("Verify", "failure", 200, "Set up job")], - } - runners = [ - {"name": "vm-01", "status": "online", "busy": True}, - {"name": "vm-02", "status": "offline", "busy": False}, - ] - queued = [ - {"databaseId": 90, "createdAt": iso(45)}, - {"databaseId": 91, "createdAt": iso(5)}, - ] - prs = [ - {"number": 1, "labels": [{"name": "automerge"}], "createdAt": iso(60 * 5)}, - {"number": 2, "labels": [], "createdAt": iso(60)}, - ] - return FakeGithub(runs, jobs, runners, queued, prs) - - -class Classification(unittest.TestCase): - def test_a_job_that_never_started_its_steps_is_infrastructure(self): - jobs = [job("Verify", "failure", iso(1), "Set up job")] - self.assertEqual(report.classify_failure(jobs), "infra") - - def test_a_failure_with_no_steps_at_all_is_infrastructure(self): - self.assertEqual( - report.classify_failure([job("Verify", "failure", iso(1))]), "infra" - ) - - def test_a_failed_test_step_is_code(self): - jobs = [job("Tests", "failure", iso(1), "Pruebas")] - self.assertEqual(report.classify_failure(jobs), "code") - - def test_the_shared_preflight_failing_is_infrastructure(self): - jobs = [ - job("Runner preflight", "failure", iso(1), "Check tools, memory and disk") - ] - self.assertEqual(report.classify_failure(jobs), "infra") - - def test_a_run_is_infrastructure_only_when_every_failed_job_is(self): - jobs = [ - job("Verify", "failure", iso(1), "Set up job"), - job("Tests", "failure", iso(1), "Pruebas"), - ] - self.assertEqual(report.classify_failure(jobs), "code") - - def test_no_failed_job_is_reported_as_code(self): - self.assertEqual( - report.classify_failure([job("Verify", "success", iso(1))]), "code" - ) - - -class Metrics(unittest.TestCase): - def setUp(self): - self.stats = report.collect(sample_github(), REPO, "CI", days=7, now=NOW) - - def test_only_conclusive_runs_of_the_workflow_inside_the_window_are_counted(self): - self.assertEqual(self.stats.conclusive, 4) - self.assertEqual(self.stats.failed, 2) - self.assertEqual(self.stats.cancelled, 1) - - def test_failures_are_split_by_cause(self): - self.assertEqual(self.stats.infra_failures, 1) - - def test_the_median_duration_is_over_conclusive_runs(self): - self.assertEqual(self.stats.median_duration_s, 210) # 60, 120, 300, 600 - - def test_the_median_queue_time_is_the_first_job_start_after_the_run_was_created( - self, - ): - self.assertEqual(self.stats.median_queue_s, 60) # 10, 30, 90, 200 - - def test_the_snapshot_reports_runners_the_queue_and_open_pull_requests(self): - self.assertEqual((self.stats.runners_online, self.stats.runners_busy), (1, 1)) - self.assertEqual(self.stats.runners_offline, 1) - self.assertEqual(self.stats.queued_now, 2) - self.assertEqual(self.stats.oldest_queued_min, 45) - self.assertEqual((self.stats.open_prs, self.stats.automerge_prs), (2, 1)) - - def test_a_repository_without_runs_has_no_rates_instead_of_dividing_by_zero(self): - stats = report.collect(FakeGithub([], {}), REPO, "CI", days=7, now=NOW) - self.assertEqual(stats.conclusive, 0) - self.assertIsNone(stats.fail_rate) - self.assertIsNone(stats.median_duration_s) - self.assertIsNone(stats.median_queue_s) - - -MARK = "" - - -def merged_pr(number, minutes_ago, marked): - comments = ( - [{"body": f"{MARK}\nMerged by the merge train"}] - if marked - else [{"body": "lgtm"}] - ) - return {"number": number, "mergedAt": iso(minutes_ago), "comments": comments} - - -class MergedOutsideTheTrain(unittest.TestCase): - """A merged pull request without the train's mark was merged around the train (FR13).""" - - def stats(self, merged, train_repos=(REPO,), train_since=None): - gh = sample_github() - gh.merged = merged - return report.collect( - gh, - REPO, - "CI", - days=7, - now=NOW, - train_repos=set(train_repos), - train_since=train_since, - ) - - def test_unmarked_merges_inside_the_window_are_counted(self): - stats = self.stats( - [merged_pr(1, 60, True), merged_pr(2, 120, False), merged_pr(3, 180, False)] - ) - self.assertEqual((stats.merged_total, stats.merged_by_hand), (3, 2)) - - def test_merges_older_than_the_window_or_before_the_train_are_not_counted(self): - old = merged_pr( - 4, 60 * 24 * 10, False - ) # ten days ago, outside the 7-day window - before_train = merged_pr(5, 60 * 24 * 3, False) - since = NOW - dt.timedelta(days=1) - stats = self.stats( - [old, before_train, merged_pr(6, 30, True)], train_since=since - ) - self.assertEqual((stats.merged_total, stats.merged_by_hand), (1, 0)) - - def test_a_repository_without_the_shared_train_is_not_counted_at_all(self): - stats = self.stats([merged_pr(1, 60, False)], train_repos=()) - self.assertIsNone(stats.merged_by_hand) - self.assertIsNone(stats.merged_total) - - def test_the_snapshot_says_how_many_were_merged_around_the_train(self): - stats = self.stats([merged_pr(1, 60, True), merged_pr(2, 120, False)]) - text = report.render([stats], days=7, now=NOW) - self.assertIn("Merged outside the train: 1 of 2", text) - - def test_the_real_query_asks_for_merged_pull_requests_with_their_comments(self): - commands = [] - gh = report.Github(lambda command: commands.append(command) or "[]") - gh.merged_prs(REPO, 100) - self.assertIn("merged", commands[0]) - self.assertTrue(any("comments" in part for part in commands[0])) - - def test_the_mark_is_the_same_text_the_train_writes(self): - sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "train")) - import automerge as train - - self.assertEqual(report.TRAIN_MARK, train.MERGE_MARK) - - -class TrainHealth(unittest.TestCase): - """The report shows whether the train is alive and runs the current script (FR14).""" - - def setUp(self): - import os - import tempfile - - self.os = os - self.dir = Path(tempfile.mkdtemp()) - self.gh = FakeGithub([], {}) - self.gh.files = { - ("naindev-contrast3d/ci-shared", "train/automerge.py"): "script v1\n" - } - - def write(self, name, text, minutes_ago=None): - path = self.dir / name - path.write_text(text, encoding="utf-8", newline="") - if minutes_ago is not None: - stamp = (NOW - dt.timedelta(minutes=minutes_ago)).timestamp() - self.os.utime(path, (stamp, stamp)) - - def health(self): - return report.train_health(self.dir, self.gh, NOW) - - def test_a_recent_log_and_the_current_script_are_healthy(self): - self.write("train.log", "[x] heartbeat\n", minutes_ago=12) - self.write("automerge.py", "script v1\n") - health = self.health() - self.assertEqual(health.log_age_min, 12) - self.assertFalse(health.silent) - self.assertEqual(health.copy, "current") - - def test_a_log_older_than_ninety_minutes_means_the_train_is_silent(self): - self.write("train.log", "[x] heartbeat\n", minutes_ago=130) - self.write("automerge.py", "script v1\n") - self.assertTrue(self.health().silent) - - def test_a_copy_that_differs_from_ci_shared_main_is_stale(self): - self.write("train.log", "x\n", minutes_ago=5) - self.write("automerge.py", "script v0\n") - health = self.health() - self.assertEqual(health.copy, "stale") - self.assertNotEqual(health.installed_version, health.repository_version) - - def test_line_endings_alone_do_not_make_a_copy_stale(self): - self.write("train.log", "x\n", minutes_ago=5) - self.write("automerge.py", "script v1\r\n") - self.assertEqual(self.health().copy, "current") - - def test_a_missing_folder_is_reported_as_not_installed(self): - health = report.train_health(self.dir / "nowhere", self.gh, NOW) - self.assertEqual(health.copy, "missing") - self.assertIsNone(health.log_age_min) - - def test_the_section_states_each_finding_in_words(self): - self.write("train.log", "x\n", minutes_ago=130) - self.write("automerge.py", "script v0\n") - text = report.render_train(self.health()) - self.assertIn("## Merge train", text) - self.assertIn("no log line for 130 min", text) - self.assertIn("differs from ci-shared main", text) - - def test_the_version_function_matches_the_trains(self): - sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "train")) - import automerge as train - - for sample in ("a\nb\n", "a\r\nb\r\n", ""): - self.assertEqual(report.text_version(sample), train.text_version(sample)) - - -class AuditSection(unittest.TestCase): - """`--audit` appends the standards audit to the report.""" - - def test_the_audit_module_is_found_beside_the_report(self): - module = report.load_audit() - self.assertTrue(callable(module.run)) - self.assertTrue(callable(module.render)) - - def test_the_section_is_the_audit_report_without_its_own_title(self): - module = report.load_audit() - findings = [module.Finding("o/a", "license", "error", "license not recognised")] - text = report.audit_section(module.render(findings, NOW)) - self.assertTrue(text.startswith("## Standards audit")) - self.assertIn("- error `license`: license not recognised", text) - self.assertNotIn( - "# Standards audit\n\n2026", text.replace("## Standards audit", "") - ) - - -class Until(unittest.TestCase): - """A window that ends in the past makes a baseline reproducible after later changes.""" - - def test_runs_created_after_the_end_of_the_window_are_ignored(self): - gh = sample_github() - gh._runs.append(run(20, "failure", 10, 60)) # 10 minutes ago - gh._jobs[20] = [("Verify", "failure", 5, "Pruebas")] - until = NOW - dt.timedelta(minutes=30) - stats = report.collect(gh, REPO, "CI", days=7, now=NOW, until=until) - self.assertEqual(stats.conclusive, 4) - self.assertEqual(stats.failed, 2) - - def test_without_until_the_window_ends_now(self): - gh = sample_github() - gh._runs.append(run(20, "failure", 10, 60)) - gh._jobs[20] = [("Verify", "failure", 5, "Pruebas")] - stats = report.collect(gh, REPO, "CI", days=7, now=NOW) - self.assertEqual(stats.conclusive, 5) - - def test_the_window_start_moves_with_until(self): - until = NOW - dt.timedelta(days=3) - text = report.render([], days=7, now=NOW, until=until) - self.assertIn("2026-10-04 to 2026-10-11", text) - self.assertIn("snapshot", text.lower()) - - def test_a_moment_may_be_a_date_or_a_date_and_time_in_utc(self): - self.assertEqual( - report.parse_moment("2026-10-14"), - dt.datetime(2026, 10, 14, 0, 0, tzinfo=dt.UTC), - ) - self.assertEqual( - report.parse_moment("2026-10-14T11:00"), - dt.datetime(2026, 10, 14, 11, 0, tzinfo=dt.UTC), - ) - self.assertEqual( - report.parse_moment("2026-10-14T11:00:00Z"), - dt.datetime(2026, 10, 14, 11, 0, tzinfo=dt.UTC), - ) - - -class Rendering(unittest.TestCase): - def test_the_table_row_is_pinned(self): - stats = report.collect(sample_github(), REPO, "CI", days=7, now=NOW) - text = report.render([stats], days=7, now=NOW) - self.assertIn( - f"| {REPO} | 4 | 2 | 50% | 50% | 3m30s | 1m00s |", - text, - ) - - def test_the_snapshot_lines_are_present(self): - stats = report.collect(sample_github(), REPO, "CI", days=7, now=NOW) - text = report.render([stats], days=7, now=NOW) - self.assertIn("Runners: 1 online (1 busy), 1 offline", text) - self.assertIn("Queued now: 2 (oldest 45 min)", text) - self.assertIn("Open pull requests: 2 (1 labelled automerge)", text) - - def test_a_repository_without_data_renders_dashes(self): - stats = report.collect(FakeGithub([], {}), REPO, "CI", days=7, now=NOW) - text = report.render([stats], days=7, now=NOW) - self.assertIn(f"| {REPO} | 0 | 0 | - | - | - | - |", text) - - def test_the_header_states_the_period(self): - text = report.render([], days=7, now=NOW) - self.assertIn("2026-10-07", text) - self.assertIn("2026-10-14", text) - - def test_durations_are_formatted_for_people(self): - self.assertEqual(report.fmt_duration(45), "45s") - self.assertEqual(report.fmt_duration(210), "3m30s") - self.assertEqual(report.fmt_duration(3720), "1h02m") - - -def timing(name, queued_s, conclusion="success", started=True): - """A job from the REST API that waited `queued_s` seconds for a runner.""" - created = NOW - dt.timedelta(hours=1) - began = created + dt.timedelta(seconds=queued_s) - stamp = "%Y-%m-%dT%H:%M:%SZ" - return { - "name": name, - "conclusion": conclusion, - "created_at": created.strftime(stamp), - "started_at": began.strftime(stamp) if started else None, - } - - -class JobQueueTime(unittest.TestCase): - def test_a_job_waits_from_its_creation_to_its_start(self): - waits = report.job_waits([timing("Verify", 45), timing("Seal", 780)]) - self.assertEqual(waits, [("Verify", 45), ("Seal", 780)]) - - def test_skipped_and_never_started_jobs_do_not_count(self): - jobs = [timing("A", 0, "skipped"), timing("B", 0, None, started=False)] - self.assertEqual(report.job_waits(jobs), []) - - def test_a_clock_skew_never_gives_a_negative_wait(self): - self.assertEqual(report.job_waits([timing("A", -3)]), [("A", 0)]) - - def test_the_percentile_is_the_nearest_rank(self): - values = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] - self.assertEqual(report.percentile(values, 90), 90) - self.assertEqual(report.percentile(values, 50), 50) - self.assertEqual(report.percentile([7], 90), 7) - self.assertIsNone(report.percentile([], 90)) - - def test_the_report_gives_median_p90_max_and_the_slowest_jobs(self): - gh = sample_github() - gh.timings = { - 1: [timing("Verify", 10), timing("Seal", 780)], - 2: [timing("Verify", 20), timing("Seal", 600)], - 3: [timing("Verify", 30), timing("Seal", 900)], - } - stats = report.collect(gh, REPO, "CI", days=7, now=NOW) - self.assertEqual(stats.jobs_sampled, 6) - self.assertEqual(stats.job_wait_max_s, 900) - self.assertEqual(stats.job_wait_p90_s, 900) - self.assertEqual(stats.job_wait_median_s, 315) # 10, 20, 30, 600, 780, 900 - self.assertEqual(stats.slowest_jobs[0], ("Seal", 780, 3)) - - def test_a_repository_without_timings_has_no_queue_figures(self): - stats = report.collect(sample_github(), REPO, "CI", days=7, now=NOW) - self.assertEqual(stats.jobs_sampled, 0) - self.assertIsNone(stats.job_wait_median_s) - self.assertEqual(stats.slowest_jobs, []) - - def test_the_section_names_the_slowest_job_and_the_runner_count(self): - gh = sample_github() - gh.timings = {1: [timing("Verify", 10), timing("Seal", 780)]} - stats = report.collect(gh, REPO, "CI", days=7, now=NOW) - text = report.render([stats], days=7, now=NOW) - self.assertIn("## Queue time per job", text) - self.assertIn( - f"| {REPO} | 2 | 6m35s | 13m00s | 13m00s | Seal (13m00s) | 1 |", text - ) - - def test_the_section_is_left_out_when_no_repository_has_timings(self): - stats = report.collect(sample_github(), REPO, "CI", days=7, now=NOW) - self.assertNotIn( - "## Queue time per job", report.render([stats], days=7, now=NOW) - ) - - def test_the_real_command_reads_the_jobs_of_the_run_with_their_creation_time(self): - calls = [] - - def fake(command): - calls.append(command) - return json.dumps({"jobs": [timing("Seal", 5)]}) - - jobs = report.Github(fake).job_timings(REPO, 42) - self.assertEqual(jobs[0]["name"], "Seal") - self.assertEqual(calls[0][:2], ["gh", "api"]) - self.assertIn(f"repos/{REPO}/actions/runs/42/jobs", " ".join(calls[0])) - - def test_a_run_whose_jobs_cannot_be_read_gives_no_timings(self): - def refuse(command): - raise subprocess.CalledProcessError(1, command, stderr="HTTP 404") - - self.assertEqual(report.Github(refuse).job_timings(REPO, 42), []) - - -class RealCommands(unittest.TestCase): - def setUp(self): - self.commands = [] - self.outputs = {} - self.gh = report.Github(self.fake_run) - - def fake_run(self, command): - self.commands.append(command) - key = " ".join(command) - for needle, output in self.outputs.items(): - if needle in key: - return output - return "[]" - - def test_runs_asks_for_the_fields_the_metrics_need(self): - self.gh.runs(REPO, 200) - command = self.commands[0] - self.assertEqual(command[:4], ["gh", "run", "list", "--repo"]) - fields = ( - "databaseId,conclusion,status,workflowName,createdAt,startedAt,updatedAt" - ) - self.assertTrue(any(fields in part for part in command)) - - def test_jobs_reads_the_jobs_of_one_run(self): - self.outputs["run view"] = json.dumps( - {"jobs": [job("Verify", "success", iso(1))]} - ) - self.assertEqual(self.gh.jobs(REPO, 7)[0]["name"], "Verify") - self.assertIn("7", self.commands[0]) - - def test_runners_reads_the_repository_runners(self): - self.outputs["actions/runners"] = json.dumps({"runners": [{"name": "vm-01"}]}) - self.assertEqual(self.gh.runners(REPO)[0]["name"], "vm-01") - - def test_a_repository_without_runner_access_reports_none_instead_of_failing(self): - def refuse(command): - raise subprocess.CalledProcessError(1, command, stderr="HTTP 403") - - self.assertEqual(report.Github(refuse).runners(REPO), []) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_runner_watch.py b/tests/test_runner_watch.py deleted file mode 100644 index 37aa3d5..0000000 --- a/tests/test_runner_watch.py +++ /dev/null @@ -1,239 +0,0 @@ -"""Tests for report/runner_watch.py: when a runner or a queue deserves a toast, and only once.""" - -from __future__ import annotations - -import datetime as dt -import json -import subprocess -import sys -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "report")) - -import runner_watch as watch - -NOW = dt.datetime(2026, 10, 15, 12, 0, 0, tzinfo=dt.UTC) -ORG = "acme" - - -def ago(minutes: float) -> str: - return (NOW - dt.timedelta(minutes=minutes)).strftime("%Y-%m-%dT%H:%M:%SZ") - - -def snapshot(runners=(), queued=()): - return {"runners": list(runners), "queued": list(queued)} - - -class Offline(unittest.TestCase): - def test_an_online_runner_raises_nothing(self): - alerts, state = watch.evaluate( - snapshot([("acme/a", "a-01", "online")]), {}, NOW - ) - self.assertEqual(alerts, []) - self.assertEqual(state["offline_since"], {}) - - def test_a_runner_just_seen_offline_is_remembered_not_reported(self): - alerts, state = watch.evaluate( - snapshot([("acme/a", "a-01", "offline")]), {}, NOW - ) - self.assertEqual(alerts, []) - self.assertEqual(state["offline_since"], {"acme/a/a-01": ago(0)}) - - def test_it_is_reported_once_it_has_been_offline_long_enough(self): - state = {"offline_since": {"acme/a/a-01": ago(11)}} - alerts, state = watch.evaluate( - snapshot([("acme/a", "a-01", "offline")]), state, NOW - ) - self.assertEqual([a.key for a in alerts], ["offline:acme/a/a-01"]) - self.assertIn("a-01", alerts[0].body) - self.assertIn("11 min", alerts[0].body) - - def test_a_runner_offline_for_less_than_the_threshold_is_not_reported(self): - state = {"offline_since": {"acme/a/a-01": ago(9)}} - alerts, _ = watch.evaluate( - snapshot([("acme/a", "a-01", "offline")]), state, NOW - ) - self.assertEqual(alerts, []) - - def test_the_same_runner_is_not_reported_twice(self): - state = {"offline_since": {"acme/a/a-01": ago(30)}} - alerts, state = watch.evaluate( - snapshot([("acme/a", "a-01", "offline")]), state, NOW - ) - self.assertEqual(len(alerts), 1) - again, _ = watch.evaluate(snapshot([("acme/a", "a-01", "offline")]), state, NOW) - self.assertEqual(again, []) - - def test_a_runner_that_comes_back_is_forgotten_and_can_be_reported_again(self): - state = { - "offline_since": {"acme/a/a-01": ago(30)}, - "alerted": ["offline:acme/a/a-01"], - } - alerts, state = watch.evaluate( - snapshot([("acme/a", "a-01", "online")]), state, NOW - ) - self.assertEqual(alerts, []) - self.assertEqual(state["offline_since"], {}) - self.assertEqual(state["alerted"], []) - - def test_an_ignored_runner_is_never_reported(self): - state = {"offline_since": {"acme/a/a-01": ago(300)}} - alerts, state = watch.evaluate( - snapshot([("acme/a", "a-01", "offline")]), state, NOW, ignore={"a-01"} - ) - self.assertEqual(alerts, []) - self.assertEqual(state["offline_since"], {}) - - def test_a_runner_that_vanished_from_the_list_is_forgotten(self): - state = { - "offline_since": {"acme/a/gone": ago(300)}, - "alerted": ["offline:acme/a/gone"], - } - _, state = watch.evaluate(snapshot([]), state, NOW) - self.assertEqual(state["offline_since"], {}) - self.assertEqual(state["alerted"], []) - - -class Queue(unittest.TestCase): - def test_a_young_queued_run_is_not_reported(self): - alerts, _ = watch.evaluate(snapshot(queued=[("acme/a", 7, ago(14))]), {}, NOW) - self.assertEqual(alerts, []) - - def test_an_old_queued_run_is_reported_once(self): - snap = snapshot(queued=[("acme/a", 7, ago(16))]) - alerts, state = watch.evaluate(snap, {}, NOW) - self.assertEqual([a.key for a in alerts], ["queue:acme/a/7"]) - self.assertIn("16 min", alerts[0].body) - again, _ = watch.evaluate(snap, state, NOW) - self.assertEqual(again, []) - - def test_a_run_that_started_is_forgotten(self): - state = {"alerted": ["queue:acme/a/7"]} - _, state = watch.evaluate(snapshot(queued=[]), state, NOW) - self.assertEqual(state["alerted"], []) - - def test_the_thresholds_are_parameters(self): - snap = snapshot(queued=[("acme/a", 7, ago(5))]) - alerts, _ = watch.evaluate(snap, {}, NOW, queue_min=3) - self.assertEqual(len(alerts), 1) - - -class Collecting(unittest.TestCase): - def test_it_reads_the_organisation_and_the_private_repositories(self): - class Gh: - def org_repos(self, org): - return [ - {"name": "a", "visibility": "PRIVATE", "isArchived": False}, - {"name": "old", "visibility": "PRIVATE", "isArchived": True}, - {"name": "open", "visibility": "PUBLIC", "isArchived": False}, - ] - - def org_runners(self, org): - return [{"name": "pool-01", "status": "online"}] - - def runners(self, repo): - return [{"name": f"{repo}-01", "status": "offline"}] - - def queued_runs(self, repo): - return [{"databaseId": 5, "createdAt": ago(40)}] - - snap = watch.collect(Gh(), ORG) - self.assertIn(("acme", "pool-01", "online"), snap["runners"]) - self.assertIn(("acme/a", "acme/a-01", "offline"), snap["runners"]) - self.assertEqual(snap["queued"], [("acme/a", 5, ago(40))]) - self.assertEqual( - len(snap["runners"]), 2, "archived and public repositories are skipped" - ) - - def test_an_unreadable_part_does_not_stop_the_rest(self): - class Gh: - def org_repos(self, org): - return [{"name": "a", "visibility": "PRIVATE", "isArchived": False}] - - def org_runners(self, org): - raise subprocess.CalledProcessError(1, ["gh"], stderr="HTTP 403") - - def runners(self, repo): - return [{"name": "a-01", "status": "online"}] - - def queued_runs(self, repo): - raise subprocess.CalledProcessError(1, ["gh"], stderr="HTTP 502") - - snap = watch.collect(Gh(), ORG) - self.assertEqual(snap["runners"], [("acme/a", "a-01", "online")]) - self.assertEqual(snap["queued"], []) - - -class RealCommands(unittest.TestCase): - def setUp(self): - self.calls = [] - - def fake(self, command): - self.calls.append(command) - return json.dumps({"runners": [{"name": "pool-01", "status": "online"}]}) - - def test_org_runners_asks_the_organisation_endpoint(self): - runners = watch.Github(self.fake).org_runners(ORG) - self.assertEqual(runners[0]["name"], "pool-01") - self.assertIn("orgs/acme/actions/runners", " ".join(self.calls[0])) - - def test_org_repos_asks_for_visibility_and_archived(self): - watch.Github(lambda c: self.calls.append(c) or "[]").org_repos(ORG) - joined = " ".join(self.calls[0]) - self.assertIn("repo list acme", joined) - self.assertIn("name,visibility,isArchived", joined) - - -class Notifying(unittest.TestCase): - def test_each_alert_becomes_one_toast_command(self): - sent = [] - alerts = [watch.Alert("k1", "T1", "B1"), watch.Alert("k2", "T2", "B2")] - watch.notify(alerts, r"C:\x\notify.ps1", lambda c: sent.append(c)) - self.assertEqual(len(sent), 2) - self.assertIn("-File", sent[0]) - self.assertEqual(sent[0][sent[0].index("-Title") + 1], "T1") - self.assertEqual(sent[1][sent[1].index("-Body") + 1], "B2") - - def test_a_failing_toast_never_raises(self): - def boom(command): - raise OSError("no powershell") - - watch.notify([watch.Alert("k", "T", "B")], "notify.ps1", boom) - - -class Main(unittest.TestCase): - def test_state_is_saved_and_a_second_run_stays_quiet(self): - import tempfile - - class Gh: - def org_repos(self, org): - return [] - - def org_runners(self, org): - return [{"name": "pool-01", "status": "offline"}] - - with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / "state.json" - state = {"offline_since": {"acme/pool-01": ago(40)}} - path.write_text(json.dumps(state), encoding="utf-8") - first = watch.run(Gh(), ORG, path, NOW, notify_path=None) - second = watch.run(Gh(), ORG, path, NOW, notify_path=None) - self.assertEqual(len(first), 1) - self.assertEqual(second, []) - self.assertIn( - "offline:acme/pool-01", - json.loads(path.read_text(encoding="utf-8"))["alerted"], - ) - - def test_a_corrupt_state_file_is_a_clean_slate(self): - import tempfile - - with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / "state.json" - path.write_text("{not json", encoding="utf-8") - self.assertEqual(watch.load_state(path), {}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_weekly_report.py b/tests/test_weekly_report.py deleted file mode 100644 index a241137..0000000 --- a/tests/test_weekly_report.py +++ /dev/null @@ -1,191 +0,0 @@ -"""Tests for report/weekly_report.py: the report written to a file, and a toast only for a deviation.""" - -from __future__ import annotations - -import datetime as dt -import sys -import tempfile -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "report")) - -import ci_report -import weekly_report as weekly - -NOW = dt.datetime(2026, 10, 19, 8, 0, 0, tzinfo=dt.UTC) # a Monday -ORG = "acme" - - -def stats(repo="acme/a", conclusive=20, failed=2, infra=0, p90=None): - s = ci_report.RepoStats( - repo=repo, conclusive=conclusive, failed=failed, infra_failures=infra - ) - s.job_wait_p90_s = p90 - s.jobs_sampled = 1 if p90 is not None else 0 - return s - - -class Deviations(unittest.TestCase): - def test_a_healthy_repository_raises_nothing(self): - self.assertEqual(weekly.find_deviations([stats(failed=2, p90=60)]), []) - - def test_a_high_failure_rate_is_a_deviation(self): - found = weekly.find_deviations([stats(conclusive=20, failed=6)]) - self.assertEqual(len(found), 1) - self.assertIn("acme/a", found[0]) - self.assertIn("30%", found[0]) - - def test_a_few_runs_prove_nothing(self): - # Two failures out of three is noise: below the minimum number of runs nothing is judged. - self.assertEqual(weekly.find_deviations([stats(conclusive=3, failed=2)]), []) - - def test_a_long_queue_is_a_deviation(self): - found = weekly.find_deviations([stats(p90=601)]) - self.assertEqual(len(found), 1) - self.assertIn("10m01s", found[0]) - - def test_infrastructure_failures_are_a_deviation_of_their_own(self): - found = weekly.find_deviations([stats(conclusive=20, failed=4, infra=3)]) - self.assertTrue(any("infrastructure" in f for f in found)) - - def test_the_thresholds_are_parameters(self): - self.assertEqual( - len(weekly.find_deviations([stats(failed=2)], fail_rate_max=0.05)), 1 - ) - self.assertEqual(weekly.find_deviations([stats(p90=601)], wait_p90_max=900), []) - - def test_a_repository_without_data_is_not_judged(self): - self.assertEqual(weekly.find_deviations([stats(conclusive=0, failed=0)]), []) - - -class FakeGithub: - """Just enough of the reads `ci_report.collect` makes.""" - - def __init__(self, failing=False): - self.failing = failing - - def org_repos(self, org): - return [ - {"name": "a", "visibility": "PRIVATE", "isArchived": False}, - {"name": "old", "visibility": "PRIVATE", "isArchived": True}, - {"name": "open", "visibility": "PUBLIC", "isArchived": False}, - ] - - def runs(self, repo, limit): - out = [] - for i in range(10): - conclusion = "failure" if (self.failing and i < 6) else "success" - moment = (NOW - dt.timedelta(hours=i + 1)).strftime("%Y-%m-%dT%H:%M:%SZ") - out.append( - { - "databaseId": i + 1, - "conclusion": conclusion, - "status": "completed", - "workflowName": "CI", - "createdAt": moment, - "startedAt": moment, - "updatedAt": moment, - "event": "push", - "headBranch": "main", - } - ) - return out - - def jobs(self, repo, run_id): - return [ - { - "name": "Verify", - "conclusion": "failure", - "startedAt": None, - "steps": [{"name": "Tests", "conclusion": "failure"}], - } - ] - - def job_timings(self, repo, run_id): - return [] - - def runners(self, repo): - return [] - - def queued_runs(self, repo): - return [] - - def open_prs(self, repo): - return [] - - -class Running(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.out = Path(self.tmp.name) - self.toasts = [] - - def tearDown(self): - self.tmp.cleanup() - - def go(self, gh, notify_path=r"C:\x\notify.ps1"): - return weekly.run( - gh, - ORG, - self.out, - NOW, - days=7, - notify_path=notify_path, - runner=self.toasts.append, - ) - - def test_the_report_is_written_with_the_date_in_its_name_and_as_latest(self): - result = self.go(FakeGithub()) - dated = self.out / "ci-report-2026-10-19.md" - self.assertTrue(dated.exists()) - self.assertEqual( - (self.out / "latest.md").read_text(encoding="utf-8"), - dated.read_text(encoding="utf-8"), - ) - text = dated.read_text(encoding="utf-8") - self.assertIn("# CI health report", text) - self.assertIn("acme/a", text) - self.assertEqual(result.path, dated) - - def test_only_private_repositories_that_are_not_archived_are_reported(self): - self.go(FakeGithub()) - text = (self.out / "latest.md").read_text(encoding="utf-8") - self.assertNotIn("acme/old", text) - self.assertNotIn("acme/open", text) - - def test_a_healthy_week_writes_the_report_and_raises_no_toast(self): - result = self.go(FakeGithub()) - self.assertEqual(result.deviations, []) - self.assertEqual(self.toasts, []) - - def test_a_bad_week_raises_one_toast_naming_the_repositories(self): - result = self.go(FakeGithub(failing=True)) - self.assertGreaterEqual(len(result.deviations), 1) - self.assertEqual(len(self.toasts), 1) - command = self.toasts[0] - self.assertIn("-File", command) - self.assertIn("acme/a", command[command.index("-Body") + 1]) - - def test_without_a_notify_path_nothing_is_toasted(self): - self.go(FakeGithub(failing=True), notify_path=None) - self.assertEqual(self.toasts, []) - - def test_a_failing_toast_never_stops_the_report(self): - def boom(command): - raise OSError("no powershell") - - result = weekly.run( - FakeGithub(failing=True), - ORG, - self.out, - NOW, - days=7, - notify_path="n.ps1", - runner=boom, - ) - self.assertTrue(result.path.exists()) - - -if __name__ == "__main__": - unittest.main() diff --git a/train/automerge.py b/train/automerge.py deleted file mode 100644 index 186bd33..0000000 --- a/train/automerge.py +++ /dev/null @@ -1,565 +0,0 @@ -"""Merge sealed pull requests into `main` for every repository of a list (the merge train). - - py -3 automerge.py --config repos.json # one cycle over every repository - py -3 automerge.py --config repos.json --dry-run # say what would happen, change nothing - -GitHub's auto-merge needs branch protection, which free private repositories do not have, so the -desktop does it: a scheduled task runs this every two minutes with the owner's `gh` login. Per -repository and cycle, at most one pull request is merged. A pull request is merged only when all of -this holds, and anything unclear is skipped, never merged: - -- open, into the base branch, not a draft, labelled `automerge`; -- GitHub says it is mergeable (no conflicts); -- the repository's gate check is green on its head commit, and, if `require_seal` is set, its head - carries the `ci-ok/` seal; -- its head contains the base branch. A sealed head that misses commits of the base was never tested - together with them, so the train merges the base into the branch through the API (never a force - push), stops for that cycle, and merges the new head once CI is green again. One stale pull - request is updated per repository and cycle, and only when no other one is ready to merge. - -A conflict (found by GitHub or while updating the branch) is flagged: the pull request gets the -`needs-human` label and loses `automerge`, so the train does not try again until the owner resolves -it and labels it again. The merge pins the exact head (`--match-head-commit`), so a push after the -checks cannot slip in. The configuration is a JSON file, see `repos.example.json`. -""" - -from __future__ import annotations - -import argparse -import datetime as dt -import hashlib -import json -import re -import subprocess -import sys -from collections.abc import Callable -from dataclasses import dataclass -from pathlib import Path - -PR_FIELDS = "number,headRefOid,baseRefName,isDraft,mergeable,labels" -REPO_PATTERN = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$") - - -class ConfigError(ValueError): - """The configuration file cannot be used.""" - - -@dataclass(frozen=True) -class Settings: - label: str = "automerge" - needs_human_label: str = "needs-human" - # A workflow run queued this long is logged once: a runner that is offline or saturated holds - # jobs for up to 24 hours before they fail. - queue_alert_minutes: int = 30 - - -@dataclass(frozen=True) -class RepoConfig: - repo: str - gate_check: str = "Gate / Gate" - require_seal: bool = False - base: str = "main" - # How `gh pr merge` merges; a repository may allow only some methods (contrast-viewer: squash). - merge_method: str = "merge" - - -MERGE_METHODS = ("merge", "squash", "rebase") - - -def load_config(path: Path | str) -> tuple[Settings, list[RepoConfig]]: - try: - data = json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as exc: - raise ConfigError(f"cannot read {path}: {exc}") from exc - if not isinstance(data, dict): - raise ConfigError("the configuration must be a JSON object") - - defaults = Settings() - settings = Settings( - label=_text(data, "label", defaults.label), - needs_human_label=_text(data, "needs_human_label", defaults.needs_human_label), - queue_alert_minutes=_positive_int( - data, "queue_alert_minutes", defaults.queue_alert_minutes - ), - ) - entries = data.get("repos") - if not isinstance(entries, list) or not entries: - raise ConfigError("`repos` must be a non-empty list") - - repos = [] - for entry in entries: - if not isinstance(entry, dict): - raise ConfigError("every entry of `repos` must be an object") - repo = entry.get("repo") - if not isinstance(repo, str) or not REPO_PATTERN.match(repo): - raise ConfigError(f"`repo` must look like owner/name, got {repo!r}") - require_seal = entry.get("require_seal", False) - if not isinstance(require_seal, bool): - raise ConfigError(f"{repo}: `require_seal` must be true or false") - merge_method = _text(entry, "merge_method", RepoConfig.merge_method) - if merge_method not in MERGE_METHODS: - raise ConfigError( - f"{repo}: `merge_method` must be one of {', '.join(MERGE_METHODS)}" - ) - repos.append( - RepoConfig( - repo=repo, - gate_check=_text(entry, "gate_check", RepoConfig.gate_check), - require_seal=require_seal, - base=_text(entry, "base", RepoConfig.base), - merge_method=merge_method, - ) - ) - return settings, repos - - -def _positive_int(source: dict, key: str, default: int) -> int: - value = source.get(key, default) - if isinstance(value, bool) or not isinstance(value, int) or value < 1: - raise ConfigError(f"`{key}` must be a positive integer") - return value - - -def _text(source: dict, key: str, default: str) -> str: - value = source.get(key, default) - if not isinstance(value, str) or not value: - raise ConfigError(f"`{key}` must be a non-empty string") - return value - - -def run_gh(command: list[str]) -> str: - # Every command is built in this file from fixed words and GitHub's own numbers and shas. - # No console window for `gh`: the task runs every two minutes on the owner's desktop. - no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0) - return subprocess.run( - command, check=True, capture_output=True, text=True, creationflags=no_window - ).stdout - - -class Github: - """The few GitHub operations the train needs, over the `gh` command line.""" - - def __init__(self, run: Callable[[list[str]], str] = run_gh): - self._run = run - - def queued_runs(self, repo: str) -> list[dict]: - out = self._run( - [ - "gh", - "run", - "list", - "--repo", - repo, - "--status", - "queued", - "--json", - "databaseId,createdAt,headBranch,workflowName", - "--limit", - "50", - ] - ) - return json.loads(out or "[]") - - def open_prs(self, repo: str, label: str) -> list[dict]: - out = self._run( - [ - "gh", - "pr", - "list", - "--repo", - repo, - "--state", - "open", - "--label", - label, - "--json", - PR_FIELDS, - "--limit", - "50", - ] - ) - return json.loads(out or "[]") - - def gate_green(self, repo: str, sha: str, check_name: str) -> bool: - out = self._run( - ["gh", "api", f"repos/{repo}/commits/{sha}/check-runs?per_page=100"] - ) - runs = [ - r - for r in json.loads(out or "{}").get("check_runs", []) - if r.get("name") == check_name - ] - return bool(runs) and all( - r.get("status") == "completed" and r.get("conclusion") == "success" - for r in runs - ) - - def sealed(self, repo: str, sha: str) -> bool: - try: - self._run(["gh", "api", f"repos/{repo}/git/ref/tags/ci-ok/{sha}"]) - except subprocess.CalledProcessError: - return False - return True - - def behind_by(self, repo: str, base: str, sha: str) -> int: - out = self._run(["gh", "api", f"repos/{repo}/compare/{base}...{sha}"]) - return int(json.loads(out)["behind_by"]) - - def merge(self, repo: str, number: int, sha: str, method: str = "merge") -> None: - if method not in MERGE_METHODS: - raise ValueError(f"unknown merge method {method!r}") - self._run( - [ - "gh", - "pr", - "merge", - str(number), - "--repo", - repo, - f"--{method}", - "--match-head-commit", - sha, - ] - ) - - def comment(self, repo: str, number: int, body: str) -> None: - self._run(["gh", "pr", "comment", str(number), "--repo", repo, "--body", body]) - - def update_branch(self, repo: str, number: int, sha: str) -> str: - try: - self._run( - [ - "gh", - "api", - "-X", - "PUT", - f"repos/{repo}/pulls/{number}/update-branch", - "-f", - f"expected_head_sha={sha}", - ] - ) - except subprocess.CalledProcessError as exc: - if "conflict" in (exc.stderr or "").lower(): - return "conflict" - raise - return "updated" - - def flag_needs_human( - self, repo: str, number: int, label: str, needs_label: str - ) -> None: - try: - self._run( - [ - "gh", - "label", - "create", - needs_label, - "--repo", - repo, - "--color", - "D93F0B", - "--description", - "A person must resolve this before the merge train retries", - ] - ) - except subprocess.CalledProcessError: - pass # most likely the label exists already; the edit below fails loudly if not - self._run( - [ - "gh", - "pr", - "edit", - str(number), - "--repo", - repo, - "--add-label", - needs_label, - "--remove-label", - label, - ] - ) - - -def classify(pr: dict, cfg: RepoConfig, settings: Settings, gh) -> tuple[str, str]: - """(state, reason) of one pull request: ready, stale, conflict or skip.""" - if settings.label not in {item.get("name") for item in pr.get("labels", [])}: - return "skip", "no automerge label" - if pr.get("isDraft"): - return "skip", "draft" - if pr.get("baseRefName") != cfg.base: - return "skip", f"not into {cfg.base}" - mergeable = pr.get("mergeable") - if mergeable == "CONFLICTING": - return "conflict", "conflicts with the base branch" - if mergeable != "MERGEABLE": - return "skip", f"mergeability is {mergeable}" - - sha = pr["headRefOid"] - if not gh.gate_green(cfg.repo, sha, cfg.gate_check): - return "skip", f"gate check '{cfg.gate_check}' is not green on its head" - if cfg.require_seal and not gh.sealed(cfg.repo, sha): - return "skip", "no ci-ok seal on its head" - behind = gh.behind_by(cfg.repo, cfg.base, sha) - if behind > 0: - return "stale", f"head misses {behind} commit(s) of {cfg.base}" - return "ready", "ready" - - -# Written as a comment on every pull request the train merges; the health report counts the merged -# pull requests that lack it as merged outside the train. -MERGE_MARK = "" - - -def text_version(text: str) -> str: - """A short fingerprint of a script, the same for LF and CRLF copies.""" - normalised = text.replace("\r\n", "\n") - return hashlib.sha256(normalised.encode("utf-8")).hexdigest()[:12] - - -def script_version() -> str: - return text_version(Path(__file__).read_text(encoding="utf-8")) - - -class Heartbeat: - """Decides when the train writes its hourly proof of life, and remembers the last one.""" - - EVERY = dt.timedelta(minutes=60) - - def __init__(self, path: Path | str | None): - self.path = Path(path) if path else None - self._last: dt.datetime | None = None - if self.path is not None and self.path.exists(): - try: - self._last = dt.datetime.fromisoformat( - json.loads(self.path.read_text(encoding="utf-8"))["last"] - ) - except (OSError, ValueError, KeyError, TypeError): - self._last = ( - None # an unreadable state only means one heartbeat too many - ) - - def due(self, now: dt.datetime) -> bool: - return self._last is None or now - self._last >= self.EVERY - - def mark(self, now: dt.datetime) -> None: - self._last = now - if self.path is not None: - self.path.write_text( - json.dumps({"last": now.isoformat()}), encoding="utf-8" - ) - - -class QueueAlerts: - """Remembers which queued runs were already reported, so each one is logged once.""" - - def __init__(self, path: Path | str | None): - self.path = Path(path) if path else None - self._seen: dict[str, list[int]] = {} - if self.path is not None and self.path.exists(): - try: - data = json.loads(self.path.read_text(encoding="utf-8")) - self._seen = {repo: [int(i) for i in ids] for repo, ids in data.items()} - except (OSError, ValueError, TypeError, AttributeError): - self._seen = {} # an unreadable state only means some runs are reported again - - def check( - self, - repo: str, - runs: list[dict], - now: dt.datetime, - threshold_minutes: int, - log: Callable[[str], None], - persist: bool = True, - ) -> None: - known = set(self._seen.get(repo, [])) - keep = known & {run["databaseId"] for run in runs} - for run in sorted(runs, key=lambda item: item["databaseId"]): - run_id = run["databaseId"] - created = dt.datetime.fromisoformat(run["createdAt"]) - minutes = (now - created).total_seconds() / 60 - if minutes >= threshold_minutes and run_id not in known: - log( - f"queued {int(minutes)} min: {run.get('workflowName', '?')} on " - f"{run.get('headBranch', '?')} (run {run_id})" - ) - keep.add(run_id) - if persist and (keep != known or repo not in self._seen): - self._seen[repo] = sorted(keep) - self._save() - - def _save(self) -> None: - if self.path is not None: - self.path.write_text( - json.dumps(self._seen, sort_keys=True), encoding="utf-8" - ) - - -def run_cycle( - gh, - configs: list[RepoConfig], - settings: Settings, - *, - dry_run: bool, - log: Callable[[str], None], - alerts: QueueAlerts | None = None, - now: dt.datetime | None = None, - heartbeat: Heartbeat | None = None, -) -> int: - """One pass over every repository. Returns 0 when nothing went wrong, 1 otherwise.""" - code = 0 - moment = now or dt.datetime.now(dt.UTC) - seen: list[int] = [] - for cfg in configs: - repo_log = lambda line, r=cfg.repo: log(f"{r} {line}") - if alerts is not None: - # A failing queue query must never stop the merging that follows. - try: - runs = gh.queued_runs(cfg.repo) - alerts.check( - cfg.repo, - runs, - moment, - settings.queue_alert_minutes, - repo_log, - persist=not dry_run, - ) - except ( - subprocess.CalledProcessError, - OSError, - ValueError, - KeyError, - ) as exc: - detail = (getattr(exc, "stderr", "") or str(exc)).strip()[:200] - repo_log(f"queue check failed: {detail}") - try: - _repo_cycle(gh, cfg, settings, dry_run, repo_log, seen) - except (subprocess.CalledProcessError, OSError, ValueError, KeyError) as exc: - detail = (getattr(exc, "stderr", "") or str(exc)).strip()[:300] - log(f"{cfg.repo}: failed: {detail}") - code = 1 - if heartbeat is not None and heartbeat.due(moment): - log( - f"heartbeat: {len(configs)} repositories, {sum(seen)} labelled pull requests, " - f"script {script_version()}" - ) - if not dry_run: - heartbeat.mark(moment) - return code - - -def _repo_cycle( - gh, - cfg: RepoConfig, - settings: Settings, - dry_run: bool, - log, - seen: list[int] | None = None, -) -> None: - prs = gh.open_prs(cfg.repo, settings.label) - if seen is not None: - seen.append(len(prs)) # for the heartbeat line - if not prs: - return - states = {} - for pr in sorted(prs, key=lambda p: p["number"]): - states[pr["number"]] = (pr, *classify(pr, cfg, settings, gh)) - for number, (_, state, reason) in sorted(states.items()): - log(f"#{number}: {reason}") - - tag = " (dry run)" if dry_run else "" - for number, (pr, state, _) in sorted(states.items()): - if state == "conflict": - log(f"#{number}: flagged {settings.needs_human_label}{tag}") - if not dry_run: - gh.flag_needs_human( - cfg.repo, number, settings.label, settings.needs_human_label - ) - - ready = [ - (n, pr) for n, (pr, state, _) in sorted(states.items()) if state == "ready" - ] - stale = [ - (n, pr) for n, (pr, state, _) in sorted(states.items()) if state == "stale" - ] - for number, _ in ready[1:]: - log(f"#{number}: waits for the next cycle") - - if ready: - number, pr = ready[0] - if dry_run: - log(f"#{number}: would merge {pr['headRefOid'][:12]} (dry run)") - return - try: - gh.merge(cfg.repo, number, pr["headRefOid"], cfg.merge_method) - except subprocess.CalledProcessError as exc: - log(f"#{number}: merge refused: {(exc.stderr or '').strip()[:300]}") - raise - log(f"#{number}: merged {pr['headRefOid'][:12]}") - # The mark tells apart a merge made by the train from one made around it (FR13). The merge - # is already done: a failing comment is logged, never an error of the cycle. - try: - gh.comment( - cfg.repo, - number, - f"{MERGE_MARK}\nMerged by the merge train at head `{pr['headRefOid'][:12]}`.", - ) - except subprocess.CalledProcessError as exc: - log(f"#{number}: mark failed: {(exc.stderr or '').strip()[:200]}") - elif stale: - number, pr = stale[0] - if dry_run: - log(f"#{number}: would merge {cfg.base} into the branch (dry run)") - return - if gh.update_branch(cfg.repo, number, pr["headRefOid"]) == "conflict": - log(f"#{number}: update conflicts, flagged {settings.needs_human_label}") - gh.flag_needs_human( - cfg.repo, number, settings.label, settings.needs_human_label - ) - else: - log( - f"#{number}: {cfg.base} merged into the branch; waiting for a new green gate" - ) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument( - "--config", - default=str(Path(__file__).with_name("repos.json")), - help="JSON list of repositories (default: repos.json beside this script)", - ) - parser.add_argument( - "--dry-run", action="store_true", help="say what would happen, change nothing" - ) - parser.add_argument("--log", help="append to this file instead of printing") - args = parser.parse_args(argv) - - def log(message: str) -> None: - line = f"[{dt.datetime.now().isoformat(timespec='seconds')}] {message}" - if args.log: - # The scheduled task runs under pythonw, which has no console: the log is the only trace. - with open(args.log, "a", encoding="utf-8") as handle: - handle.write(line + "\n") - else: - print(line, flush=True) - - try: - settings, configs = load_config(args.config) - except ConfigError as exc: - log(f"configuration error: {exc}") - return 2 - alerts = QueueAlerts(Path(args.config).with_name("queue-alerts.json")) - heartbeat = Heartbeat(Path(args.config).with_name("heartbeat.json")) - return run_cycle( - Github(), - configs, - settings, - dry_run=args.dry_run, - log=log, - alerts=alerts, - heartbeat=heartbeat, - ) - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/train/install.ps1 b/train/install.ps1 deleted file mode 100644 index 2240da0..0000000 --- a/train/install.ps1 +++ /dev/null @@ -1,78 +0,0 @@ -# Installs the merge train on the desktop: every two minutes, one cycle over the repositories listed -# in repos.json (see automerge.py). Run it from a normal PowerShell window of the owner's session: -# scheduled tasks created from a sandboxed or elevated shell can be private to that shell. -# -# powershell -NoProfile -ExecutionPolicy Bypass -File train\install.ps1 -# powershell -NoProfile -ExecutionPolicy Bypass -File train\install.ps1 -Remove -# -# The script is copied to $Destination, so the task does not depend on which branch a checkout is -# on (the crm-platform train learned this the hard way). Run this again after automerge.py changes. -# repos.json is created from repos.example.json only when it does not exist; it is never overwritten. -# The task uses the owner's `gh` login; nothing else is stored. -param( - [string]$Destination = 'D:\Development\Tools\ci-train', - [switch]$Remove -) - -$ErrorActionPreference = 'Stop' -$taskName = 'CI train' - -if ($Remove) { - Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue - Write-Host "Task '$taskName' removed. Files in $Destination are left in place." - exit 0 -} - -if (-not (Get-Command gh -ErrorAction SilentlyContinue)) { throw 'gh is not installed' } -gh auth status *> $null -if ($LASTEXITCODE -ne 0) { throw 'gh is not signed in: run gh auth login' } - -# The real pythonw.exe, not the `pyw` launcher: under the task scheduler the launcher exited with -# code 2 and wrote nothing (crm-platform, 30/09/2026), while the interpreter itself runs fine. -$python = (py -3 -c "import sys;print(sys.executable)") -$pythonw = Join-Path (Split-Path $python) 'pythonw.exe' -if (-not (Test-Path $pythonw)) { throw "pythonw.exe not found at $pythonw" } - -$source = $PSScriptRoot -$script = Join-Path $Destination 'automerge.py' -$config = Join-Path $Destination 'repos.json' -$log = Join-Path $Destination 'train.log' - -New-Item -ItemType Directory -Force -Path $Destination | Out-Null -Copy-Item -Force (Join-Path $source 'automerge.py') $script -if (-not (Test-Path $config)) { - Copy-Item (Join-Path $source 'repos.example.json') $config - Write-Host "Created $config from the example. Review the list of repositories." -} - -# pythonw: no console window flashing every two minutes; the script writes its own log. -# No -WorkingDirectory: with it the task failed with 0x8007010B on this desktop (30/09/2026), -# although the directory exists; every path below is absolute anyway. -$action = New-ScheduledTaskAction ` - -Execute $pythonw ` - -Argument "`"$script`" --config `"$config`" --log `"$log`"" -$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) ` - -RepetitionInterval (New-TimeSpan -Minutes 2) -$settings = New-ScheduledTaskSettingsSet ` - -MultipleInstances IgnoreNew ` - -ExecutionTimeLimit (New-TimeSpan -Minutes 5) ` - -AllowStartIfOnBatteries ` - -DontStopIfGoingOnBatteries ` - -StartWhenAvailable -$principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" ` - -LogonType Interactive -RunLevel Limited - -Register-ScheduledTask ` - -TaskName $taskName ` - -Action $action ` - -Trigger $trigger ` - -Settings $settings ` - -Principal $principal ` - -Description 'Merges pull requests labelled automerge whose gate is green and whose head contains main.' ` - -Force | Out-Null - -Write-Host "Task '$taskName' installed: every 2 minutes." -Write-Host " Configuration: $config" -Write-Host " Log: $log" -Write-Host " Try without merging: py -3 `"$script`" --config `"$config`" --dry-run" -Write-Host " Remove: train\install.ps1 -Remove" diff --git a/train/repos.example.json b/train/repos.example.json deleted file mode 100644 index be14e09..0000000 --- a/train/repos.example.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "label": "automerge", - "needs_human_label": "needs-human", - "repos": [ - { "repo": "naindev-contrast3d/contrast3d-platform" }, - { "repo": "naindev-contrast3d/contrast3d-bot" }, - { "repo": "naindev-contrast3d/contrast-viewer", "merge_method": "squash" }, - { "repo": "naindev-contrast3d/gha-local-runners" } - ] -}