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
129 changes: 2 additions & 127 deletions .github/scripts/validate_community_preset.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,23 +335,10 @@ def submission(args: argparse.Namespace) -> None:
raise Blocked("original catalog entry is not an object")
if previous is not None and not isinstance(previous.get("created_at"), str):
raise Blocked("original catalog entry has no created_at to preserve")
original_rows = documentation_rows(
read_text(args.docs, "original documentation", Blocked), Blocked
)
expected_row = documentation_row(expected)
previous_row = None
if previous is not None:
previous_row = existing_documentation_row(original_rows, previous)
snapshot = {
"expected": expected,
"created_at": previous.get("created_at") if previous else None,
"expected_timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT00:00:00Z"),
"documentation": {
"expected_row_count": original_rows.count(expected_row),
"previous_row": previous_row,
"previous_row_count": original_rows.count(previous_row)
if previous_row is not None else 0,
},
}
try:
args.snapshot.write_text(json.dumps(snapshot), encoding="utf-8")
Expand All @@ -360,85 +347,6 @@ def submission(args: argparse.Namespace) -> None:
print("PASSED: published preset.yml, release tag, README, and issue fields agree")


def documentation_row(entry: dict) -> str:
def cell(value: str) -> str:
return value.replace("\\", r"\\").replace("|", r"\|").replace("\n", " ")

provided = entry["provides"]
quantities = [
f"{count} {name[:-1] if count == 1 else name}"
for name, count in provided.items() if count
]
dependencies = entry["requires"].get("extensions", [])
requires = ", ".join(f"{name} extension" for name in dependencies) or "—"
repo = entry["repository"].rstrip("/").rsplit("/", 1)[-1]
return (
f"| {cell(entry['name'])} | {cell(entry['description'])} | "
f"{', '.join(quantities)} | {requires} | "
f"[{repo}]({entry['repository']}) |"
)


def markdown_table_cells(row: str) -> list[str]:
cells = []
cell = []
escaped = False
for character in row:
if escaped:
if character in ("\\", "|"):
cell.append(character)
else:
cell.extend(("\\", character))
escaped = False
elif character == "\\":
escaped = True
elif character == "|":
cells.append("".join(cell).strip())
cell = []
else:
cell.append(character)
if escaped:
cell.append("\\")
cells.append("".join(cell).strip())
return cells


def documentation_rows(text: str, error_type: type[Exception]) -> list[str]:
lines = text.splitlines()
try:
start = next(i for i, line in enumerate(lines) if line.startswith("| Preset |"))
except StopIteration as exc:
raise error_type("documentation has no Community Presets table") from exc
rows = []
for line in lines[start + 2:]:
if not line.startswith("|"):
break
rows.append(line.strip())
return rows


def existing_documentation_row(rows: list[str], entry: dict) -> str:
name = entry.get("name")
repository = entry.get("repository")
if not isinstance(name, str) or not isinstance(repository, str):
raise Blocked("original catalog entry lacks documentation row identity")
matches = []
for row in rows:
cells = markdown_table_cells(row)
if len(cells) < 3 or cells[1] != name:
continue
url_cell = cells[-2] if cells[-1] == "" else cells[-1]
link = re.fullmatch(r"\[[^\]]*\]\(([^)]+)\)", url_cell)
if link and link[1].rstrip("/") == repository.rstrip("/"):
matches.append(row)
if len(matches) != 1:
raise Blocked(
"original documentation must contain exactly one row matching the "
f"catalog name and repository for {name!r}; found {len(matches)}"
)
return matches[0]


def generated(args: argparse.Namespace) -> None:
snapshot = read_json(args.snapshot, "verifier snapshot", Blocked)
expected = snapshot.get("expected")
Expand Down Expand Up @@ -469,46 +377,13 @@ def generated(args: argparse.Namespace) -> None:
raise GeneratedError("catalog entry updated_at does not match the expected UTC date")
if catalog.get("updated_at") != expected_timestamp:
raise GeneratedError("catalog top-level updated_at does not match the expected UTC date")
documentation = snapshot.get("documentation")
if not isinstance(documentation, dict):
raise Blocked("verifier snapshot lacks original documentation state")
expected_row_count = documentation.get("expected_row_count")
previous_row = documentation.get("previous_row")
previous_row_count = documentation.get("previous_row_count")
if (
not isinstance(expected_row_count, int)
or isinstance(expected_row_count, bool)
or expected_row_count < 0
or previous_row is not None and not isinstance(previous_row, str)
or not isinstance(previous_row_count, int)
or isinstance(previous_row_count, bool)
or previous_row_count < 0
):
raise Blocked("verifier snapshot has invalid original documentation state")
rows = documentation_rows(
read_text(args.docs, "generated documentation", GeneratedError),
GeneratedError,
)
names = [markdown_table_cells(row)[1] for row in rows]
if names != sorted(names, key=str.casefold):
raise GeneratedError("documentation preset names are not in alphabetical order")
expected_row = documentation_row(expected)
expected_generated_count = expected_row_count + (
0 if previous_row == expected_row else 1
)
if rows.count(expected_row) != expected_generated_count:
raise GeneratedError(f"documentation row does not match validated values: {expected_row}")
if previous_row is not None and previous_row != expected_row:
expected_previous_count = max(0, previous_row_count - 1)
if rows.count(previous_row) != expected_previous_count:
raise GeneratedError("previous documentation row was not replaced")
print("PASSED: generated catalog and documentation match validated submission")
print("PASSED: generated catalog matches validated submission")


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("phase", choices=("submission", "generated"))
for name in ("issue", "archive", "readme", "catalog", "docs", "snapshot"):
for name in ("issue", "archive", "readme", "catalog", "snapshot"):
parser.add_argument(f"--{name}", required=True, type=Path)
args = parser.parse_args()
try:
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/add-community-preset.lock.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading