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
53 changes: 53 additions & 0 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,59 @@ jobs:
- name: Scan tracked files for private identity and paths
run: python3 .modavd/scripts/privacy.py .

authors:
name: Commit authors and trailers
runs-on: ubuntu-24.04
timeout-minutes: 10
env:
# 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
with:
fetch-depth: 0
persist-credentials: false
- name: Run repo checks unit tests
run: python3 -B -I -X utf8 scripts/test_repo_checks.py -v
# PR 里的提交在 pull_request 时已经查过。push 和 merge_group 下要查的只剩 GitHub 生成的 squash 提交,
# 它的作者邮箱取自贡献者 GitHub 账号的设置,不归作者检查管;查了会让合并队列和 main 无端变红。
- name: Check commit authors and trailers
if: github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch'
run: python3 -B -I -X utf8 scripts/repo_checks.py

shared-scripts:
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- name: Checkout without persistent credentials
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- 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/repo_checks.py
scripts/test_repo_checks.py
sparse-checkout-cone-mode: false
- name: Shared scripts are ModAVD's
shell: bash
run: |
set -euo pipefail
for f in 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."
exit 1
fi
done
echo "repo_checks.py and test_repo_checks.py are the same as ModAVD/ModAVD main $(git -C .modavd rev-parse --short HEAD)"

zizmor:
name: Workflow security (zizmor)
runs-on: ubuntu-24.04
Expand Down
66 changes: 66 additions & 0 deletions scripts/repo_checks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""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

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 allowed(name: str, email: str) -> bool:
identity = f"{name} <{email}>"
return bool(ALLOWED_AUTHOR.fullmatch(identity) or any(rx.fullmatch(email) for rx in ALLOWED_NOREPLY))


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_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("REPO_CHECK_BASE")
head = os.environ.get("REPO_CHECK_HEAD")
if not base or not head:
base, head = "origin/main", "HEAD"
try:
ids = commits(base, head)
except subprocess.CalledProcessError as exc:
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__":
sys.exit(main())
54 changes: 54 additions & 0 deletions scripts/test_repo_checks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import 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.allowed("qiyinxi", "qiyinxi@foxmail.com"))
self.assertTrue(repo_checks.allowed("bot", "123+bot[bot]@users.noreply.github.com"))
# Dependabot 的提交作者,原样照 GitHub 写的抄。
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_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_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__":
unittest.main()
Loading