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
9 changes: 9 additions & 0 deletions .github/PROJECT_SYNC.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@ or deletes source Issues/PRs.
reject stalled cursors, and serialize runs. Apply mode prints the plan first;
on failure it reports confirmed, outcome-unknown and unattempted mutation counts,
with affected item/field, so partial writes can be reconciled.
- Full scans log phase/page and candidate progress to the Actions log. Stable
release membership is determined with one `git tag --contains` graph walk per
distinct merge commit instead of one `git merge-base` process per commit/tag
pair; missing fetched tags fail closed.
- Local microbenchmark against the full checkout: 237 version tags and 20 sampled
tag commits (version order used as a proxy for publication order). Pairwise
`merge-base` checks ran 2,110 processes in 31.67 s; `tag --contains` ran 20 in
0.35 s (90x on this sample). This measures Git ancestry only, not GraphQL or
full-workflow wall time.
- Privileged jobs run trusted default-branch code only, use full Git history/tags,
and never execute PR code. PR tests use no Project secret.

Expand Down
124 changes: 109 additions & 15 deletions scripts/sync_github_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import os
import re
import subprocess
import sys
import urllib.error
import urllib.request
from functools import cache
Expand All @@ -22,13 +23,14 @@
DELIVERY_OPTIONS = ("未关联实现", "尚未合入", "已合入待发布", "已发布")


def connection(query, path, *, initial=None, **variables):
def connection(query, path, *, initial=None, progress=None, **variables):
"""Read every page and fail if the cursor stalls.

Args:
query: GraphQL operation accepting a cursor variable.
path: Keys leading to a connection in the response.
initial: Optional first page already returned in a parent query.
progress: Optional label for flushed progress output.
**variables: Other operation variables.

Returns:
Expand All @@ -37,7 +39,7 @@ def connection(query, path, *, initial=None, **variables):
Raises:
RuntimeError: A cursor does not advance or the connection is inaccessible.
"""
nodes, cursor, seen = [], None, set()
nodes, cursor, seen, pages = [], None, set(), 0
while True:
if initial is not None:
data, initial = initial, None
Expand All @@ -48,6 +50,13 @@ def connection(query, path, *, initial=None, **variables):
if not isinstance(data, dict):
raise RuntimeError("GitHub connection is inaccessible")
nodes.extend(node for node in data["nodes"] if node)
pages += 1
if progress:
print(
f"Project sync: {progress}, page {pages}, {len(nodes)} items",
file=sys.stderr,
flush=True,
)
page = data["pageInfo"]
if not page["hasNextPage"]:
return nodes
Expand Down Expand Up @@ -171,6 +180,53 @@ def ancestor(commit, ref):
return result.returncode == 0


@cache
def tag_names():
"""Read fetched tag names once so missing release tags fail closed."""
result = subprocess.run(
["git", "tag", "--list"],
cwd=ROOT,
capture_output=True,
text=True,
timeout=30,
check=False,
)
if result.returncode:
raise RuntimeError("Cannot list fetched release tags")
return frozenset(result.stdout.splitlines())


@cache
def tags_containing(commit):
"""Return tags containing a full commit using one Git graph walk.

Args:
commit: Full implementation commit OID.

Returns:
Tag names whose peeled commit descends from the implementation commit.

Raises:
ValueError: Commit OID is invalid.
RuntimeError: The repository cannot answer the containment query.
"""
if not re.fullmatch(r"[0-9a-f]{40}", commit):
raise ValueError("Invalid implementation commit")
result = subprocess.run(
["git", "tag", "--contains", commit],
cwd=ROOT,
capture_output=True,
text=True,
timeout=30,
check=False,
)
if result.returncode:
raise RuntimeError(
"Cannot verify release tag ancestry; fetch full history and tags"
)
return frozenset(result.stdout.splitlines())


