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
26 changes: 15 additions & 11 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -81,32 +81,36 @@ 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' }}
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 || github.sha }}
steps:
- name: Checkout full history without persistent credentials
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
Expand Down
91 changes: 44 additions & 47 deletions scripts/repo_checks.py
Original file line number Diff line number Diff line change
@@ -1,69 +1,66 @@
"""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
import re
import subprocess
import sys

EXPECTED = "qiyinxi <qiyinxi@foxmail.com>"
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 <qiyinxi@foxmail\.com>$")
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())
53 changes: 38 additions & 15 deletions scripts/test_repo_checks.py
Original file line number Diff line number Diff line change
@@ -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 <noreply@openai.com>\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 <noreply@openai.com>"], 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__":
Expand Down
Loading