Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 51 additions & 10 deletions scripts/fleet/repo-universe/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,38 @@
)


def decode_pages(text: str) -> list[dict]:
def validate_entry(entry: object, source: str, index: int) -> dict:
"""One enumeration entry must be a repo object with a string
full_name. Valid JSON with the wrong shape — a string/null entry
in a page array, an API error object saved into a capture, a repo
object missing full_name — must surface as a named error
identifying the capture source and the offending entry, never as
a bare TypeError/KeyError that aborts the run with no indication
of which capture or entry is at fault (#6716; the contract #6652
established on the checker side).
"""
if not isinstance(entry, dict):
raise ValueError(
f"{source}: enumeration entry {index} is not a JSON object: "
f"{entry!r:.80}"
)
if not isinstance(entry.get("full_name"), str):
raise ValueError(
f"{source}: enumeration entry {index} has no string "
f"full_name: {entry!r:.80}"
)
return entry


def decode_pages(text: str, source: str = "enumeration capture") -> list[dict]:
"""Decode one or more concatenated JSON documents.

`gh api --paginate` emits one JSON array (or object) per page, so a
captured enumeration file — like live --paginate output — is a
stream of documents, not a single JSON value. Decode them all and
flatten the entries.
flatten the entries. Every entry is shape-validated as it lands
(validate_entry), so a wrong-shape capture fails at decode time
naming the source and entry instead of crashing a consumer.
"""
entries: list[dict] = []
decoder = json.JSONDecoder()
Expand All @@ -94,16 +119,19 @@ def decode_pages(text: str) -> list[dict]:
break
doc, idx = decoder.raw_decode(text, idx)
if isinstance(doc, list):
entries.extend(doc)
for entry in doc:
entries.append(validate_entry(entry, source, len(entries)))
else:
entries.append(doc)
entries.append(validate_entry(doc, source, len(entries)))
return entries


def load_enumeration(path: str | None) -> list[dict]:
if path is None:
return []
return decode_pages(Path(path).read_text())
return decode_pages(
Path(path).read_text(), source=f"enumeration capture {path}"
)


def merge_repos(*groups: list[dict]) -> list[dict]:
Expand All @@ -112,8 +140,9 @@ def merge_repos(*groups: list[dict]) -> list[dict]:
but the org and user captures can overlap, and the two org
captures are merged before classification (#5615)."""
merged: dict[str, dict] = {}
for group in groups:
for repo in group:
for group_no, group in enumerate(groups):
for i, repo in enumerate(group):
repo = validate_entry(repo, f"merge_repos group {group_no}", i)
merged.setdefault(repo["full_name"], repo)
return list(merged.values())

Expand Down Expand Up @@ -153,7 +182,7 @@ def fetch_live(endpoint: str) -> list[dict]:
check=True,
).stdout
# --paginate concatenates one JSON array per page.
return decode_pages(out)
return decode_pages(out, source=f"live enumeration {endpoint}")


def parse_census(text: str) -> dict[str, dict]:
Expand Down Expand Up @@ -232,7 +261,14 @@ def build(
) -> str:
census = parse_census(census_text)
gh: dict[str, dict] = {}
for repo in org_repos + user_repos:
# build re-indexes by full_name, so it validates entries itself:
# a caller that bypassed decode_pages/merge_repos gets the same
# named error, not a bare KeyError (#6716).
for i, repo in enumerate(org_repos):
repo = validate_entry(repo, "build org_repos", i)
gh[repo["full_name"]] = repo
for i, repo in enumerate(user_repos):
repo = validate_entry(repo, "build user_repos", i)
gh[repo["full_name"]] = repo

names = sorted(set(gh) | set(census), key=str.lower)
Expand Down Expand Up @@ -378,4 +414,9 @@ def main(argv: list[str] | None = None) -> int:


if __name__ == "__main__":
sys.exit(main())
try:
sys.exit(main())
except ValueError as exc:
# A wrong-shape enumeration capture (#6716) is a named,
# actionable failure, not a traceback.
raise SystemExit(f"error: {exc}")
67 changes: 67 additions & 0 deletions scripts/fleet/repo-universe/test_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,73 @@ def test_offline_mode_requires_each_capture_singly(self) -> None:
self.assertIn(flag, proc.stderr)
self.assertFalse(self.out.exists())

def run_gen_raw(self) -> subprocess.CompletedProcess:
return subprocess.run(
[
sys.executable,
str(GENERATE),
"--org-json",
str(self.dir / "org.json"),
"--forks-org-json",
str(self.dir / "forks-org.json"),
"--user-json",
str(self.dir / "user.json"),
"--census",
str(self.dir / "census.md"),
"--census-label",
"fixture census",
"--output",
str(self.out),
],
capture_output=True,
text=True,
)

def assert_wrong_shape_fails_named(self, proc: subprocess.CompletedProcess) -> None:
# #6716: a wrong-shape entry must fail with a clear error
# naming the capture source and the entry — no bare
# TypeError/KeyError traceback, and no artifact written.
self.assertNotEqual(proc.returncode, 0)
self.assertIn("org.json", proc.stderr)
self.assertNotIn("Traceback", proc.stderr)
self.assertNotIn("TypeError", proc.stderr)
self.assertNotIn("KeyError", proc.stderr)
self.assertFalse(self.out.exists())

def test_non_dict_entry_in_page_array_fails_named(self) -> None:
(self.dir / "org.json").write_text(json.dumps(ORG + ["oops"]))
self.assert_wrong_shape_fails_named(self.run_gen_raw())

def test_dict_page_without_full_name_fails_named(self) -> None:
# A saved API error page concatenated after a valid page: the
# object document is an entry with no full_name.
(self.dir / "org.json").write_text(
json.dumps(ORG) + "\n" + json.dumps({"message": "API rate limit exceeded"})
)
proc = self.run_gen_raw()
self.assert_wrong_shape_fails_named(proc)
self.assertIn("full_name", proc.stderr)

def test_null_entry_fails_named(self) -> None:
(self.dir / "org.json").write_text(json.dumps(ORG + [None]))
self.assert_wrong_shape_fails_named(self.run_gen_raw())

def test_consumers_validate_entries_directly(self) -> None:
# build/merge_repos validate entries that never passed
# through decode_pages, so a direct caller gets the named
# error instead of a bare KeyError/TypeError (#6716).
spec = importlib.util.spec_from_file_location("generate", GENERATE)
gen = importlib.util.module_from_spec(spec)
spec.loader.exec_module(gen)
with self.assertRaises(ValueError):
gen.merge_repos([{"name": "no-full-name"}])
with self.assertRaises(ValueError):
gen.build([{"name": "no-full-name"}], [], CENSUS, "label", {})
with self.assertRaises(ValueError):
gen.build([], ["oops"], CENSUS, "label", {})
with self.assertRaises(ValueError):
gen.decode_pages(json.dumps([{"full_name": "a/b"}, None]), source="cap X")

def test_idempotent_zero_diff_on_unchanged_inputs(self) -> None:
first = self.run_gen()
second = self.run_gen()
Expand Down
Loading