def delivery(content, current, linked, releases, mainline):
"""Calculate implementation links and the earliest proven stable release.

Expand All @@ -192,25 +248,28 @@ def delivery(content, current, linked, releases, mainline):
all_integrated = (
bool(merged) and len(commits) == len(merged) and integrated == commits
)
published = None
for release in sorted(
stable_releases = sorted(
(
r
for r in releases
if not r["isDraft"] and not r["isPrerelease"] and r.get("publishedAt")
),
key=lambda r: r["publishedAt"],
):
if (
all_merged
and all_integrated
and all(
ancestor(commit, f"refs/tags/{release['tagName']}")
for commit in integrated
)
published = None
if all_merged and all_integrated and stable_releases:
release_names = {r["tagName"] for r in stable_releases}
missing = release_names - tag_names()
if missing:
raise RuntimeError(
"Stable release tags are missing; fetch full history and tags"
)
):
published = release
break
common_tags = release_names.copy()
for commit in integrated:
common_tags.intersection_update(tags_containing(commit))
published = next(
(r for r in stable_releases if r["tagName"] in common_tags), None
)
progress = (
"已发布"
if published
Expand Down Expand Up @@ -430,6 +489,17 @@ def read_subject(repository, number):
initial=content[field],
id=content["id"],
)
for item in content["projectItems"]:
item["fieldValues"] = connection(
"""query($id:ID!,$cursor:String){node(id:$id){... on ProjectV2Item{
fieldValues(first:100,after:$cursor){nodes{
... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{name}}}
... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{name}}}
}pageInfo{hasNextPage endCursor}}}}} """.strip(),
("node", "fieldValues"),
initial=item["fieldValues"],
id=item["id"],
)
return content


Expand Down Expand Up @@ -580,6 +650,7 @@ def reconcile(
... on ProjectV2SingleSelectField{id name options{id name}}
}pageInfo{hasNextPage endCursor}}}}}""",
("node", "fields"),
progress="Project fields",
project=project,
)
fields = {}
Expand Down Expand Up @@ -632,6 +703,7 @@ def reconcile(
}pageInfo{hasNextPage endCursor}}
}pageInfo{hasNextPage endCursor}}}}}""",
("node", "items"),
progress="Project items",
project=project,
)
tracked = {
Expand All @@ -648,6 +720,7 @@ def reconcile(
labels(first:100){nodes{name}pageInfo{hasNextPage endCursor}}}
pageInfo{hasNextPage endCursor}}}}""",
("repository", "issues"),
progress="Repository issues",
states=["OPEN", "CLOSED"],
**variables,
)
Expand All @@ -659,6 +732,7 @@ def reconcile(
pageInfo{hasNextPage endCursor}}
}pageInfo{hasNextPage endCursor}}}}""",
("repository", "pullRequests"),
progress="Repository PRs",
states=["OPEN", "CLOSED", "MERGED"],
**variables,
)
Expand Down Expand Up @@ -714,6 +788,7 @@ def reconcile(
releases(first:100,after:$cursor){nodes{tagName url publishedAt isDraft isPrerelease}
pageInfo{hasNextPage endCursor}}}}""",
("repository", "releases"),
progress="Repository releases",
**variables,
)
mainline = subprocess.run(
Expand All @@ -725,7 +800,19 @@ def reconcile(
check=True,
).stdout.strip()
plan = []
for content in candidates:
if subject is None:
print(
f"Project sync: calculating delivery for {len(candidates)} candidates",
file=sys.stderr,
flush=True,
)
for index, content in enumerate(candidates, 1):
if subject is None and index % 50 == 0:
print(
f"Project sync: calculated {index}/{len(candidates)} candidates",
file=sys.stderr,
flush=True,
)
item = tracked.get(content["id"])
if item and item["isArchived"]:
continue
Expand Down Expand Up @@ -903,6 +990,13 @@ def main(argv=None):
not isinstance(v, str) or not v.strip() for v in status_names.values()
) or len(set(status_names.values())) != len(STATUS_OPTIONS):
raise ValueError("Status names must be nonempty and distinct")
print(
"Project sync: starting full reconciliation"
if subject is None
else f"Project sync: starting bounded sync for item #{subject}",
file=sys.stderr,
flush=True,
)
try:
plan = reconcile(
project,
Expand Down
Loading
Loading