diff --git a/cli/administration/deploy/ci/gh.py b/cli/administration/deploy/ci/gh.py index 4e3a69a7b3..1d94b9e80f 100644 --- a/cli/administration/deploy/ci/gh.py +++ b/cli/administration/deploy/ci/gh.py @@ -104,3 +104,15 @@ def fetch_run(run_id: str, repo: str | None = None) -> dict: return json.loads( _gh(["run", "view", run_id, "--json", "jobs,displayTitle"], repo=repo) ) + + +def fetch_run_ref(run: str, repo: str) -> dict: + """Jobs plus the run title of a run given as a URL or a bare id. + + Args: + run: a run URL, or a bare run id that resolves against ``repo``. + repo: ``owner/repo`` a bare id belongs to. + """ + if run.isdigit(): + return fetch_run(run, repo=repo) + return fetch_run(run_id_from_url(run), repo=slug_from_url(run)) diff --git a/cli/administration/deploy/ci/selections.py b/cli/administration/deploy/ci/selections.py index fe33b9d581..d7c43a83c5 100644 --- a/cli/administration/deploy/ci/selections.py +++ b/cli/administration/deploy/ci/selections.py @@ -37,7 +37,13 @@ if TYPE_CHECKING: from collections.abc import Iterable, Mapping from typing import Any -from .runs import _effective, _iter_deploy_jobs +from .runs import ( + _effective, + _iter_deploy_jobs, + dispatched_priority, + parse_role_statuses, + untriggered_priority, +) def failed_selections(jobs: list[dict], *, strict: bool = False) -> list[str]: @@ -130,6 +136,31 @@ def collapse_failures(tokens: Iterable[str], hard: Iterable[str]) -> list[str]: return sorted(roles | pinned) +def retrigger_entries( + source: dict, repo: str, *, strict: bool, roles_only: bool +) -> tuple[list[str], list[str]]: + """The two halves of the priority line a retrigger of ``source`` dispatches. + + Args: + source: the run as ``gh.fetch_run`` returns it. + repo: ``owner/repo`` the run lives in. + strict: only hard failures (❌) count as failed. + roles_only: hard failures come back as role names, see + :func:`collapse_failures`. + + Returns: + The failed selections, and the priority entries the run never deployed. + """ + jobs = source["jobs"] + failed = failed_selections(jobs, strict=strict) + if roles_only: + failed = collapse_failures(failed, failed_selections(jobs, strict=True)) + untriggered = untriggered_priority( + dispatched_priority(source, repo), parse_role_statuses(jobs) + ) + return failed, untriggered + + def _variants(entry: Mapping[str, Any]) -> tuple[int, ...]: """The variant shards one matrix row covers.""" return tuple(int(part) for part in str(entry.get("variant", "")).split(",") if part) diff --git a/cli/administration/deploy/ci/trigger/__main__.py b/cli/administration/deploy/ci/trigger/__main__.py index dc919bbb74..2d1a23e9b1 100644 --- a/cli/administration/deploy/ci/trigger/__main__.py +++ b/cli/administration/deploy/ci/trigger/__main__.py @@ -27,14 +27,6 @@ _WORKFLOW = "entry-manual-steer.yml" _ALL = "__ALL__" -def _fetch(run: str, repo: str) -> dict: - """The jobs and title of *run*, given as a URL or a bare id (which - resolves against *repo*, the current branch's own).""" - if run.isdigit(): - return gh.fetch_run(run, repo=repo) - return gh.fetch_run(gh.run_id_from_url(run), repo=gh.slug_from_url(run)) - - def _ranking(whitelist: str, config: dict[str, str]) -> list[dict[str, str]]: """The regular line the retrigger's own discovery would walk. @@ -251,7 +243,7 @@ def main(argv: list[str] | None = None) -> int: source = None if args.run: - source = _fetch(args.run, repo) + source = gh.fetch_run_ref(args.run, repo) elif args.failed is not None: run = runs.find_last_deploy_run(branch, repo=repo) if run is None: @@ -271,14 +263,8 @@ def main(argv: list[str] | None = None) -> int: p.error("--apps was empty") whitelist = apps elif args.failed is not None: - statuses = runs.parse_role_statuses(source["jobs"]) - failed = selections.failed_selections(source["jobs"], strict=args.strict) - if args.roles_only: - failed = selections.collapse_failures( - failed, selections.failed_selections(source["jobs"], strict=True) - ) - untriggered = runs.untriggered_priority( - runs.dispatched_priority(source, repo), statuses + failed, untriggered = selections.retrigger_entries( + source, repo, strict=args.strict, roles_only=args.roles_only ) if not failed and not untriggered: print("Nothing failed in that run; not triggering.") diff --git a/cli/meta/ci/priority/__init__.py b/cli/meta/ci/priority/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cli/meta/ci/priority/__main__.py b/cli/meta/ci/priority/__main__.py new file mode 100644 index 0000000000..c6b6ff2af2 --- /dev/null +++ b/cli/meta/ci/priority/__main__.py @@ -0,0 +1,82 @@ +"""Print the priority line a retrigger of a CI run dispatches, on one line.""" + +from __future__ import annotations + +import argparse +import sys + +from cli.administration.deploy.ci import gh, runs, selections + + +def _source(run: str | None) -> tuple[dict, str] | None: + """The run to read and the repository it lives in. + + Args: + run: a run URL or a bare run id; ``None`` reads the latest deploy run + of the current branch. + + Returns: + The run as ``gh.fetch_run`` returns it and its ``owner/repo``, or + ``None`` when the current branch has no deploy run. + """ + repo = gh.resolve_repo() + if run: + owner_repo = repo if run.isdigit() else gh.slug_from_url(run) + return gh.fetch_run_ref(run, repo), owner_repo + found = runs.find_last_deploy_run(gh.current_branch(), repo=repo) + if found is None: + return None + return {"jobs": found["_jobs"], "displayTitle": found.get("displayTitle", "")}, repo + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser( + prog="infinito meta ci priority", + description=( + "Print the priority line that 'infinito administration deploy ci " + "trigger --failed' dispatches for a run: every selection that was not " + "green, with its variant, deploy mode, network and distro, plus the " + "priority entries the run never deployed. The entries come out " + "space-separated on a single line, ready to paste into the priority " + "input of the manual CI workflow. Nothing is dispatched." + ), + ) + p.add_argument( + "run", + nargs="?", + default=None, + metavar="URL|ID", + help="Run URL or bare run id. Default: the latest deploy run on the current branch.", + ) + p.add_argument( + "--strict", + action="store_true", + help="Only hard failures (❌), not cancelled or still-running jobs.", + ) + p.add_argument( + "--roles-only", + action="store_true", + help="Hard failures come back as role names instead of their exact axes.", + ) + args = p.parse_args(argv) + + resolved = _source(args.run) + if resolved is None: + print( + "No CI run with deploy jobs found on the current branch.", file=sys.stderr + ) + return 1 + source, repo = resolved + failed, untriggered = selections.retrigger_entries( + source, repo, strict=args.strict, roles_only=args.roles_only + ) + entries = sorted(set(failed) | set(untriggered)) + if not entries: + print("Nothing failed in that run.", file=sys.stderr) + return 0 + print(" ".join(entries)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/unit/python/cli/meta/ci/test_priority.py b/tests/unit/python/cli/meta/ci/test_priority.py new file mode 100644 index 0000000000..f1892200c5 --- /dev/null +++ b/tests/unit/python/cli/meta/ci/test_priority.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +import io +import unittest +import unittest.mock as mock +from contextlib import redirect_stderr, redirect_stdout + +from cli.administration.deploy.ci import gh, runs +from cli.meta.ci.priority import __main__ as priority +from tests.unit.python.cli.administration.deploy.ci.test_trigger import ( + _FAILED_TOKENS, + _RUN_URL, + _SOURCE_RUN, + _job, +) + +_NEVER_DEPLOYED = "web-app-z#1@compose+tor" + + +class TestPriorityLine(unittest.TestCase): + def _run(self, source: dict, inputs: dict[str, str]) -> tuple[int, str, str]: + out, err = io.StringIO(), io.StringIO() + with ( + mock.patch.object(gh, "resolve_repo", return_value="o/r"), + mock.patch.object(gh, "fetch_run", return_value=source), + mock.patch.object(runs, "inputs_from_jobs", return_value=inputs), + redirect_stdout(out), + redirect_stderr(err), + ): + rc = priority.main([_RUN_URL]) + return rc, out.getvalue(), err.getvalue() + + def test_failed_and_never_deployed_entries_print_on_one_line(self) -> None: + rc, out, _ = self._run(_SOURCE_RUN, {"priority": _NEVER_DEPLOYED}) + self.assertEqual(rc, 0) + self.assertEqual( + out, + " ".join(sorted([*_FAILED_TOKENS.split(), _NEVER_DEPLOYED])) + "\n", + ) + + def test_a_green_run_prints_nothing(self) -> None: + green = { + "jobs": [_job("docker", "web-app-x", "success")], + "displayTitle": _SOURCE_RUN["displayTitle"], + } + rc, out, err = self._run(green, {}) + self.assertEqual(rc, 0) + self.assertEqual(out, "") + self.assertIn("Nothing failed", err) + + +if __name__ == "__main__": + unittest.main()