From 9f98bfcaf94c6ec9860f57a0aaa42b814346b7e4 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 21 Nov 2026 17:24:51 +0100 Subject: [PATCH] =?UTF-8?q?ci:=20=E6=8F=90=E4=BA=A4=E4=BD=9C=E8=80=85?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E6=8D=A2=E6=88=90=20ModAVD=20=E7=9A=84?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E7=89=88=E6=9C=AC=EF=BC=8CCI=20=E6=A0=B8?= =?UTF-8?q?=E5=AF=B9=E9=80=90=E5=AD=97=E8=8A=82=E7=9B=B8=E5=90=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs ModAVD/ModAVD#44 Refs ModAVD/ModAVD#145 --- .github/workflows/ci.yml | 27 ++++++----- scripts/repo_checks.py | 91 ++++++++++++++++++------------------- scripts/test_repo_checks.py | 53 +++++++++++++++------ 3 files changed, 98 insertions(+), 73 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6303b6f..7d28088 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -114,32 +114,37 @@ jobs: - name: Scan tracked files for private data shell: bash run: python3 -B -I -X utf8 scripts/privacy.py . --allowlist scripts/privacy-allowlist.json - - name: Checkout ModAVD for the shared privacy scanner + - name: Checkout ModAVD for the shared scripts uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: ModAVD/ModAVD ref: main path: .modavd persist-credentials: false - sparse-checkout: scripts/privacy.py + sparse-checkout: | + scripts/privacy.py + scripts/repo_checks.py + scripts/test_repo_checks.py sparse-checkout-cone-mode: false - - name: scripts/privacy.py is ModAVD's + - name: Shared scripts are ModAVD's shell: bash run: | set -euo pipefail - if ! cmp -s scripts/privacy.py .modavd/scripts/privacy.py; then - echo "::error file=scripts/privacy.py::scripts/privacy.py differs from ModAVD/ModAVD main. The scanner is changed in ModAVD first; copy its scripts/privacy.py here byte for byte (only privacy-allowlist.json is this repository's own)." - exit 1 - fi - echo "scripts/privacy.py is the same as ModAVD/ModAVD main $(git -C .modavd rev-parse --short HEAD)" + for f in scripts/privacy.py scripts/repo_checks.py scripts/test_repo_checks.py; do + if ! cmp -s "$f" ".modavd/$f"; then + echo "::error file=$f::$f differs from ModAVD/ModAVD main. These scripts are changed in ModAVD first; copy its $f here byte for byte (only privacy-allowlist.json is this repository's own)." + exit 1 + fi + done + echo "privacy.py, repo_checks.py and test_repo_checks.py are the same as ModAVD/ModAVD main $(git -C .modavd rev-parse --short HEAD)" authors: runs-on: ubuntu-24.04 timeout-minutes: 10 env: - CHECK_BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || '' }} - CHECK_HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} - CHECK_MANUAL: ${{ github.event_name == 'workflow_dispatch' && '1' || '0' }} + # Empty outside pull_request: the script then checks origin/main..HEAD. + REPO_CHECK_BASE: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || '' }} + REPO_CHECK_HEAD: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || '' }} steps: - name: Checkout full history without persistent credentials uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/scripts/repo_checks.py b/scripts/repo_checks.py index a29e0d3..6343dca 100644 --- a/scripts/repo_checks.py +++ b/scripts/repo_checks.py @@ -1,4 +1,8 @@ -"""Check commit authors and Co-authored-by trailers for public history.""" +"""Validate commit authors and Co-authored-by trailers for public history. + +This file and test_repo_checks.py are the same in every ModAVD repository. Change them in ModAVD/ModAVD first, then +copy them byte for byte to the others; each repository's CI compares them with ModAVD/ModAVD main. +""" from __future__ import annotations import os @@ -6,64 +10,57 @@ import subprocess import sys -EXPECTED = "qiyinxi " -NOREPLY = re.compile(r"^(?:[0-9]+\+[A-Za-z0-9-]+(?:\[bot\])?|[A-Za-z0-9-]+)@users\.noreply\.github\.com$") -TRAILER = re.compile(r"^\s*Co-authored-by:\s*(.+?)\s*<([^>]+)>\s*$", re.I | re.M) +ALLOWED_AUTHOR = re.compile(r"^qiyinxi $") +ALLOWED_NOREPLY = ( + re.compile(r"^[0-9]+\+[A-Za-z0-9-]+(?:\[bot\])?@users\.noreply\.github\.com$"), + re.compile(r"^[A-Za-z0-9-]+@users\.noreply\.github\.com$"), +) -def identity_allowed(name: str, email: str) -> bool: +def allowed(name: str, email: str) -> bool: identity = f"{name} <{email}>" - if identity == EXPECTED: - return True - blocked_ai_emails = {"noreply@" + "anthropic.com", "noreply@" + "openai.com"} - if email.lower() in blocked_ai_emails: - return False - return bool(NOREPLY.fullmatch(email)) + return bool(ALLOWED_AUTHOR.fullmatch(identity) or any(rx.fullmatch(email) for rx in ALLOWED_NOREPLY)) -def commits_in_range(base: str, head: str): - raw = subprocess.check_output( - ["git", "log", "--no-merges", "--format=%H%x00%an%x00%ae%x00%B%x1e", f"{base}..{head}"], - text=True, - encoding="utf-8", - ) - commits = [] - for record in raw.split("\x1e"): - record = record.strip("\n") - if not record: - continue - sha, name, email, message = record.split("\x00", 3) - commits.append((sha, name, email, message)) - return commits +def commits(base: str, head: str, cwd: str = ".") -> list[str]: + spec = f"{base}..{head}" + out = subprocess.check_output(["git", "rev-list", "--no-merges", spec], cwd=cwd, text=True, encoding="utf-8") + return [x for x in out.splitlines() if x] -def check_commits(commits): - failures = [] - for sha, name, email, message in commits: - if not identity_allowed(name, email): - failures.append(f"{sha}: author {name} <{email}> is not allowed") - for trailer_name, trailer_email in TRAILER.findall(message): - if not identity_allowed(trailer_name, trailer_email): - failures.append(f"{sha}: Co-authored-by {trailer_name} <{trailer_email}> is not allowed") - return failures +def check_commit(commit: str, cwd: str = ".") -> list[str]: + fmt = "%an%x00%ae%x00%B" + raw = subprocess.check_output(["git", "show", "-s", f"--format={fmt}", commit], cwd=cwd, text=True, + encoding="utf-8") + name, email, message = raw.split("\x00", 2) + errors: list[str] = [] + if not allowed(name.strip(), email.strip()): + errors.append(f"{commit}: author {name.strip()} <{email.strip()}> is not allowed") + for line in message.splitlines(): + if line.strip().lower().startswith("co-authored-by:"): + value = line.split(":", 1)[1].strip() + match = re.fullmatch(r".+ <([^<>]+)>", value) + if not match or not allowed(value.rsplit(" <", 1)[0], match.group(1)): + errors.append(f"{commit}: {line}") + return errors def main() -> int: - base = os.environ.get("CHECK_BASE_SHA") - head = os.environ.get("CHECK_HEAD_SHA") or subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() - if os.environ.get("CHECK_MANUAL") == "1" or not base: - base = "origin/main" + base = os.environ.get("REPO_CHECK_BASE") + head = os.environ.get("REPO_CHECK_HEAD") + if not base or not head: + base, head = "origin/main", "HEAD" try: - commits = commits_in_range(base, head) + ids = commits(base, head) except subprocess.CalledProcessError as exc: - print(f"无法读取提交范围 {base}..{head}: {exc}", file=sys.stderr) - return 2 - failures = check_commits(commits) - print(f"检查 {len(commits)} 个非合并提交") - for failure in failures: - print(f"FAIL: {failure}") - return 1 if failures else 0 + print(f"cannot inspect {base}..{head}: git exited {exc.returncode}") + return 1 + errors = [error for commit in ids for error in check_commit(commit)] + for error in errors: + print(error) + print(f"Author check: {len(ids)} non-merge commits; {len(errors)} failures") + return 1 if errors else 0 if __name__ == "__main__": - raise SystemExit(main()) + sys.exit(main()) diff --git a/scripts/test_repo_checks.py b/scripts/test_repo_checks.py index 965508a..861ed9a 100644 --- a/scripts/test_repo_checks.py +++ b/scripts/test_repo_checks.py @@ -1,30 +1,53 @@ -from pathlib import Path +import os +import subprocess import sys +import tempfile import unittest +from pathlib import Path -# CI runs this file with python -I, which leaves the script directory off sys.path. +# CI runs this with python -I, which leaves the script's own directory off sys.path. sys.path.insert(0, str(Path(__file__).resolve().parent)) import repo_checks # noqa: E402 class RepoChecksTest(unittest.TestCase): def test_allowed_identities(self): - self.assertTrue(repo_checks.identity_allowed("qiyinxi", "qiyinxi@foxmail.com")) - self.assertTrue(repo_checks.identity_allowed("Bot", "123+bot[bot]@users.noreply.github.com")) + self.assertTrue(repo_checks.allowed("qiyinxi", "qiyinxi@foxmail.com")) + self.assertTrue(repo_checks.allowed("bot", "123+bot[bot]@users.noreply.github.com")) # Dependabot 的提交作者,原样照 GitHub 写的抄。 - self.assertTrue(repo_checks.identity_allowed("dependabot[bot]", "49699333+dependabot[bot]@users.noreply.github.com")) - self.assertTrue(repo_checks.identity_allowed("Old", "octocat@users.noreply.github.com")) + self.assertTrue(repo_checks.allowed("dependabot[bot]", "49699333+dependabot[bot]@users.noreply.github.com")) + self.assertTrue(repo_checks.allowed("someone", "someone@users.noreply.github.com")) + self.assertFalse(repo_checks.allowed("ai", "noreply@openai.com")) + self.assertFalse(repo_checks.allowed("Claude", "noreply@" + "anthropic.com")) + self.assertFalse(repo_checks.allowed("qiyinxi", "someone@example.com")) + self.assertTrue(repo_checks.allowed("Old", "octocat@users.noreply.github.com")) + self.assertFalse(repo_checks.allowed("Someone", "someone@example.com")) + self.assertFalse(repo_checks.allowed("Codex", "noreply@openai.com")) - def test_rejects_private_or_ai_identities(self): - self.assertFalse(repo_checks.identity_allowed("Someone", "someone@example.com")) - self.assertFalse(repo_checks.identity_allowed("Codex", "noreply@openai.com")) - self.assertFalse(repo_checks.identity_allowed("Claude", "noreply@" + "anthropic.com")) + def test_commit_and_coauthor(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + subprocess.run(["git", "init", "-q"], cwd=root, check=True) + subprocess.run(["git", "config", "user.name", "qiyinxi"], cwd=root, check=True) + subprocess.run(["git", "config", "user.email", "qiyinxi@foxmail.com"], cwd=root, check=True) + (root / "x").write_text("x") + subprocess.run(["git", "add", "x"], cwd=root, check=True) + env = dict(os.environ, GIT_AUTHOR_NAME="qiyinxi", GIT_AUTHOR_EMAIL="qiyinxi@foxmail.com") + subprocess.run(["git", "commit", "-qm", "ok\n\nCo-authored-by: bot <123+bot[bot]@users.noreply.github.com>"], cwd=root, env=env, check=True) + commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip() + self.assertEqual(repo_checks.check_commit(commit, str(root)), []) - def test_commit_and_trailer_checks(self): - good = [("a" * 40, "qiyinxi", "qiyinxi@foxmail.com", "说明\n\nCo-authored-by: Bot <123+bot[bot]@users.noreply.github.com>\n")] - self.assertEqual(repo_checks.check_commits(good), []) - bad = [("b" * 40, "qiyinxi", "qiyinxi@foxmail.com", "说明\n\nCo-authored-by: AI \n")] - self.assertEqual(len(repo_checks.check_commits(bad),), 1) + def test_rejects_ai_trailer(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + subprocess.run(["git", "init", "-q"], cwd=root, check=True) + subprocess.run(["git", "config", "user.name", "qiyinxi"], cwd=root, check=True) + subprocess.run(["git", "config", "user.email", "qiyinxi@foxmail.com"], cwd=root, check=True) + (root / "x").write_text("x") + subprocess.run(["git", "add", "x"], cwd=root, check=True) + subprocess.run(["git", "commit", "-qm", "bad\n\n co-authored-by: bot "], cwd=root, check=True) + commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip() + self.assertTrue(repo_checks.check_commit(commit, str(root))) if __name__ == "__main__":