Files
cindy/scripts/check-dco.mjs
Dash 2dd1600f3e chore(dco): 落地 DCO 签名基础设施(App 门禁 + 本地 hook + 自查脚本) (#396)
* chore(dco): 落地 DCO 签名基础设施

仓库公开前把 DCO 从 CONTRIBUTING 里的一句要求补成可执行的门禁。PR 侧用已装到 org 的
DCO GitHub App,本仓提供它的配置、本地自查与自动签名。历史提交不受影响:只看 PR 内的
commit。

- DCO:Developer Certificate of Origin 1.1 原文,逐字未改
- .github/dco.yml:开启 individual + thirdParty remediation commit,让漏签的 PR 可以
  不改写历史、保住已有 review 讨论
- .githooks/prepare-commit-msg:本地自动补签。git 没有让 commit 自动签名的配置项
  (format.signOff 只作用于 format-patch / am),只能用 hook;输出排版对齐原生
  git commit -s,并显式钉住 --if-exists / --if-missing,避免开发者的 trailer.ifExists
  配置导致静默漏签
- scripts/install-dco-hook.mjs:把上面的 hook 复制进 hooks 目录,不覆盖他人同名 hook
- scripts/check-dco.mjs:提交前自查(pnpm check:dco)。判定对齐 App——名字与邮箱都要
  匹配 author 或 committer,并校验邮箱形状;刻意不识别 remediation commit,保证本地
  通过则 App 必过,不会出现本地绿而 PR 红
- scripts/__tests__/check-dco.test.mjs:13 个用例,含真 git 仓库端到端
- CONTRIBUTING / README(中英)、PR 模板、AGENTS.md、development-workflow.md 写明门禁、
  两种补签方式,以及 agent 自动提交同样适用

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Signed-off-by: Dash <dashhuang@gmail.com>

* fix(dco): hook 改签 committer,并收紧本地自查与 hook 所有权判定

处理 review 反馈里核实成立的部分。两个真 bug:

- hook 原来取 GIT_AUTHOR_IDENT,在 git commit --author=、cherry-pick 或 rebase 他人
  patch 时会替原作者伪造 DCO 声明。改取 GIT_COMMITTER_IDENT——原生 git commit -s 就是
  这个语义(签名是执行提交者的声明);门禁接受 author 或 committer 的签名,不影响通过。
- install-dco-hook 的所有权判定原来只看「文件含 marker」。开发者按提示把本仓逻辑合并进
  自己的 hook 后,那份复合 hook 会被判成本仓的旧版本并被整份覆盖,抹掉他自己的逻辑。
  改为比对开头两行(shebang + marker 注释),复合 hook 一律算 foreign 不覆盖。

三处收紧本地自查,都是为了不出现「本地绿、PR 红」:

- 邮箱形状原来的单行正则会放行 validator.isEmail 拒绝的地址(连续点、下划线域名等),
  现在 local part 与域名分开校验并要求字母 TLD
- 签名改为 name+email 成对匹配某一个身份。原来拆成两个集合,author=Alice<a@x>、
  committer=Bob<b@x> 时 `Alice <b@x>` 也能过,尽管这个身份不存在。这让本脚本比 App 更严,
  偏严只会本地红、PR 绿,是安全方向
- 修复提示里的 rebase base 用完整 sha,短 sha 在大仓可能歧义

另外删掉了 check-dco.mjs 头部对 .github/workflows/dco.yml 的引用(该 workflow 已改用
DCO App,文件不存在)。

新增回归用例覆盖:--author 场景下签 committer 且与原生 -s 一致、复合 hook 判 foreign、
validator 会拒的地址逐个断言拒绝、交叉身份签名不通过。反向验证过前两项——还原任一处
修复会分别红 2 个用例。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Signed-off-by: Dash <dashhuang@gmail.com>

* fix(dco): hook 安装器不再猜所有权,邮箱校验对齐 validator 字符集

第二轮 review 反馈,三处成立:

- hook 所有权判定上一版按「开头两行」判断,只挡住了「把本仓逻辑合并进自己的 hook」,
  挡不住「在本仓装好的 hook 后面追加自己的逻辑」——后者开头两行仍是我们的,会被判成
  旧版本并整份覆盖。这两种情况在磁盘上分辨不出来,所以不再猜:内容不等于源文件就是
  modified,一律要显式 --force 才覆盖,并提示先 diff。
- 邮箱形状仍比 validator.isEmail 宽松:local part 收紧到 RFC 5322 的 atext 字符集
  (拒 a(b)@x.com 这类),域名 label 不再允许以连字符开头或结尾(拒 a@-foo.com)。
  含方括号的 bot 地址因此也不合格,但 bot 提交在 exemptReason 就豁免了,走不到这里——
  补了交叉用例把这条钉住。
- resolveHooksDir 依赖的 --path-format 要 git 2.31+,旧版直接失败会让安装器不可用,
  回落成 --git-path + show-toplevel 自己拼绝对路径。

另有一条 P1 是误报:说 commit 651e353f 没有签名,但该 sha 在远端与本地都不存在
(gh api 返回 422、git cat-file 失败),PR 的两个 commit 都带 Signed-off-by。上一轮
同一 bot 报的 ac842de1 也是同样情况,都是它在自己环境重建 commit 后检查了自己的 sha。

新增用例:追加型复合 hook 判 modified、无 --force 时拒绝覆盖且不改动文件、--force 才
覆盖、resolveHooksDir 返回绝对路径、bot 地址不合格但仍豁免、validator 会拒的新反例。
反向验证过邮箱那处——放宽 atext 会红 2 个用例。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Signed-off-by: Dash <dashhuang@gmail.com>

* fix(dco): 修正旧版 git 的 hooks 路径基准,补齐邮箱长度上限与 fork 默认基准

第三轮 review 反馈,三处成立:

- resolveHooksDir 的旧版 git 回落分支用仓库根去解析 `git rev-parse --git-path hooks`
  的返回值,但那个相对路径是相对于**执行 git 时的 cwd**。从子目录调用时它形如
  ../../.git/hooks,拿仓库根解析会向上多走几级,把 hook 装进隔壁或上层仓库的
  .git/hooks——既漏装本仓,又动了别的仓库。改用同一个 cwd 解析,并把这一步抽成
  resolveHooksPathFrom 以便直接断言(走到该分支需要 git < 2.31,CI 上跑不到)。
- 邮箱校验只做了字符集与连字符规则,没有长度上限:65 字符的 local part 本地放行、
  validator.isEmail 拒绝。补上 local part ≤ 64、域名 ≤ 254、单个 label ≤ 63,并断言
  恰好在上限的地址仍放行。
- 本地默认基准候选加 upstream/main 且排在 origin/main 之前。从 fork 干活时 origin/main
  可能领先于上游,拿它当基准会把 fork 自己那些未签名的提交排除在范围外,而 PR 的真实
  base 是上游。这只是本地自查的启发式,真实结论仍以 PR 上的 DCO check 为准。

另有一条 P1 是同类误报(第三次):说 commit 426347872c 没有签名,但该 sha 在远端与本地
都不存在,PR 的三个 commit 都带 Signed-off-by,DCO check 为 success。

反向验证过前两处:把 hooks 路径基准改回仓库根、或去掉长度检查,各会红 1 个用例。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Signed-off-by: Dash <dashhuang@gmail.com>

* docs(dco): 修正 hook 与安装器注释里过时的 author/门禁归属表述

两处都是前几轮改动留下的文档漂移,reviewer 指出的都对:

- install-dco-hook.mjs 顶部仍写「追加与 commit author 一致的 Signed-off-by」,但 hook 在
  第一轮修复后已改成签 committer(与原生 git commit -s 一致)。
- 两个文件都把「PR 上的门禁」说成 scripts/check-dco.mjs。实际权威门禁是 DCO GitHub App
  (配置见 .github/dco.yml),check-dco.mjs 只是本地提交前自查。

只改注释,无逻辑改动。顺带全仓 grep 了同类措辞,没有其它残留。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Signed-off-by: Dash <dashhuang@gmail.com>

* fix(dco): 补邮箱整体长度上限、bot 判定只认邮箱、修复丢失可执行位的 hook

第五轮 review 反馈,三处成立:

- 邮箱长度上限漏了整体那一条。local part ≤ 64、域名 ≤ 254、label ≤ 63 各自满足时,
  整个地址仍可能超过 validator.isEmail 的 254 上限(reviewer 给的例子是 258 字符)。
  补上整体检查,并加了长度恰好 254 放行、255 拒绝的边界断言。
- isBotIdentity 不再认 author name 的 `[bot]` 后缀。`git config user.name` 谁都能设成
  `Foo[bot]`,按 name 豁免等于给本地检查留一个一步就能绕过的后门,且方向是「本地绿、
  PR 红」——App 判定的是不可伪造的 GitHub 账号类型。现在只认 bot 邮箱
  (web-flow 的 noreply@github.com 与 `*[bot]@users.noreply.github.com`)。
- 安装器遇到「内容逐字一致但丢了可执行位」时会报「已是最新」直接返回,而 git 会静默
  忽略不可执行的 hook——于是安装器说装好了,提交却一直没签名。现在这种情况会补回
  执行位并说明原因,--check 也会点出「NOT executable」而不是笼统报 installed。

另有一条 P1 是同类误报(第四次):说 commit 8d8ec210 没有签名且「resolves locally」,但
该 sha 在本仓远端与本地都不存在(gh api 422、git cat-file 失败),PR 的 5 个 commit 全部
带 Signed-off-by。

顺带清理了上一轮抽函数时留在 resolveHooksPathFrom 前面的悬空注释。

反向验证过三处:去掉整体长度检查、恢复 name 后缀豁免、去掉可执行位修复,各会红 1 个用例。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Signed-off-by: Dash <dashhuang@gmail.com>

* fix(dco): hook 固定 LF 检出,签名解析对齐 App 的行格式

第六轮 review 反馈,三处成立:

- .githooks/ 下的 hook 没有扩展名,命不中 .gitattributes 已有的 `*.sh` / `*.mjs`
  规则。Windows autocrlf 检出成 CRLF 后 `#!/bin/sh\r` 无法执行,git commit 会直接
  `fatal: cannot exec`——装了 hook 的人从此提交不了。补 `.githooks/** text eol=lf`,
  git check-attr 已确认生效。仓库先前为 *.sh 与 *.mjs 加过同样保护并写了注释,这次是漏了。
- 签名解析比 App 宽松三处,都会造成「本地绿、PR 红」:行首空白(App 的 `^Signed-off-by:`
  锚在行首,缩进行在它眼里不是签名)、冒号后多个空格(多出的空格被 App 算进 name,
  与 author 比不上)、捕获值 trim(App 拿原样值比对)。正则改为与 dcoapp/app 的
  `/^Signed-off-by: (.*) <(.*)>\s*$/gim` 逐字对齐,比对时签名侧只 lowercase 不 trim。
- 安装器提示的 diff 命令换成 `git diff --no-index`:git 本来就是本仓前置依赖,而
  diff(1) 在部分 Windows 环境没有。

另有两条 P1 是同类误报(第五、六次,sha 7c571f80 与 be844285 在本仓远端与本地都不存在),
一条是过时反馈(bot name 豁免已在 e83fca65 去掉)。

CI 的 verify 之前红过一次,核实是 main 基线问题:#329 合入后有 3 条源码文本断言过时,
main 上的 5c1a81c 已修好,但它比本 PR 那轮 CI 晚合入。已 update-branch 同步最新 main。

反向验证过两处正则修复:放宽任一处各会红 1 个用例。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Signed-off-by: Dash <dashhuang@gmail.com>

* refactor(dco): classifyHook 的源文件读取改为懒求值

默认参数 `expectedContent = readHookSource()` 会在调用时就求值,于是
`classifyHook(null)`(没装 hook 这条最常见的路径)也要读一次磁盘,并且把这个判断
绑到了源文件可读上。改成先判 missing、再按需 `?? readHookSource()`。

行为不变,纯效率与依赖面收敛。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Signed-off-by: Dash <dashhuang@gmail.com>

* fix(dco): 本地不再按邮箱豁免 bot,改为只豁免 merge commit

reviewer 指出上一轮的邮箱豁免仍可伪造:author 邮箱是自由填写的,
`999999+not-a-real-account[bot]@users.noreply.github.com` 谁都能设,而 App 认的是
GitHub 账号类型(author.type === "Bot")。按邮箱豁免等于留一个可伪造的后门,方向还是
最坏的「本地绿、PR 红」。

离线能可靠判定的豁免依据只有父提交数量,所以 exemptReason 现在只豁免 merge commit。
bot 提交在本地照常检查——方向安全(本地红、PR 绿),失败输出里解释清楚:这类地址在
PR 上由 App 按账号类型豁免,而账号类型离线取不到,所以本地不敢信一个可伪造的地址。

原 isBotIdentity 改名为 looksLikeBotAddress,语义收窄为「只用于失败输出的提示」,
并去掉了已在上一轮移除的 name 后缀判断残留说明。

同步了三处因语义变更而过时的表述:check-dco.mjs 里「bot 提交在 exemptReason 就被豁免,
走不到这里」、测试文件头的「merge/bot 豁免」、以及 CONTRIBUTING 中英两版里对
`pnpm check:dco` 保守程度的说明(现在明确列出 remediation 与 bot 两项差异)。

提交前门禁:根 pnpm test:unit 有 1 项 apps/mobile 的 startupSplashOverlay 超时失败,
与本 PR 无关——该测试单跑 3.95s、默认上限 5s,本机负载峰值 150+ 时必然 flake;定向重跑
6/6 通过。不在本 PR 混入无关修复。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Signed-off-by: Dash <dashhuang@gmail.com>

---------

Signed-off-by: Dash <dashhuang@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-25 19:49:56 +08:00

348 lines
15 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
// DCO(Developer Certificate of Origin)门禁:校验一段 commit 范围里每个非豁免 commit
// 都带有与其 author(或 committer)一致的 Signed-off-by trailer。DCO 全文见仓库根
// 的 DCO 文件,贡献者侧说明见 CONTRIBUTING.md「贡献的许可与署名(DCO)」。
//
// 只检查 PR 引入的新 commit(merge-base..head),不追溯仓库历史,因此对 DCO 生效前
// 的既有提交无影响。只读 git 元数据,不访问网络、不读任何私有配置或凭证。
//
// PR 上的权威门禁是 DCO GitHub App 的 check(配置见 .github/dco.yml),本脚本是提交前
// 的本地自查,判定刻意与 App 对齐或更严,好让本地通过一定意味着 App 通过。
//
// 本地用法:
// pnpm check:dco 校验 origin/main..HEAD
// node scripts/check-dco.mjs --base <ref> --head <ref>
// 在 pull_request 事件下运行时(GITHUB_EVENT_PATH 存在)自动从 payload 取
// base.sha 与 head.sha 作为范围。
import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
import { isSignOffHookInstalled } from './install-dco-hook.mjs';
// git log 的字段/记录分隔符:用 ASCII 控制字符,避免与 commit message 内容碰撞。
const FIELD_SEP = '\u001f';
const RECORD_SEP = '\u001e';
const LOG_FORMAT = ['%H', '%P', '%an', '%ae', '%cn', '%ce', '%B'].join(FIELD_SEP) + RECORD_SEP;
// 与 DCO App 的匹配器逐字对齐(dcoapp/app 的 `lib/dco.js`:
// `/^Signed-off-by: (.*) <(.*)>\s*$/gim`)。逐行匹配而不强求在 message 末尾:trailer
// 之后常见还有 Co-authored-by 等其他 trailer。
//
// 刻意不放宽这三处,它们都会造成「本地绿、PR 红」:
// - 不允许行首空白:App 的 `^Signed-off-by:` 锚在行首,缩进过的行在它眼里根本不是签名。
// - `Signed-off-by:` 后只允许一个空格:写两个空格时 App 会把多出来的空格算进 name,
// 于是 name 与 author 比不上。
// - 捕获值不 trim(见 validateCommit):App 拿原样捕获去比,`Alice ` 不等于 `Alice`。
const SIGN_OFF_LINE = /^Signed-off-by: (.*) <(.*)>\s*$/i;
// bot 地址的形状特征:dependabot 等用 `<name>[bot]@users.noreply.github.com`,
// GitHub Web UI 用 web-flow 的 noreply@github.com。
//
// **这只用于在失败输出里提示,不用于豁免。** App 判定 bot 的依据是 GitHub 账号类型
// (`author.type === "Bot"`),离线拿不到也伪造不了;而 author 邮箱谁都能设成
// `999999+not-a-real-account[bot]@users.noreply.github.com`。按邮箱豁免就等于给本地检查
// 留一个可伪造的后门,方向还是最坏的那种——「本地绿、PR 红」。所以本地一律检查,
// 只在输出里说明「若它真是 bot,PR 上的 App 会豁免」。
const BOT_EMAILS = new Set(['noreply@github.com']);
const BOT_EMAIL_SUFFIX = '[bot]@users.noreply.github.com';
// 本地默认基准。upstream/main 排在前面:从 fork 干活时 origin/main 可能领先于上游,
// 拿它当基准会把 fork 自己那些未签名的提交排除在范围外,而 PR 的真实 base 是上游。
// 这只是本地自查的启发式——真实 base 以 PR 上的 DCO check 为准,所以通过时会把实际用的
// 基准打印出来。
const DEFAULT_BASE_CANDIDATES = ['upstream/main', 'origin/main', 'main'];
const git = (args, options = {}) =>
execFileSync('git', args, { encoding: 'utf8', ...options }).trim();
export function normalizeEmail(email) {
return String(email ?? '').trim().toLowerCase();
}
export function normalizeName(name) {
return String(name ?? '').trim().toLowerCase();
}
// 邮箱形状:对齐 DCO App 用的 validator.isEmail 的默认规则。
// - local part 限定为 RFC 5322 的 atext 字符集,点分隔且不允许连续点或首尾点。
// 注意 atext 不含括号、方括号、引号等,所以 `a(b)@x.com` 会被拒——validator 也拒。
// - 域名每个 label 不能以连字符开头或结尾,不允许下划线,且必须有字母 TLD(于是 git 未配
// user.email 时自动生成的 `user@hostname` 会被拒)。
// 无法逐条复刻 validator,取舍上刻意偏严:宁可本地误报,也不要放行一个 App 会拒的地址,
// 那才会变成「本地绿、PR 红」。含方括号的 bot 邮箱(dependabot 等)同样不符合 atext,
// 于是这类提交在本地会被报出来——而 App 因为账号是 Bot 直接跳过。结论不同但方向安全
// (本地红、PR 绿),失败输出里会说明这一点。
const ATEXT = "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]";
const DOMAIN_LABEL = '[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?';
const EMAIL_LOCAL_PART = new RegExp(`^${ATEXT}+(?:\\.${ATEXT}+)*$`);
const EMAIL_DOMAIN = new RegExp(`^${DOMAIN_LABEL}(?:\\.${DOMAIN_LABEL})*\\.[A-Za-z]{2,}$`);
// validator.isEmail 的长度上限,超出即拒。整体上限单独存在:local part 与 domain 各自
// 合规、加起来仍可能超过 254。
const MAX_TOTAL = 254;
const MAX_LOCAL_PART = 64;
const MAX_DOMAIN = 254;
const MAX_DOMAIN_LABEL = 63;
export function looksLikeEmail(email) {
const value = String(email ?? '').trim();
if (value.length > MAX_TOTAL) return false;
const at = value.lastIndexOf('@');
if (at <= 0 || at === value.length - 1) return false;
const localPart = value.slice(0, at);
const domain = value.slice(at + 1);
if (localPart.length > MAX_LOCAL_PART || domain.length > MAX_DOMAIN) return false;
if (domain.split('.').some((label) => label.length > MAX_DOMAIN_LABEL)) return false;
return EMAIL_LOCAL_PART.test(localPart) && EMAIL_DOMAIN.test(domain);
}
/**
* 提取 message 里所有 Signed-off-by 行。捕获值原样保留、不 trim——App 也不 trim,
* 多出来的空白会让它与 author 比对失败,这里跟着一起失败才不会「本地绿、PR 红」。
*/
export function parseSignOffs(message) {
const signOffs = [];
for (const line of String(message ?? '').split(/\r?\n/)) {
const match = SIGN_OFF_LINE.exec(line);
if (match) signOffs.push({ name: match[1], email: match[2] });
}
return signOffs;
}
/** 只判断「地址长得像 bot」,供失败输出提示用;不构成豁免,理由见上面的注释。 */
export function looksLikeBotAddress(email) {
const normalizedEmail = normalizeEmail(email);
return BOT_EMAILS.has(normalizedEmail) || normalizedEmail.endsWith(BOT_EMAIL_SUFFIX);
}
/**
* 返回豁免原因,不豁免则返回 null。
*
* 只有 merge commit 能离线可靠判定(父提交数量),所以只豁免它。bot 提交交给 App 按账号
* 类型豁免——本地宁可多报一条,也不放过一个可伪造的身份。
*/
export function exemptReason(commit) {
if (commit.parents.length > 1) return 'merge commit';
return null;
}
/**
* 返回错误列表;空列表即通过。判定与 DCO App(dcoapp/app 的 lib/dco.js)对齐,两处
* 刻意更严——偏严只会「本地红、PR 绿」,偏宽才会「本地绿、PR 红」,后者才是要避免的:
*
* 1. 签名必须整体匹配 author 或 committer 这一个身份。App 是把 name 与 email 拆成两个
* 集合分别判断,于是 author=Alice<a@x>、committer=Bob<b@x> 时 `Alice <b@x>` 也能过,
* 尽管这个身份并不存在——这里按 name+email 成对比较。
* 2. 邮箱形状见 looksLikeEmail。
*
* 本脚本同样不识别 remediation commit(App 侧由 .github/dco.yml 开启),也是同一取舍。
* 面向贡献者的文案统一用英文。
*/
export function validateCommit(commit) {
const signOffs = parseSignOffs(commit.message);
if (signOffs.length === 0) {
return ['No Signed-off-by trailer.'];
}
// 与 App 一致:只看 author.email(缺失时回落 committer.email)。改成「两者都非法才
// 失败」会比 App 宽松,反而制造本地绿、PR 红。
const email = commit.authorEmail || commit.committerEmail;
if (!looksLikeEmail(email)) {
return [`${email} is not a valid email address.`];
}
const identities = [
{ name: normalizeName(commit.authorName), email: normalizeEmail(commit.authorEmail) },
{ name: normalizeName(commit.committerName), email: normalizeEmail(commit.committerEmail) },
];
// 签名侧只 lowercase、不 trim(App 亦然);commit 侧 trim 是安全的,git ident 本身
// 不带前后空白。两边处理方式刻意不同,正是为了让「Alice 」这种写法在本地也失败。
const matches = (signOff) =>
identities.some(
(identity) =>
identity.name === String(signOff.name).toLowerCase() &&
identity.email === String(signOff.email).toLowerCase()
);
if (signOffs.some(matches)) return [];
const got = signOffs.map((signOff) => `"${signOff.name} <${signOff.email}>"`).join(', ');
return [
`Expected a sign-off from "${commit.authorName} <${commit.authorEmail}>" or ` +
`"${commit.committerName} <${commit.committerEmail}>", got ${got}. ` +
'The name and the address have to match one of them as a whole.',
];
}
export function validateCommits(commits) {
const failures = [];
const exempted = [];
let checked = 0;
for (const commit of commits) {
const reason = exemptReason(commit);
if (reason) {
exempted.push({ commit, reason });
continue;
}
checked += 1;
const errors = validateCommit(commit);
if (errors.length > 0) failures.push({ commit, errors });
}
return { failures, exempted, checked };
}
export function parseGitLog(stdout) {
return String(stdout)
.split(RECORD_SEP)
.map((record) => record.replace(/^\r?\n/, ''))
.filter((record) => record.trim() !== '')
.map((record) => {
const [sha, parents, authorName, authorEmail, committerName, committerEmail, message] =
record.split(FIELD_SEP);
return {
sha: (sha ?? '').trim(),
parents: (parents ?? '').trim() ? parents.trim().split(/\s+/) : [],
authorName: authorName ?? '',
authorEmail: authorEmail ?? '',
committerName: committerName ?? '',
committerEmail: committerEmail ?? '',
message: message ?? '',
};
});
}
export function shortSha(sha) {
return String(sha ?? '').slice(0, 8);
}
export function subjectOf(commit) {
return String(commit.message ?? '').split(/\r?\n/, 1)[0].trim();
}
function readArg(name) {
const index = process.argv.indexOf(name);
return index !== -1 ? process.argv[index + 1] : undefined;
}
function revParse(ref) {
try {
return git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], { stdio: ['ignore', 'pipe', 'ignore'] });
} catch {
return null;
}
}
/** 解析待校验范围。返回的 start 是排除端点(start..head)。 */
function resolveRange() {
const explicitBase = readArg('--base');
const explicitHead = readArg('--head');
const eventPath = process.env.GITHUB_EVENT_PATH;
let base = explicitBase;
let head = explicitHead ?? 'HEAD';
if (!base && eventPath) {
const event = JSON.parse(readFileSync(eventPath, 'utf8'));
const pr = event.pull_request;
if (!pr) throw new Error('Event payload has no pull_request; check the workflow trigger.');
base = pr.base?.sha;
head = explicitHead ?? pr.head?.sha ?? 'HEAD';
if (!base) throw new Error('Event payload is missing pull_request.base.sha.');
}
if (!base) {
base = DEFAULT_BASE_CANDIDATES.find((candidate) => revParse(candidate));
if (!base) {
throw new Error(
`No default base ref found (${DEFAULT_BASE_CANDIDATES.join(' / ')}); pass --base <ref>.`
);
}
}
const baseSha = revParse(base);
if (!baseSha) throw new Error(`Cannot resolve base ref: ${base} (fetch it first if missing).`);
const headSha = revParse(head);
if (!headSha) throw new Error(`Cannot resolve head ref: ${head}.`);
// 用 merge-base 而不是 base 本身:base 分支在 PR 开着期间会前进,直接用
// base.sha..head 会把 base 侧的他人提交也算进来,造成误报。
let start = baseSha;
try {
start = git(['merge-base', baseSha, headSha]);
} catch {
// 没有共同祖先(例如孤立分支)时退回 base 本身。
}
return { start, head: headSha, baseRef: base };
}
function reportFailures({ failures, start }) {
const plural = failures.length === 1 ? 'commit' : 'commits';
console.error(`DCO check failed: ${failures.length} ${plural} without a valid Signed-off-by.\n`);
for (const { commit, errors } of failures) {
console.error(`- ${shortSha(commit.sha)} ${subjectOf(commit)}`);
for (const error of errors) console.error(` ${error}`);
// 地址像 bot 时给一句解释,免得有人以为门禁在为难 dependabot:真 bot 由 App 按 GitHub
// 账号类型豁免,而账号类型离线取不到,所以本地照常报。
if (looksLikeBotAddress(commit.authorEmail)) {
console.error(' This looks like a bot address. Bot commits are exempt on the pull request,');
console.error(' where the DCO App can check the GitHub account type — this check cannot,');
console.error(' so it reports them rather than trusting a forgeable address.');
}
}
// 用完整 sha:短 sha 在大仓里可能歧义,让复制粘贴的命令直接失败。
console.error('\nHow to fix, on your pull request branch:');
console.error(' most recent commit only: git commit --amend -s --no-edit');
console.error(` several commits: git rebase --signoff ${start}`);
console.error(' then update the PR: git push --force-with-lease');
console.error('\nTo stop forgetting, commit with `git commit -s`, or install the hook shipped');
console.error('with this repository once: `pnpm dco:install-hook` (.githooks/prepare-commit-msg).');
console.error('The DCO file at the repository root states what the sign-off certifies;');
console.error('CONTRIBUTING.en.md explains the requirement in full.');
}
function main() {
const { start, head, baseRef } = resolveRange();
const stdout = execFileSync('git', ['log', `--format=${LOG_FORMAT}`, `${start}..${head}`], {
encoding: 'utf8',
maxBuffer: 64 * 1024 * 1024,
});
const commits = parseGitLog(stdout);
if (commits.length === 0) {
console.log(`No new commits in ${shortSha(start)}..${shortSha(head)}; nothing to check.`);
return;
}
const { failures, exempted, checked } = validateCommits(commits);
if (failures.length > 0) {
reportFailures({ failures, start });
process.exit(1);
}
const exemptNote = exempted.length > 0 ? `, ${exempted.length} exempt (merge commits)` : '';
console.log(
`DCO check passed: ${checked} ${checked === 1 ? 'commit' : 'commits'} signed off${exemptNote} ` +
`— range ${shortSha(start)}..${shortSha(head)} (base ${baseRef}).`
);
if (!process.env.GITHUB_EVENT_PATH && !isSignOffHookInstalled()) {
console.log('Tip: `pnpm dco:install-hook` signs off local commits automatically.');
}
}
// 仅作为入口执行时运行;被 import 时只导出纯函数,便于单测。
const isDirectRun = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isDirectRun) {
try {
main();
} catch (error) {
console.error(String(error?.message ?? error));
process.exit(1);
}
}