Repository navigation
Expand file tree
/
Copy pathcentral_config.py
More file actions
executable file
·333 lines (289 loc) · 13.5 KB
/
Copy pathcentral_config.py
File metadata and controls
executable file
·333 lines (289 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.13"
# dependencies = ["editorconfig==0.17.1", "ruamel.yaml==0.19.1"]
# ///
"""Write and check the central bot-settings repositories from the hub.
CodeRabbit reads a repository named `coderabbit` under the owner as central configuration, and Qodo reads `pr-agent-settings`.
A repository's own file wins over the central one: CodeRabbit ignores the central file, and Qodo overrides each key the own file sets.
The central file turns automatic review off, so it is safe only once every fleet repository sets that key itself.
So it exists only while every live registry repository under the owner sets the key in its own file on its default branch.
`precondition` reports that gate, `write` puts the settings repository's files into a checkout, and `check` reads them back at a ref.
The README comes from `repo-config/central/<name>/README.md`, and the config text is a constant in this file.
The YAML parser is imported inside the code that needs it.
Exit codes: 0 ok, 1 a refusal, a failed precondition or drift, 2 a read or the command could not run.
Only `precondition` exits 1 on a failed gate, since a withheld config is the gate working.
So `write` exits 0 whether it wrote the config or withheld it, and `check` reads a withheld config as no drift.
"""
from __future__ import annotations
import argparse
import sys
import tomllib
from pathlib import Path
from typing import Any, NamedTuple
sys.path.insert(0, str(Path(__file__).resolve().parent))
import gh_graphql
from agent_policy import (
CONFIG_DIR,
TOML_PATH,
YAML_PATH,
Reader,
Refusal,
Result,
Unreadable,
apply,
current_text,
gh_reader,
gh_rest,
keep_endings,
lf_text,
load_registry,
verify_checkout,
)
CENTRAL_DIR = CONFIG_DIR / "central"
README_PATH = "README.md"
GENERATED = "# Generated by ProjectTemplate scripts/central_config.py, so change it there rather than here.\n"
class Settings(NamedTuple):
"""One settings repository: the bot it configures and the file and key the gate reads."""
bot: str
config: str
key: tuple[str, ...]
text: str
TABLE: dict[str, Settings] = {
"coderabbit": Settings(
bot="CodeRabbit",
config=YAML_PATH,
key=("reviews", "auto_review", "enabled"),
text=GENERATED
+ "# A repository carrying its own .coderabbit.yaml uses that file instead of this one.\n"
+ "reviews:\n auto_review:\n enabled: false\n",
),
"pr-agent-settings": Settings(
bot="Qodo",
config=TOML_PATH,
key=("config", "disable_auto_feedback"),
text=GENERATED
+ "# A repository carrying its own .pr_agent.toml overrides what it sets here.\n"
+ "[config]\ndisable_auto_feedback = true\n",
),
}
def settings_for(repo: str) -> tuple[str, str, Settings]:
"""The owner, the name and the table entry for `repo`, or a Refusal."""
owner, _, name = repo.partition("/")
if not owner or name not in TABLE:
raise Refusal(f"{repo} is not a settings repository, expected OWNER/{{{'|'.join(TABLE)}}}")
return owner, name, TABLE[name]
def source_readme(name: str) -> str:
"""The hand-authored README for the settings repository, as LF text."""
path = CENTRAL_DIR / name / README_PATH
text = lf_text(path)
if text is None:
raise Refusal(f"{path} is missing")
return text
def fleet_repos(registry_data: Any, owner: str) -> list[str]:
"""The `owner/name` of every live registry repository under `owner`, refusing where there is none.
An archived or excluded entry is skipped, since it sits outside the fleet, and the account-wide auto-off default is meant to reach it.
Every other status counts, so a status this script does not know keeps the gate shut rather than open.
An entry naming no readable url refuses, since skipping it would drop a repository from the gate.
An empty list would hold the gate vacuously, which is how a mistyped owner would land the central file.
"""
if not isinstance(registry_data, dict):
raise Refusal("the registry file is absent or not an object")
found = []
for entry in registry_data.get("repos", []):
url = entry.get("url") if isinstance(entry, dict) else None
match = gh_graphql.ORIGIN.search(url) if isinstance(url, str) else None
if match is None:
raise Refusal(f"registry entry {entry!r} names no readable repository url")
if entry.get("status") in ("archived", "excluded"):
continue
if match.group(1).lower() == owner.lower():
found.append(f"{match.group(1)}/{match.group(2)}")
if not found:
raise Refusal(
f"the registry lists no live repository under {owner}, so the gate measures nothing"
)
return found
def key_problem(settings: Settings, text: str) -> str | None:
"""Why `text` does not set the key to a bool, or None where it does."""
try:
if settings.config == YAML_PATH:
from ruamel.yaml import YAML, YAMLError
try:
doc = YAML(typ="safe").load(text)
except YAMLError:
return f"{settings.config} does not parse"
else:
doc = tomllib.loads(text)
except tomllib.TOMLDecodeError:
return f"{settings.config} does not parse"
node: Any = doc
for part in settings.key:
node = node.get(part) if isinstance(node, dict) else None
dotted = ".".join(settings.key)
if node is None:
return f"{settings.config} does not set {dotted}"
if not isinstance(node, bool):
return f"{settings.config} sets {dotted} to a value that is not a bool"
return None
def own_file(
slug: str, settings: Settings, run: gh_graphql.Runner = gh_graphql.run_subprocess
) -> Result:
"""Whether `slug` carries its own config on its default branch that sets the key."""
proc = gh_rest(f"repos/{slug}", ".default_branch", run)
branch = proc.stdout.strip()
if proc.returncode != 0 or not branch:
return Result(False, f"{slug}: default branch is unreadable ({proc.stderr.strip()})", True)
try:
text = gh_reader(slug, branch, run)(settings.config)
except Unreadable as exc:
return Result(False, f"{slug}: {settings.config} is unreadable ({exc})", True)
if text is None:
return Result(False, f"{slug}: {settings.config} is absent on {branch}")
problem = key_problem(settings, text)
if problem is not None:
return Result(False, f"{slug}: {problem}")
return Result(True, f"{slug}: {settings.config} sets {'.'.join(settings.key)} on {branch}")
def precondition(
repo: str, registry_data: Any, run: gh_graphql.Runner = gh_graphql.run_subprocess
) -> list[Result]:
"""One result per live registry repository under the settings repository's owner."""
owner, _, settings = settings_for(repo)
return [own_file(slug, settings, run) for slug in fleet_repos(registry_data, owner)]
def lacking(results: list[Result]) -> str:
"""The failed repositories as the withheld line lists them."""
return ", ".join(r.msg.split(":", 1)[0].split("/", 1)[-1] for r in results if not r.ok)
def require_readable(results: list[Result]) -> None:
"""Raise Unreadable naming each repository whose read did not answer."""
unread = [r.msg for r in results if r.unreadable]
if unread:
raise Unreadable("; ".join(unread))
def write(
repo: str,
registry_data: Any,
checkout: Path,
dry_run: bool = False,
run: gh_graphql.Runner = gh_graphql.run_subprocess,
) -> list[str]:
"""Put the README and the gated config into `checkout`, returning one status line per file.
Everything is planned first, so a refusal or an unreadable repository leaves the checkout untouched.
"""
_, name, settings = settings_for(repo)
verify_checkout(checkout, repo)
results = precondition(repo, registry_data, run)
require_readable(results)
readme = keep_endings(checkout / README_PATH, source_readme(name))
steps = [(README_PATH, None if current_text(checkout / README_PATH) == readme else readme)]
if all(r.ok for r in results):
wanted = keep_endings(checkout / settings.config, settings.text)
unchanged = current_text(checkout / settings.config) == wanted
steps.append((settings.config, None if unchanged else wanted))
return apply(checkout, steps, dry_run)
lines = apply(checkout, steps, dry_run, remove=(settings.config,))
lines.append(
f"withheld {settings.config}: {sum(not r.ok for r in results)} repo(s) lack their own "
f"file setting {'.'.join(settings.key)}: {lacking(results)}"
)
return lines
def check(
repo: str,
registry_data: Any,
ref: str,
run: gh_graphql.Runner = gh_graphql.run_subprocess,
) -> list[Result]:
"""What the settings repository holds at `ref` against what `write` would put there."""
_, name, settings = settings_for(repo)
read: Reader = gh_reader(repo, ref, run)
results = []
try:
readme = read(README_PATH)
config = read(settings.config)
except Unreadable as exc:
return [Result(False, f"{repo} at {ref} is unreadable ({exc})", True)]
if readme is None:
results.append(Result(False, f"{README_PATH} is missing, run write to create it"))
else:
same = readme.replace("\r\n", "\n") == source_readme(name)
results.append(
Result(same, f"{README_PATH} {'equals' if same else 'differs from'} the source")
)
pre = precondition(repo, registry_data, run)
if any(r.unreadable for r in pre):
return results + [Result(False, r.msg, True) for r in pre if r.unreadable]
if all(r.ok for r in pre):
if config is None:
results.append(Result(False, f"{settings.config} is missing, run write to create it"))
else:
same = config.replace("\r\n", "\n") == settings.text
msg = f"{settings.config} {'equals' if same else 'differs from'} the generated text"
results.append(Result(same, msg))
return results
count = sum(not r.ok for r in pre)
if config is None:
who = f"{count} repo(s) lack their own file: {lacking(pre)}"
results.append(Result(True, f"{settings.config} is withheld while {who}"))
else:
who = f"{count} repo(s) lacking their own file ({lacking(pre)})"
msg = f"{settings.config} is present and silences {settings.bot} on {who}, run write to remove it"
results.append(Result(False, msg))
return results
def build_parser() -> argparse.ArgumentParser:
"""The command line: three subcommands, each naming the settings repository and the registry."""
parser = argparse.ArgumentParser(
prog="central_config.py",
description="Write and check the central CodeRabbit and Qodo settings repositories.",
epilog="Exit codes: 0 ok, 1 a refusal, a failed precondition or drift, 2 a read or the command could not run. "
"Only precondition exits 1 on a failed gate. A withheld config is no drift to check, and write exits 0 on it.",
)
sub = parser.add_subparsers(dest="command", required=True)
for cmd, text in (
(
"precondition",
"report whether every live registry repository under the owner carries its own file setting the key",
),
(
"write",
"write the README and the gated config into a checkout, never staging or committing",
),
("check", "compare the settings repository at a ref with what write would produce"),
):
one = sub.add_parser(cmd, help=text, description=text)
one.add_argument("--repo", required=True, help="OWNER/NAME of the settings repository")
one.add_argument("--registry", required=True, help="path to registry/repos.json")
if cmd == "write":
one.add_argument("--checkout", required=True, help="the settings repository checkout")
one.add_argument(
"--dry-run", action="store_true", help="plan every file and write none"
)
if cmd == "check":
one.add_argument("--ref", default="main", help="the branch or commit to read")
return parser
def run_command(args: argparse.Namespace, run: gh_graphql.Runner) -> int:
"""Run the parsed subcommand, print its lines, and return its exit code."""
registry_data = load_registry(args.registry)
if args.command == "write":
for line in write(args.repo, registry_data, Path(args.checkout), args.dry_run, run):
print(line)
return 0
if args.command == "precondition":
results = precondition(args.repo, registry_data, run)
else:
results = check(args.repo, registry_data, args.ref, run)
for result in results:
print(f" {'ok ' if result.ok else 'FAIL'} {result.msg}")
if any(result.unreadable for result in results):
return 2
return 0 if all(result.ok for result in results) else 1
def main(argv: list[str] | None = None, run: gh_graphql.Runner = gh_graphql.run_subprocess) -> int:
"""Parse `argv`, run it through `run` for every gh call, and map a refusal or failure to its exit code."""
args = build_parser().parse_args(argv)
try:
return run_command(args, run)
except Refusal as exc:
print(f"central_config.py: {exc}", file=sys.stderr)
return 1
except (OSError, ImportError, Unreadable, gh_graphql.GraphQLError) as exc:
print(f"central_config.py: could not run ({exc})", file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main())