diff --git a/.github/scripts/propose_release_line.py b/.github/scripts/propose_release_line.py new file mode 100644 index 0000000..ebff66f --- /dev/null +++ b/.github/scripts/propose_release_line.py @@ -0,0 +1,280 @@ +# SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: GPL-3.0-or-later +"""Propose a fixed G2 snapshot in a draft configuration PR, never on master.""" + +import copy +import difflib +import json +import os +import re +import subprocess +from urllib.parse import quote, urlencode + +import yaml + +from release_line_checks import ( + MAX_TRAVERSAL_DEPTH, SHA_RE, api, content, g2_members, head_version, release_lines, + validate_line, +) + + +MARKER = "", 1)[0]) + if (release.get("group") != "G2" or release.get("release_line", "master") != source_line + or release.get("base_branch") != default + or [m["repo"] for m in release["members"]] != [r for _, r in members]): + raise RuntimeError(f"{branch} 的发布线或成员记录异常") + for member in release["members"]: + version = member.get("version", release["version"]) + safe = re.sub(r"[^A-Za-z0-9._-]+", "-", version).strip("-") + if member["base"] != source_branch or not any( + p.get("merged_at") and p["head"]["ref"] == f"automation/update-changelog/{safe}" + and p["created_at"] >= release["started_at"] and p["head"]["repo"] + and p["head"]["repo"]["full_name"] == member["repo"] + and p.get("merge_commit_sha") + and head_version(api, member["repo"], p["merge_commit_sha"]) == version + for p in member_prs[member["repo"]]): + raise RuntimeError(f"{branch} 的成员发布尚未完成: {member['repo']}") + + +def snapshot(api, members, branch, bases=None, version=None): + fixed, versions = {}, {} + if bases is not None and set(bases) != {member for member, _ in members}: + raise RuntimeError("草稿 bases 必须恰好包含 G2 的 17 个成员 ID") + for member, repo in members: + sha = bases[member] if bases is not None else ref(api, repo, branch) + if sha is None and bases is None: + raise RuntimeError(f"{repo} 源分支不存在: {branch}") + if not isinstance(sha, str) or not SHA_RE.fullmatch(sha): + raise RuntimeError(f"{repo} 缺少完整的基准 SHA") + commit = api(f"repos/{repo}/git/commits/{sha}") + if commit.get("sha", "").lower() != sha.lower(): + raise RuntimeError(f"{repo} 基准 commit 不存在: {sha}") + fixed[member] = commit["sha"] + versions[member] = head_version(api, repo, fixed[member]).split(":", 1)[-1] + if len(set(versions.values())) != 1: + raise RuntimeError(f"17 个基准 changelog 去 epoch 后版本不一致: {versions}") + common = next(iter(versions.values())) + if version is not None and version != common: + raise RuntimeError(f"草稿初始版本 {version} 与固定基准共同版本 {common} 不符") + return fixed, common + + +def rewrite(text, line, branch, bases, version): + before = yaml.safe_load(text) + expected = copy.deepcopy(before) + expected["release_lines"][line] = {"member_branch": branch, "bases": bases} + expected["groups"]["G2"]["versions"][line] = version + root = {k.value: v for k, v in yaml.compose(text).value} + groups = {k.value: v for k, v in root["groups"].value} + g2 = {k.value: v for k, v in groups["G2"].value} + line_key = line if yaml.safe_load(line) == line else json.dumps(line) + additions = [ + (root["release_lines"].end_mark.line, + [f" {line_key}:", f" member_branch: {json.dumps(branch)}", " bases:"] + + [f" {member}: {json.dumps(sha)}" for member, sha in bases.items()]), + (g2["versions"].end_mark.line, [f" {line_key}: {json.dumps(version)}"]), + ] + lines = text.splitlines() + for position, new_lines in sorted(additions, reverse=True): + # YAML end_mark skips comments belonging to the following section. + indent = len(new_lines[0]) - len(new_lines[0].lstrip()) + while position and (not lines[position - 1].strip() or ( + lines[position - 1].lstrip().startswith("#") + and len(lines[position - 1]) - len(lines[position - 1].lstrip()) < indent)): + position -= 1 + lines[position:position] = new_lines + updated = "\n".join(lines) + "\n" + if yaml.safe_load(updated) != expected: + raise RuntimeError("无法在保留 G1 与既有配置的前提下增加发布线") + return updated + + +def propose(api, repo, line, target, source_branch="master", dry_run=True): + validate_line(line, target) + if line == "master": + raise RuntimeError("Propose 只新增 develop 发布线") + if (not isinstance(source_branch, str) or subprocess.run( + ["git", "check-ref-format", "--branch", source_branch], capture_output=True).returncode): + raise RuntimeError(f"非法源成员分支: {source_branch}") + info = api(f"repos/{repo}") + default = info["default_branch"] + base_sha = ref(api, repo, default) + text = content(api, repo, "groups.yaml", base_sha) + cfg = yaml.safe_load(text) + lines = release_lines(cfg) + members = g2_members(cfg, repo.split("/")[0]) + if line in lines: + if lines[line]["member_branch"] != target: + raise RuntimeError("已合并发布线不能覆盖或改投成员分支") + print(f"{line} 配置已合并;使用 Prepare,不修改既有线") + return None + if target in {value["member_branch"] for value in lines.values()}: + raise RuntimeError(f"成员分支 {target} 已映射到另一发布线") + branch = f"automation/propose-release-line/{line}" + if subprocess.run(["git", "check-ref-format", "--branch", branch], + capture_output=True).returncode: + raise RuntimeError("发布线 ID 生成了无效的提案分支") + proposals = prs(api, repo, branch) + if len([p for p in proposals if p["state"] == "open"]) > 1: + raise RuntimeError("提案分支有重复的开放 PR,需人工核实") + pr = proposals[0] if proposals else None + identity = {"release_line": line, "target_branch": target, "source_branch": source_branch} + if pr and (pr.get("merged_at") or pr["state"] != "open" or not pr.get("draft") + or pr["base"]["ref"] != default or not pr["head"]["repo"] + or pr["head"]["repo"]["full_name"] != repo): + raise RuntimeError("只更新原开放草稿 PR;已关闭、已审核或已合并提案请人工核实") + previous = ref(api, repo, branch) + bases = version = None + if previous: + if pr and pr["head"]["sha"] != previous: + raise RuntimeError("草稿 PR 与提案分支 SHA 不一致,重跑前请核实") + delta = api(f"repos/{repo}/compare/{base_sha}...{previous}") + original = yaml.safe_load(content(api, repo, "groups.yaml", + delta["merge_base_commit"]["sha"])) + candidate = yaml.safe_load(content(api, repo, "groups.yaml", previous)) + release_lines(candidate) + value = candidate["release_lines"].get(line, {}) + bases, version = value.get("bases"), candidate["groups"]["G2"]["versions"].get(line) + expected = copy.deepcopy(original) + expected["release_lines"][line] = value + expected["groups"]["G2"]["versions"][line] = version + if (candidate != expected or value.get("member_branch") != target + or not isinstance(bases, dict) + or [(f["filename"], f["status"]) for f in delta["files"]] + != [("groups.yaml", "modified")]): + raise RuntimeError("原提案只能增加本线配置与初始版本,不能覆盖其他已合并配置") + commit = api(f"repos/{repo}/git/commits/{previous}") + for _ in range(MAX_TRAVERSAL_DEPTH + 1): + if MARKER in commit["message"]: + saved = json.loads(commit["message"].split(MARKER, 1)[1].split("\n-->", 1)[0]) + if "source_line" in saved and "source_branch" not in saved: + saved["source_branch"] = lines.get(saved.pop("source_line"), {}).get("member_branch") + if saved != identity: + raise RuntimeError("原草稿提案的源分支或目标输入不同") + break + if not commit["parents"]: + raise RuntimeError("提案分支没有可确认的来源标记") + commit = api(f"repos/{repo}/git/commits/{commit['parents'][0]['sha']}") + else: + raise RuntimeError("提案来源记录过深,需人工核实") + source_idle(api, repo, cfg, source_branch, default, base_sha) + bases, version = snapshot(api, members, source_branch, bases, version) + updated = rewrite(text, line, target, bases, version) + output = (f"G2 {line} -> {target},源成员分支 {source_branch},初始版本 {version}\n\n" + + "\n".join(f"- {member} ({member_repo}): {bases[member]}" + for member, member_repo in members) + "\n\n" + + "".join(difflib.unified_diff(text.splitlines(True), updated.splitlines(True), + fromfile="groups.yaml", tofile="groups.yaml"))) + print(output) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary: + summary.write(f"```\n{output}\n```\n") + if dry_run: + return {"bases": bases, "version": version, "config": updated} + if ref(api, repo, default) != base_sha or ref(api, repo, branch) != previous: + raise RuntimeError("配置或草稿在预检期间变化;请重跑,不覆盖新提交") + source_idle(api, repo, cfg, source_branch, default, base_sha) + if previous is None or content(api, repo, "groups.yaml", previous) != updated: + tree = api(f"repos/{repo}/git/commits/{base_sha}")["tree"]["sha"] + tree = api(f"repos/{repo}/git/trees", {"base_tree": tree, "tree": [ + {"path": "groups.yaml", "mode": "100644", "type": "blob", "content": updated}]}) + parents = [previous, base_sha] if previous else [base_sha] + commit = api(f"repos/{repo}/git/commits", {"tree": tree["sha"], "parents": parents, + "message": f"chore: propose G2 {line}\n\n{MARKER}{json.dumps(identity)}\n-->"}) + if previous: + api(f"repos/{repo}/git/refs/heads/{quote(branch, safe='/')}", + {"sha": commit["sha"], "force": False}, method="PATCH") + else: + try: + api(f"repos/{repo}/git/refs", {"ref": f"refs/heads/{branch}", "sha": commit["sha"]}) + except RuntimeError: + if ref(api, repo, branch) != commit["sha"]: + raise RuntimeError("提案分支并发创建或 API 失败;保留现状并重跑") + body = (f"{MARKER}{json.dumps(identity)}\n-->\n\n源成员分支:`{source_branch}`。\n\n" + "固定下列 SHA 作为新线分支快照。可在本草稿中修改历史 SHA 及初始版本," + "合并检查须重新验证所有基准。不自动创建成员分支或合并本 PR。\n\n" + + "\n".join(f"- `{member}`: [{bases[member]}](https://github.com/{member_repo}/commit/{bases[member]})" + for member, member_repo in members)) + details = {"title": f"chore: propose G2 {line} ({version})", "body": body} + if pr: + if any(pr.get(key) != value for key, value in details.items()): + pr = api(f"repos/{repo}/pulls/{pr['number']}", details, method="PATCH") + else: + try: + pr = api(f"repos/{repo}/pulls", {**details, "head": branch, "base": default, "draft": True}) + except RuntimeError: + existing = prs(api, repo, branch, state="open") + head = ref(api, repo, branch) + if (len(existing) != 1 or not existing[0].get("draft") or existing[0]["base"]["ref"] != default + or not existing[0]["head"]["repo"] or existing[0]["head"]["repo"]["full_name"] != repo + or existing[0]["head"]["ref"] != branch or existing[0]["head"]["sha"] != head): + raise + pr = existing[0] + print(f"配置草稿 PR: {pr['html_url']}") + return pr + + +if __name__ == "__main__": + if "SOURCE_BRANCH" not in os.environ and "SOURCE_LINE" in os.environ: + raise RuntimeError("来源参数已改为 source_branch;请重新从表单发起,不要重跑旧参数的运行") + propose(api, os.environ["GITHUB_REPOSITORY"], os.environ["RELEASE_LINE"], + os.environ["TARGET_BRANCH"], os.environ.get("SOURCE_BRANCH", "master"), + os.environ.get("DRY_RUN", "true").lower() == "true") diff --git a/.github/scripts/release_line_checks.py b/.github/scripts/release_line_checks.py new file mode 100644 index 0000000..3df58e6 --- /dev/null +++ b/.github/scripts/release_line_checks.py @@ -0,0 +1,345 @@ +# SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: GPL-3.0-or-later +"""Read-only G2 release-line checks shared by the coordinator and Prepare.""" + +import base64 +import fnmatch +import json +import os +import re +import subprocess +import tempfile +from urllib.parse import quote, urlencode + +import yaml + + +GUARD_CONTEXT = "group-version-guard" +WORKFLOW_FILES = ("call-update-changelog.yml", "call-verify-group-version.yml") +G2_MEMBER_COUNT = 17 +MAX_TRAVERSAL_DEPTH = 100 +RELEASE_INPUTS = { + "version": "string", "name": "string", "email": "string", + "base_branch": "string", "distribution": "string", "create_pr": "boolean", +} +SHA_RE = re.compile(r"[0-9a-fA-F]{40}") +LINE_RE = re.compile(r"[A-Za-z0-9._-]+") + + +class ReadinessError(RuntimeError): + def __init__(self, state, message): + self.state = state + super().__init__(f"{state}: {message}") + + +def api(path, data=None, method=None, missing=False, paginate=False): + """Same gh API adapter/signature as sync-baseline; errors fail closed.""" + args = ["gh", "api", path] + if method: + args += ["--method", method] + if data is not None: + args += ["--input", "-"] + if paginate: + args += ["--paginate", "--slurp"] + # Paths are passed as one argv item with shell=False; no shell interpolation occurs. + result = subprocess.run(args, input=json.dumps(data) if data is not None else None, # nosemgrep + capture_output=True, text=True) + if result.returncode: + if missing and "(HTTP 404)" in result.stderr: + return None + raise RuntimeError(f"GitHub API 失败: {path}: {result.stderr.strip()}") + value = json.loads(result.stdout) if result.stdout.strip() else None + if path == "graphql" and value.get("errors"): + raise RuntimeError(f"GitHub GraphQL 失败: {value['errors']}") + return [item for page in value for item in page] if paginate else value + + +def content(api, repo, path, ref, missing=False): + value = api(f"repos/{repo}/contents/{quote(path, safe='/')}?" + f"{urlencode({'ref': ref})}", missing=missing) + if value is None and missing: + return None + if not isinstance(value, dict) or value.get("encoding") != "base64": + raise RuntimeError(f"无法读取文件: {repo}@{ref}:{path}") + return base64.b64decode(value["content"]).decode("utf-8") + + +def validate_line(line, branch): + if not isinstance(line, str) or not LINE_RE.fullmatch(line): + raise RuntimeError(f"非法发布线 ID: {line}") + if not isinstance(branch, str) or subprocess.run( + ["git", "check-ref-format", "--branch", branch], capture_output=True).returncode: + raise RuntimeError(f"非法成员分支: {branch}") + if line == "master": + if branch != "master": + raise RuntimeError("master 发布线必须映射 master") + elif not branch.startswith("develop/"): + raise RuntimeError("新发布线的成员分支必须为 develop/") + + +def release_lines(cfg): + lines = cfg.get("release_lines") + versions = cfg.get("groups", {}).get("G2", {}).get("versions") + if not isinstance(lines, dict) or not isinstance(versions, dict) or "master" not in lines: + raise RuntimeError("请先合并 G2 release_lines / versions 配置迁移") + branches = [] + for line, value in lines.items(): + if not isinstance(value, dict): + raise RuntimeError(f"发布线 {line} 配置无效") + validate_line(line, value.get("member_branch")) + branches.append(value["member_branch"]) + if line not in versions or not isinstance(versions[line], str): + raise RuntimeError(f"发布线 {line} 缺少 G2 初始版本") + if len(branches) != len(set(branches)) or set(lines) != set(versions): + raise RuntimeError("发布线分支映射必须唯一,且与 G2 versions 一一对应") + return lines + + +def g2_members(cfg, owner): + members = cfg.get("groups", {}).get("G2", {}).get("members") + if (not isinstance(members, list) or len(members) != G2_MEMBER_COUNT + or any(not isinstance(m, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", m) + for m in members) or len(set(members)) != G2_MEMBER_COUNT): + raise RuntimeError("只支持 groups.G2.members 中现有的 17 个唯一成员") + overrides = cfg.get("repo_overrides", {}) + result = [] + for member in members: + name = overrides.get(member, member) + if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", name): + raise RuntimeError(f"成员 {member} 的 repo_overrides 无效") + result.append((member, f"{owner}/{name}")) + if len({repo for _, repo in result}) != G2_MEMBER_COUNT: + raise RuntimeError("G2 仓库映射重复") + return result + + +def head_version(api, repo, sha): + text = content(api, repo, "debian/changelog", sha) + with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8") as changelog: + changelog.write(text) + changelog.flush() + result = subprocess.run(["dpkg-parsechangelog", "-l", changelog.name, "-S", "Version"], + capture_output=True, text=True) + version = result.stdout.strip() + if result.returncode or not version or subprocess.run( + ["dpkg", "--validate-version", version], capture_output=True).returncode: + raise RuntimeError(f"无法解析 {repo}@{sha} 的 changelog: {result.stderr.strip()}") + return version + + +def branch_info(api, repo, branch, missing=False): + return api(f"repos/{repo}/branches/{quote(branch, safe='')}", missing=missing) + + +def _event(workflow, name): + events = workflow.get("on", workflow.get(True)) + if isinstance(events, dict) and name in events: + return events[name] or {} + if events == name or isinstance(events, list) and name in events: + return {} + return None + + +def _matches(pattern, branch): + # fnmatch handles character classes; a single * must not cross a GitHub branch slash. + regex = fnmatch.translate(pattern.replace("**", "__DOUBLE_STAR__") + .replace("?", "__SINGLE_CHAR__")).replace(".*", "[^/]*") + return re.fullmatch(regex.replace("__DOUBLE_STAR__", ".*") + .replace("__SINGLE_CHAR__", "[^/]"), branch) is not None + + +def _covers(event, branch): + if ("paths" in event or "paths-ignore" in event + or "branches" in event and "branches-ignore" in event): + return False + patterns = event.get("branches") + selected = patterns is None + if patterns is not None: + if not isinstance(patterns, list): + return False + for pattern in patterns: + if not isinstance(pattern, str) or "+" in pattern or "\\" in pattern: + return False + if _matches(pattern.removeprefix("!"), branch): + selected = not pattern.startswith("!") + ignored = event.get("branches-ignore", []) + if (not isinstance(ignored, list) + or any(not isinstance(pattern, str) or "+" in pattern or "\\" in pattern + for pattern in ignored)): + return False + return selected and not any(_matches(pattern, branch) for pattern in ignored) + + +def _inputs(event, where): + inputs = event.get("inputs", {}) + for name, kind in RELEASE_INPUTS.items(): + if inputs.get(name, {}).get("type") != kind: + raise ReadinessError("TEMPLATE_MISSING", f"{where} 缺少兼容输入 {name}: {kind}") + if any(value.get("required") and name not in RELEASE_INPUTS + for name, value in inputs.items()): + raise ReadinessError("TEMPLATE_MISSING", f"{where} 存在协调器不会提供的必需输入") + + +def check_workflow_file(api, repo, filename, ref, branch, text=None): + """Validate a caller and its reusable workflow without running either.""" + where = f"{repo}@{ref}:{filename}" + if text is None: + text = content(api, repo, f".github/workflows/{filename}", ref, missing=True) + if text is None: + raise ReadinessError("TEMPLATE_MISSING", f"{where} 不存在") + try: + workflow = yaml.safe_load(text) + if not isinstance(workflow, dict): + raise ValueError("workflow 不是对象") + dispatch = filename == WORKFLOW_FILES[0] + event = _event(workflow, "workflow_dispatch" if dispatch else "pull_request_target") + if not isinstance(event, dict): + raise ValueError("缺少 workflow_dispatch / pull_request_target 入口") + if dispatch: + _inputs(event, where) + else: + required = {"opened", "reopened", "synchronize", "edited", "ready_for_review", "closed"} + types = event.get("types", ["opened", "reopened", "synchronize"]) + if not required.issubset(types) or not _covers(event, branch): + raise ValueError(f"guard 无法覆盖 {branch} 的全部必要 PR 事件") + permissions = workflow.get("permissions", {}) + if not isinstance(permissions, dict) or permissions.get("statuses") != "write": + raise ValueError("guard 缺少 statuses: write") + shared_file = "update-changelog.yml" if dispatch else "verify-group-version.yml" + jobs = workflow.get("jobs", {}) + candidates = [job for job in jobs.values() if isinstance(job, dict) and + isinstance(job.get("uses"), str) and + f"/.github/workflows/{shared_file}@" in job["uses"]] + if len(candidates) != 1 or candidates[0].get("if") not in (None, True): + raise ValueError("共享工作流入口缺失、重复或有无法验证的条件") + job = candidates[0] + match = re.fullmatch(r"([A-Za-z0-9._-]+/\.github)/(\.github/workflows/[^@]+)@(.+)", + job["uses"]) + if not match: + raise ValueError("共享工作流引用无效") + shared_repo, path, shared_ref = match.groups() + if shared_repo != f"{repo.split('/')[0]}/.github": + raise ValueError("共享工作流必须引用当前组织的 .github 仓库") + if dispatch and any(job.get("with", {}).get(name) != "${{ inputs." + name + " }}" + for name in RELEASE_INPUTS): + raise ValueError("发版入口必须原样传递 base_branch 及现有输入") + shared = yaml.safe_load(content(api, shared_repo, path, shared_ref)) + call = _event(shared, "workflow_call") + if not isinstance(call, dict): + raise ValueError("共享工作流没有 workflow_call 入口") + if dispatch: + _inputs(call, job["uses"]) + except (TypeError, ValueError, KeyError, yaml.YAMLError) as error: + raise ReadinessError("TEMPLATE_MISSING", f"{where}: {error}") from error + return text + + +def check_member_workflows(api, repo, branch, info=None): + info = info or api(f"repos/{repo}") + if info.get("archived") is not False or info.get("disabled") is not False: + raise ReadinessError("WORKFLOW_INACTIVE", f"{repo} 已归档、禁用或状态未知") + target = branch_info(api, repo, branch, missing=True) + if target is None: + raise ReadinessError("BRANCH_MISSING", f"{repo}:{branch}") + actions = api(f"repos/{repo}/actions/permissions") + if actions.get("enabled") is not True: + raise ReadinessError("WORKFLOW_INACTIVE", f"{repo} Actions 未启用或不可读取") + for ref in dict.fromkeys((info["default_branch"], branch)): + head = target if ref == branch else branch_info(api, repo, ref) + for filename in WORKFLOW_FILES: + check_workflow_file(api, repo, filename, head["commit"]["sha"], branch) + for filename in WORKFLOW_FILES: + workflow = api(f"repos/{repo}/actions/workflows/{filename}", missing=True) + if workflow is None or workflow.get("state") != "active": + raise ReadinessError("WORKFLOW_INACTIVE", f"{repo}/{filename} 未启用或不可读取") + return target + + +def release_app_id(value): + if type(value) is not int or value <= 0: + raise ReadinessError("PROTECTION_FAILED", "无法确认发布 App 的身份") + return value + + +def read_protection(api, repo, branch, head=None): + """A protection 404 is only absence when branch state and effective rules agree.""" + head = head or branch_info(api, repo, branch) + classic = api(f"repos/{repo}/branches/{quote(branch, safe='')}/protection", missing=True) + rules = api(f"repos/{repo}/rules/branches/{quote(branch, safe='')}?per_page=100", + paginate=True) + if classic is not None and not isinstance(classic, dict): + raise ReadinessError("PROTECTION_FAILED", f"{repo}:{branch} 保护响应格式不可确认") + if not isinstance(rules, list) or not isinstance(head.get("protected"), bool): + raise ReadinessError("PROTECTION_FAILED", f"{repo}:{branch} 保护状态不可读取") + if classic is None and head["protected"] and not rules: + raise ReadinessError("PROTECTION_FAILED", f"{repo}:{branch} 保护返回 404,无法确认有效规则") + rulesets = {} + for rule in rules: + ruleset_id = rule.get("ruleset_id") + if type(ruleset_id) is not int: + raise ReadinessError("PROTECTION_FAILED", f"{repo}:{branch} 有效规则来源未知") + if ruleset_id not in rulesets: + value = api(f"repos/{repo}/rulesets/{ruleset_id}?includes_parents=true") + if value.get("enforcement") != "active" or "bypass_actors" not in value: + raise ReadinessError("PROTECTION_FAILED", f"{repo}:{branch} 无法读取规则集绕过权限") + rulesets[ruleset_id] = value + return {"classic": classic, "rules": rules, "rulesets": rulesets} + + +def _enabled(protection, name): + value = protection.get(name) + return value.get("enabled") if isinstance(value, dict) else value + + +def _classic_ready(protection, app_id): + if not isinstance(protection, dict): + return False + reviews = protection.get("required_pull_request_reviews") + checks = protection.get("required_status_checks") or {} + return (isinstance(reviews, dict) + and not any(reviews.get("bypass_pull_request_allowances", {}).values()) + and _enabled(protection, "enforce_admins") is True + and _enabled(protection, "allow_force_pushes") is False + and _enabled(protection, "allow_deletions") is False + and _enabled(protection, "lock_branch") is not True + and checks.get("strict") is True + and any(check.get("context") == GUARD_CONTEXT and check.get("app_id") == app_id + for check in checks.get("checks", []))) + + +def protection_ready(protection, app_id): + if _classic_ready(protection["classic"], app_id): + return True + # Rules are additive. Only rulesets whose bypass list is known empty prove enforcement. + rules = [rule for rule in protection["rules"] + if protection["rulesets"][rule["ruleset_id"]]["bypass_actors"] == []] + types = {rule["type"] for rule in rules} + checks = [rule.get("parameters", {}) for rule in rules if rule["type"] == "required_status_checks"] + return ({"pull_request", "deletion", "non_fast_forward"}.issubset(types) + and any(value.get("strict_required_status_checks_policy") is True + and any(check.get("context") == GUARD_CONTEXT + and check.get("integration_id") == app_id + for check in value.get("required_status_checks", [])) + for value in checks)) + + +def check_member_ready(api, repo, branch, app_id=None): + """Return READY only after live workflow and effective protection checks; never writes.""" + if app_id is None: + try: + app_id = int(os.environ["APP_ID"]) + except (KeyError, ValueError) as error: + raise ReadinessError("PROTECTION_FAILED", "缺少发布 App ID") from error + state = "TEMPLATE_MISSING" + try: + target = check_member_workflows(api, repo, branch) + state = "PROTECTION_FAILED" + protection = read_protection(api, repo, branch, target) + if not protection_ready(protection, release_app_id(app_id)): + raise ReadinessError(state, f"{repo}:{branch} 需要 PR、禁止绕过/force/delete、严格检查 " + f"{GUARD_CONTEXT}(来源发布 App)") + return {"repo": repo, "branch": branch, "state": "READY"} + except RuntimeError: + raise + except Exception as error: + raise ReadinessError(state, f"{repo}:{branch} 工作流或 API 响应格式不可确认: {error}") from error diff --git a/.github/workflows/propose-release-line.yml b/.github/workflows/propose-release-line.yml new file mode 100644 index 0000000..8013bd9 --- /dev/null +++ b/.github/workflows/propose-release-line.yml @@ -0,0 +1,66 @@ +# SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: GPL-3.0-or-later +name: Propose release line + +on: + workflow_dispatch: + inputs: + release_line: + description: 新发布线 ID(例如 develop-2500u1) + required: true + type: string + target_branch: + description: 新发布线在各成员仓库中的分支名(例如 develop/2500u1) + required: true + type: string + source_branch: + description: 各成员仓库中已有的代码来源分支(默认 master;例如 develop/2500u3,无需先登记发布线) + required: false + type: string + default: master + dry_run: + description: 只读预检并输出固定 SHA 与配置差异 + required: false + type: boolean + default: true + +permissions: + contents: read + +jobs: + propose: + if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch) + runs-on: ubuntu-latest + timeout-minutes: 30 + concurrency: + group: baseline-controller + cancel-in-progress: false + queue: max + steps: + - name: Create GitHub App token + id: app_token + uses: actions/create-github-app-token@v3 + with: + app-id: ${{ secrets.APP_ID }} + private-key: ${{ secrets.APP_PRIVATE_KEY }} + owner: ${{ github.repository_owner }} + permission-contents: write + permission-pull-requests: write + + - name: Checkout trusted default branch + uses: actions/checkout@v5 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: Install deps + run: pip install --quiet pyyaml + + - name: Propose fixed member snapshot + env: + GH_TOKEN: ${{ steps.app_token.outputs.token }} + RELEASE_LINE: ${{ inputs.release_line }} + TARGET_BRANCH: ${{ inputs.target_branch }} + SOURCE_BRANCH: ${{ inputs.source_branch }} + DRY_RUN: ${{ inputs.dry_run }} + run: python3 .github/scripts/propose_release_line.py diff --git a/.github/workflows/release-group.yml b/.github/workflows/release-group.yml index 9862499..6ac2994 100644 --- a/.github/workflows/release-group.yml +++ b/.github/workflows/release-group.yml @@ -21,10 +21,11 @@ on: description: debian/changelog 中的维护者邮箱 required: true type: string - base_branch: - description: 成员目标分支(G2;留空使用各成员默认分支,恢复时沿用原分支) + release_line: + description: 发布线 ID(G2 使用配置中的成员分支;G1 只支持 master) required: false type: string + default: master distribution: description: Changelog 发行套件(G2) required: false @@ -45,7 +46,7 @@ permissions: contents: read concurrency: - group: release-group-${{ inputs.group }} + group: release-group-${{ inputs.group == 'G2' && format('{0}-{1}', inputs.release_line || 'master', inputs.group) || inputs.group }} cancel-in-progress: false queue: max @@ -56,7 +57,7 @@ jobs: group: ${{ inputs.group }} version: ${{ inputs.version }} dry_run: ${{ inputs.dry_run }} - base_branch: ${{ inputs.base_branch }} + release_line: ${{ inputs.release_line }} distribution: ${{ inputs.distribution }} create_pr: ${{ inputs.create_pr }} defer_pr: true @@ -68,6 +69,7 @@ jobs: needs: plan if: ${{ !inputs.dry_run && needs.plan.outputs.repos != '[]' }} runs-on: ubuntu-latest + timeout-minutes: 15 strategy: fail-fast: false matrix: @@ -127,7 +129,7 @@ jobs: group: ${{ inputs.group }} version: ${{ inputs.version }} dry_run: false - base_branch: ${{ inputs.base_branch }} + release_line: ${{ inputs.release_line }} distribution: ${{ inputs.distribution }} create_pr: true defer_pr: true diff --git a/.github/workflows/sync-baseline.yml b/.github/workflows/sync-baseline.yml index 3dfe097..0288f7e 100644 --- a/.github/workflows/sync-baseline.yml +++ b/.github/workflows/sync-baseline.yml @@ -26,6 +26,10 @@ on: base_branch: required: false type: string + release_line: + required: false + type: string + default: master distribution: required: false type: string @@ -58,6 +62,7 @@ jobs: coordinate: name: Coordinate group release runs-on: ubuntu-latest + timeout-minutes: 45 if: > github.event_name != 'pull_request_target' || github.event.pull_request.head.repo.full_name == github.repository || @@ -81,6 +86,12 @@ jobs: permission-contents: write permission-pull-requests: write permission-statuses: write + permission-administration: ${{ inputs.group != 'G1' && 'read' || '' }} + + - uses: actions/checkout@v5 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false - name: Install deps run: pip install --quiet pyyaml @@ -89,10 +100,12 @@ jobs: id: coordinate env: GH_TOKEN: ${{ steps.app_token.outputs.token }} + APP_ID: ${{ secrets.APP_ID }} GROUP: ${{ inputs.group }} VERSION: ${{ inputs.version }} DRY_RUN: ${{ inputs.dry_run }} MEMBER_BASE: ${{ inputs.base_branch }} + RELEASE_LINE: ${{ inputs.release_line }} DISTRIBUTION: ${{ inputs.distribution }} CREATE_PR: ${{ inputs.create_pr }} DEFER_PR: ${{ inputs.defer_pr }} @@ -106,6 +119,7 @@ jobs: import os import re import subprocess + import sys import tempfile import time from concurrent.futures import ThreadPoolExecutor @@ -113,6 +127,9 @@ jobs: import yaml + sys.path.insert(0, os.path.join(os.environ.get("GITHUB_WORKSPACE", "."), ".github", "scripts")) + from release_line_checks import MAX_TRAVERSAL_DEPTH + MARKER = "