1"""Repository governance from the contracts: owners, the file, the config.
3Each package's ``workshop.toml`` names who reviews it (``[owners]``
4with ``users``, ``teams``, and ``approvals``); the root contract's
5own ``[owners]`` guard the governance declarations themselves, so
6raising a reviewer count is a reviewed merge like any change. This
7module turns those declarations into the forge's CODEOWNERS file (a
8managed generated artifact the drift gate compares offline), into
9the repository settings ``configure`` asserts, and into the
10generated post-merge workflow that applies them, so nobody carries
11forge-specific knowledge in their head.
12"""
14from __future__ import annotations
16from pathlib import Path
17from typing import Any
19from livery.footman import fail
20from livery.forge import Codeowners, CodeownersEntry, Forge, RepoConfig
21from livery.workshop._contract import load_contract
24def _owners_table(contract: dict[str, Any]) -> dict[str, Any]:
25 return dict(contract.get("owners") or {})
28def owners_of(contract: dict[str, Any]) -> tuple[tuple[str, ...], tuple[str, ...], int]:
29 """A contract's ``(users, teams, approvals)`` owner declaration.
31 Approvals default to zero: declared owners document and route
32 review without gating the merge until a count is asked for,
33 which is what a solo maintainer needs (a forge that forbids
34 self-approval deadlocks a solo repo on any required review).
35 """
36 table = _owners_table(contract)
37 users = tuple(str(name) for name in table.get("users", []) if str(name).strip())
38 teams = tuple(str(name) for name in table.get("teams", []) if str(name).strip())
39 approvals = int(table.get("approvals", 0))
40 return users, teams, approvals
43def offline_forge(root: Path) -> Forge:
44 """The contract's forge backend with no credential attached.
46 The codeowners rendering is pure string building, so the drift
47 gate may hold a backend offline; nothing built here may be used
48 for a network call.
49 """
50 from livery.forge import GiteaForge, GithubForge, GitlabForge
52 contract = load_contract(root / "workshop.toml")
53 table = contract.get("forge") or {}
54 kind = str(table.get("kind", ""))
55 url = str(table.get("url", ""))
56 if kind == "github":
57 return GithubForge.connect(url=url, token="")
58 if kind == "gitea":58 ↛ 60line 58 didn't jump to line 60 because the condition on line 58 was always true
59 return GiteaForge.connect(url=url or "http://offline.invalid", token="")
60 if kind == "gitlab":
61 return GitlabForge.connect(url=url or "http://offline.invalid", token="")
62 fail(f"unknown forge kind {kind!r}: use github, gitea, or gitlab")
65def governance_entries(root: Path) -> tuple[CodeownersEntry, ...]:
66 """The neutral ownership declarations, root guard first.
68 The root contract's owners guard the root ``workshop.toml`` and
69 the rendered codeowners file itself (config-as-code guarded by
70 itself); each package's owners guard its directory. A workspace
71 with no owner declarations anywhere answers empty, and no file
72 is generated.
73 """
74 from livery.workshop._packages import discover_packages
76 contract = load_contract(root / "workshop.toml")
77 forge_table = contract.get("forge") or {}
78 owner = str(forge_table.get("owner", ""))
79 if not str(forge_table.get("kind", "")):
80 # No forge declared: nothing to render a dialect for, and a
81 # bare rig must not be forced to invent one.
82 return ()
84 def _qualified(users: tuple[str, ...], teams: tuple[str, ...]) -> tuple[str, ...]:
85 return users + tuple(f"{owner}/{team}" for team in teams)
87 entries: list[CodeownersEntry] = []
88 root_users, root_teams, root_approvals = owners_of(contract)
89 rendered_path = offline_forge(root).codeowners(()).path
90 if root_users or root_teams:
91 guard = _qualified(root_users, root_teams)
92 entries.append(
93 CodeownersEntry(
94 path="/workshop.toml", owners=guard, min_approvals=root_approvals
95 )
96 )
97 entries.append(
98 CodeownersEntry(
99 path=f"/{rendered_path}", owners=guard, min_approvals=root_approvals
100 )
101 )
102 if (root / "packages").is_dir():
103 for package in discover_packages(root):
104 contract_file = package.directory / "workshop.toml"
105 users, teams, approvals = owners_of(load_contract(contract_file))
106 if not (users or teams):
107 continue
108 entries.append(
109 CodeownersEntry(
110 path=f"/{package.path}/",
111 owners=_qualified(users, teams),
112 min_approvals=approvals,
113 )
114 )
115 return tuple(entries)
118def codeowners_file(root: Path) -> Codeowners | None:
119 """The rendered codeowners artifact, or None with no declarations."""
120 entries = governance_entries(root)
121 if not entries:
122 return None
123 return offline_forge(root).codeowners(entries)
126def governance_paths(root: Path) -> tuple[str, ...]:
127 """The paths whose change means governance may need re-applying."""
128 paths = ["workshop.toml", "packages/*/workshop.toml"]
129 rendered = codeowners_file(root)
130 if rendered is not None:130 ↛ 131line 130 didn't jump to line 131 because the condition on line 130 was never true
131 paths.append(rendered.path)
132 return tuple(paths)
135def governance_config(root: Path) -> RepoConfig:
136 """The approvals half of the repository settings.
138 The repo-wide count is the highest any declaration asks, because
139 GitHub and Gitea express one count through protection; GitLab's
140 per-path sections carry the rest, where a paid tier enforces
141 them. No declarations anywhere means no approval requirement.
142 """
143 entries = governance_entries(root)
144 if not entries:
145 return RepoConfig()
146 highest = max(entry.min_approvals for entry in entries)
147 # A count of zero asserts zero and requires no codeowner review
148 # either: on a forge that forbids self-approval, a codeowner
149 # requirement alone still deadlocks a solo repo, and ownership
150 # stays documented in the file.
151 return RepoConfig(
152 min_approvals=highest,
153 require_codeowner_review=highest > 0,
154 )
157def unknown_owners(root: Path, forge: Forge, owner: str) -> tuple[str, ...]:
158 """Declared owners the forge does not know, for configure's check.
160 Users are checked against ``members(owner)``, teams against
161 ``teams(owner)``; the answers are live listings, so this runs
162 only where the forge is already being spoken to, never on the
163 merge path.
164 """
165 members = set(forge.members(owner))
166 teams = set(forge.teams(owner))
167 missing: list[str] = []
168 for entry in governance_entries(root):
169 for name in entry.owners:
170 _, slash, team = name.partition("/")
171 if slash:
172 if team not in teams and name not in teams:172 ↛ 173line 172 didn't jump to line 173 because the condition on line 172 was never true
173 missing.append(f"team {name} (declared on {entry.path})")
174 elif name not in members:
175 missing.append(f"user {name} (declared on {entry.path})")
176 return tuple(dict.fromkeys(missing))