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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ python scripts/sync_all_siblings.py update --pr --setup-venvs
`sync-shared-<sha>` branch, push it, and open a PR with `gh`. The PR lists the files,
links the shared diff and reports the local checks. Older sync PRs still open are
flagged as superseded, not closed.
6. With `--auto-merge` (off by default): `gh pr merge --auto --squash` on the new PR, so it
merges itself once CI passes. Skipped, with the reason in the table, where the repo has
"Allow auto-merge" off, or where the default branch requires no status checks (branch
protection or a ruleset): there GitHub's auto-merge merges at once, before CI has run. As of
2026-11 every sibling is in both cases, so it takes a ruleset requiring the CI jobs, plus the
repo setting, before it does anything.

`--commit` stops after a local commit on the default branch; `--push` pushes that commit
straight to it instead of opening a PR. `--no-test` skips the local checks (CI still runs
Expand Down
66 changes: 65 additions & 1 deletion scripts/sync_all_siblings.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,7 @@ def release_sibling(
setup_venvs: bool,
keep_failed: bool,
shared_main: str | None,
auto_merge: bool = False,
) -> StatusRow:
"""Refresh, sync, check, commit and (per `mode`) push or open a PR for one sibling."""
info = read_sibling_info(sibling)
Expand Down Expand Up @@ -574,7 +575,10 @@ def row(status: str, ok: bool, commit: str | None = None) -> StatusRow:
)
if proc.returncode != 0:
return row(f"PR failed ({(proc.stderr or proc.stdout).strip()}); branch {branch} pushed", False, new)
status = f"PR {proc.stdout.strip()}"
url = proc.stdout.strip()
status = f"PR {url}"
if auto_merge:
status += "; " + enable_auto_merge(sibling, url, default)
# Older sync PRs still open are now stale: flag them rather than close them unasked.
others = _gh(
["pr", "list", "--state", "open", "--json", "headRefName,url", "-q"]
Expand All @@ -594,6 +598,54 @@ def row(status: str, ok: bool, commit: str | None = None) -> StatusRow:
_git(sibling, "switch", "--quiet", default) # ready for the next run


def required_checks(sibling: Path, branch: str) -> list[str]:
"""The status checks `branch` requires, from classic branch protection and from rulesets.

Raises SiblingError when GitHub can't say (a 404 from branch protection only means "not
protected"). gh fills in {owner}/{repo} from the sibling's origin remote.
"""
checks: list[str] = []
protection = _gh(
["api", f"repos/{{owner}}/{{repo}}/branches/{branch}/protection/required_status_checks"]
+ ["--jq", ".contexts[]"],
cwd=sibling,
)
if protection.returncode == 0:
checks += protection.stdout.splitlines()
elif "HTTP 404" not in protection.stderr:
raise SiblingError(f"branch protection: {(protection.stderr or protection.stdout).strip()}")
rules = _gh(
["api", f"repos/{{owner}}/{{repo}}/rules/branches/{branch}", "--jq"]
+ ['.[] | select(.type == "required_status_checks") | .parameters.required_status_checks[].context'],
cwd=sibling,
)
if rules.returncode != 0:
raise SiblingError(f"rulesets: {(rules.stderr or rules.stdout).strip()}")
checks += rules.stdout.splitlines()
return list(dict.fromkeys(c.strip() for c in checks if c.strip()))


def enable_auto_merge(sibling: Path, pr_url: str, base: str) -> str:
"""Turn on squash auto-merge for a sync PR, or say why not: a clause for the status row.

Never a failure: the PR is open either way, and a person can merge it. Without required
checks GitHub's auto-merge merges at once, before CI has run, so that case is skipped.
"""
allowed = _gh(["api", "repos/{owner}/{repo}", "--jq", ".allow_auto_merge"], cwd=sibling)
if allowed.returncode == 0 and allowed.stdout.strip() == "false":
return "auto-merge skipped: turned off for the repo (Settings > General > Allow auto-merge)"
try:
checks = required_checks(sibling, base)
except SiblingError as exc:
return f"auto-merge skipped: couldn't read {base}'s required checks ({exc})"
if not checks:
return f"auto-merge skipped: {base} requires no status checks, so it would merge before CI ran"
proc = _gh(["pr", "merge", pr_url, "--auto", "--squash"], cwd=sibling)
if proc.returncode != 0:
return f"auto-merge failed ({(proc.stderr or proc.stdout).strip()})"
return f"auto-merge on (squash, once {', '.join(checks)} pass)"


def run_update(
parent_dir: Path,
*,
Expand All @@ -604,6 +656,7 @@ def run_update(
setup_venvs: bool = False,
keep_failed: bool = False,
only: str | None = None,
auto_merge: bool = False,
) -> int:
siblings = select_siblings(discover_siblings(parent_dir), only)
if not siblings:
Expand All @@ -626,6 +679,7 @@ def run_update(
setup_venvs=setup_venvs,
keep_failed=keep_failed,
shared_main=shared_main,
auto_merge=auto_merge,
)
for sibling in siblings
]
Expand Down Expand Up @@ -810,6 +864,13 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
default=False,
help="with --pr/--commit/--push: leave a sync whose checks failed in the tree (default: undo it)",
)
update_parser.add_argument(
"--auto-merge",
action="store_true",
default=False,
help="with --pr: turn on squash auto-merge for each new PR; skipped (and said why) where the repo "
"has auto-merge off or its default branch requires no checks, which would merge before CI ran",
)

args = parser.parse_args(list(argv) if argv is not None else None)
if args.command is None:
Expand All @@ -821,6 +882,8 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
update_parser.error("--dry-run doesn't go with --pr/--commit/--push; use it alone to preview")
if args.mode is None and (args.no_test or args.keep_failed):
update_parser.error("--no-test and --keep-failed only go with --pr/--commit/--push")
if args.auto_merge and args.mode != "pr":
update_parser.error("--auto-merge only goes with --pr")
if args.mode is not None and args.test and args.no_test:
update_parser.error("--test and --no-test contradict each other")
return args
Expand All @@ -843,6 +906,7 @@ def main(argv: Sequence[str] | None = None) -> int:
setup_venvs=bool(args.setup_venvs),
keep_failed=bool(args.keep_failed),
only=only,
auto_merge=bool(args.auto_merge),
)
return run_status(parent_dir, latest=bool(args.latest), only=only)

Expand Down
67 changes: 67 additions & 0 deletions tests/test_sync_all_siblings.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,13 @@ def __init__(self) -> None:
self.created: list[list[str]] = []
self.repos: list[str] = []
self.logged_in = True
# For --auto-merge, per sibling: the repo setting, the checks branch protection and rulesets
# require (None: the API call fails), and what `gh pr merge` says (None: it works).
self.auto_merge_allowed: dict[str, bool] = {}
self.protected_checks: dict[str, list[str] | None] = {}
self.ruleset_checks: dict[str, list[str]] = {}
self.merge_error: dict[str, str] = {}
self.merged: list[list[str]] = []

def __call__(self, args: Sequence[str], *, cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
a = list(args)
Expand All @@ -347,6 +354,24 @@ def __call__(self, args: Sequence[str], *, cwd: Path | None = None) -> subproces
u for (n, b), u in self.open.items() if n == cwd.name and b.startswith("sync-shared-") and b != current
]
return subprocess.CompletedProcess(a, 0, stdout="".join(u + "\n" for u in urls), stderr="")
if a[:2] == ["api", "repos/{owner}/{repo}"]:
return subprocess.CompletedProcess(
a, 0, stdout=f"{str(self.auto_merge_allowed.get(cwd.name, True)).lower()}\n", stderr=""
)
if a[0] == "api" and a[1].endswith("/protection/required_status_checks"):
if cwd.name not in self.protected_checks:
return subprocess.CompletedProcess(a, 1, stdout="", stderr="gh: Branch not protected (HTTP 404)")
checks = self.protected_checks[cwd.name]
if checks is None:
return subprocess.CompletedProcess(a, 1, stdout="", stderr="gh: Resource not accessible (HTTP 403)")
return subprocess.CompletedProcess(a, 0, stdout="".join(c + "\n" for c in checks), stderr="")
if a[0] == "api" and "/rules/branches/" in a[1]:
checks = self.ruleset_checks.get(cwd.name, [])
return subprocess.CompletedProcess(a, 0, stdout="".join(c + "\n" for c in checks), stderr="")
if a[:2] == ["pr", "merge"]:
self.merged.append(a)
error = self.merge_error.get(cwd.name)
return subprocess.CompletedProcess(a, 1 if error else 0, stdout="", stderr=error or "")
if a[:2] == ["pr", "create"]:
self.created.append(a)
url = f"https://github.example/{cwd.name}/pull/{len(self.created)}"
Expand Down Expand Up @@ -554,3 +579,45 @@ def test_select_siblings_accepts_short_and_full_names(tmp_path: Path):
"mcp-server-gamma",
]
assert mod.select_siblings(paths, None) == paths


def test_update_pr_auto_merge_only_where_checks_gate_it(tmp_path: Path, portfolio, capsys):
mod, _, gh = portfolio
names = ["alpha", "beta", "gamma", "delta", "eps", "zeta"]
for name in names:
make_git_sibling(tmp_path, f"mcp-server-{name}", f"{name}_mcp")
gh.protected_checks["mcp-server-alpha"] = ["test (3.11)", "alpine"] # classic protection: merges
gh.ruleset_checks["mcp-server-beta"] = ["shared-drift"] # a ruleset: merges too
gh.auto_merge_allowed["mcp-server-gamma"] = False # repo setting off
# delta: neither protection nor rulesets, so auto-merge would merge before CI
gh.protected_checks["mcp-server-eps"] = None # can't read protection
gh.protected_checks["mcp-server-zeta"] = ["test"]
gh.merge_error["mcp-server-zeta"] = "Pull request is in clean status"

assert mod.main(["update", "--parent-dir", str(tmp_path / "src"), "--pr", "--auto-merge"]) == 0 # never fails
table = capsys.readouterr().out
table = table[table.index("SIBLING") :]
rows = {line.split()[0]: line for line in table.splitlines()[2:]}

assert "auto-merge on (squash, once test (3.11), alpine pass)" in rows["mcp-server-alpha"]
assert "auto-merge on (squash, once shared-drift pass)" in rows["mcp-server-beta"]
assert "auto-merge skipped: turned off for the repo" in rows["mcp-server-gamma"]
assert "auto-merge skipped: main requires no status checks" in rows["mcp-server-delta"]
assert "auto-merge skipped: couldn't read main's required checks (branch protection: " in rows["mcp-server-eps"]
assert "auto-merge failed (Pull request is in clean status)" in rows["mcp-server-zeta"]
assert all(row.split()[3] == "PR" for row in rows.values()) # every PR opened regardless
merged = sorted(m[2].rsplit("/", 3)[1] for m in gh.merged)
assert merged == ["mcp-server-alpha", "mcp-server-beta", "mcp-server-zeta"]
assert all(m[3:] == ["--auto", "--squash"] for m in gh.merged)


def test_auto_merge_is_off_by_default_and_only_with_pr(tmp_path: Path, portfolio, capsys):
mod, _, gh = portfolio
make_git_sibling(tmp_path, "mcp-server-alpha", "alpha_mcp")
gh.protected_checks["mcp-server-alpha"] = ["test"]
assert mod.main(["update", "--parent-dir", str(tmp_path / "src"), "--pr"]) == 0
assert gh.merged == [] and "auto-merge" not in capsys.readouterr().out
for mode in ([], ["--commit"], ["--push"]):
with pytest.raises(SystemExit):
mod.main(["update", "--parent-dir", str(tmp_path / "src"), *mode, "--auto-merge"])
assert "--auto-merge only goes with --pr" in capsys.readouterr().err
Loading