根治Repository checks本地漏检
Project CI / Repository checks (push) Successful in 1m18s
Project CI / Frontend tests (push) Successful in 3m1s
Project CI / Backend tests (push) Successful in 4m17s
Project CI / Native shell tests (push) Failing after 12m32s

修复 Agent 失败展示变更中的 import 排序错误
统一 CI 与 master pre-push 的 Repository checks 入口
让 staged JS 和 TS 自动执行 ESLint 修复与 Prettier
补充部分暂存、忽略文件和待推 SHA 回归测试
同步分支保护与本地门禁流程文档
This commit is contained in:
2026-08-12 22:06:16 +08:00
parent 794f3d4cf8
commit fd423770d8
14 changed files with 393 additions and 121 deletions
+2 -17
View File
@@ -69,23 +69,8 @@ jobs:
- name: Install npm dependencies
run: bash scripts/ci-npm-ci-with-retry.sh
- name: Run repository lint gates
run: npm run lint
- name: Build web applications
run: npm run build
- name: Validate content data
run: npm run check:content
- name: Check committed whitespace
shell: bash
run: |
set -euo pipefail
base_ref="${SPACETIME_SCHEMA_BASE_REF:-}"
test -n "${base_ref}"
git cat-file -e "${base_ref}^{commit}"
git diff --check "${base_ref}"...HEAD
- name: Run repository checks
run: npm run check:repository-ci
frontend-tests:
name: Frontend tests
+1
View File
@@ -0,0 +1 @@
npm run check:pre-push-master -- "$@"
@@ -37,9 +37,9 @@ import {
formatAgentRuntimePlanStep,
formatAgentRuntimeTaskQueue,
isAgentRuntimeTerminalState,
projectProfessionalAgentLabel,
projectRuntimeVisibleCurrentWork,
projectRuntimeVisibleError,
projectProfessionalAgentLabel,
taskRowsFromManifest,
} from '../agent-runtime';
import {
@@ -13,9 +13,9 @@ import type {
PendingUiConfirmation,
} from '../../app/types';
import {
ProjectSupervisorRuntimePanel,
projectProfessionalAgentLabel,
projectRuntimeVisibleError,
ProjectSupervisorRuntimePanel,
projectSupervisorVisibleConversationText,
projectWorkspaceStatusForDisplay,
} from '../agent-runtime';
@@ -1,5 +1,6 @@
import { describe, expect, test, vi } from 'vitest';
import { createGameCreationAppManifest } from '../../../packages/shared/src/contracts/gameCreationApp';
import type {
AgentRuntimeResponseStream,
AgentRuntimeResult,
@@ -9,10 +10,10 @@ import type {
LocalConversationMessageRecord,
} from '../src/app/types';
import {
formatAgentRuntimeEvent,
formatAgentRecentRuntimeTask,
isAgentRuntimeTerminalState,
agentRuntimeConversationStatus,
formatAgentRecentRuntimeTask,
formatAgentRuntimeEvent,
isAgentRuntimeTerminalState,
mergeGameChatRuntimeResponseMessagesIntoHistory,
mergeProjectSupervisorConversation,
MUD_POINT_INSUFFICIENT_INTERRUPTION_MESSAGE,
@@ -28,7 +29,6 @@ import {
deriveAgentStatusCards,
formatAgentCardRuntimeStatus,
} from '../src/features/project-summary/agentPresentation';
import { createGameCreationAppManifest } from '../../../packages/shared/src/contracts/gameCreationApp';
describe('普通用户工作区状态', () => {
test('用项目名称替代 Unix 和 Windows 绝对路径', () => {
@@ -1,5 +1,12 @@
# 决策记录
## 2026-08-12 Repository checks 采用 CI 与本地共用的单一门禁入口
- 背景:master run 1037 的 Backend/Frontend 已通过,但 `Repository checks` 因 3 个 `simple-import-sort/imports` 错误失败。原 pre-commit 只运行 PrettierPrettier 不处理 ESLint import 排序;推送前又未运行完整仓库 lint,因此本地与 CI 的覆盖范围长期存在漂移。
- 决策:`npm run check:repository-ci` 成为 Repository checks 唯一仓库入口,统一执行 lint、生产构建、内容检查和基线到候选提交的空白差异检查;Gitea workflow 与 master pre-push 只调用该入口。pre-push 必须验证待推 master SHA 是当前 `HEAD` 且已跟踪工作树干净,无法确认候选内容时失败关闭;feature 分支不运行该重门禁。
- 提交门禁:lint-staged 对 staged JS/TS 先运行按 ESLint 配置过滤 ignored 文件的 autofix wrapper,再运行 Prettier。回归测试覆盖 import 排序、部分暂存恢复、ignored 文件、feature push 跳过、master push 参数绑定,以及 workflow/hook 共用入口。
- 权威边界:本地 hook 可被 `--no-verify` 绕过,不能从制度上保证 master 永远不红。服务端根治要求禁止日常直接 push master,统一走 PR,并要求当前 head 的 Repository/Frontend/Backend/Native 四项检查全部成功后合并;紧急白名单只能最小化保留。
## 2026-08-12 Agent 失败原因使用稳定分类贯穿 Runtime 与正式展示面
- 背景:Codex app-server 的 failed turn 已携带 `turn.error.codexErrorInfo`,但适配器曾丢弃该字段并写固定失败句;Runtime、事件 `publicText`、最近任务、game-chat 阶段记录和多个 Agent 卡片又各自用固定文案覆盖已有安全原因。自主构建 final-reply 已形成确定性完成文案时还对任意错误 fallback 成成功,导致鉴权、额度、上下文、策略、sandbox、配置或网络失败可能被伪装为完成。
@@ -611,13 +611,15 @@ npm run check:server-rs-ddd
- 页面交互 smoke
- 移动端视口检查
### 提交前 TypeScript 自动格式化
### 提交与 master 推送前自动门禁
仓库级 Git `pre-commit` hook 通过 `lint-staged`,只对当前已暂存的 `*.ts``*.tsx` 文件运行 Prettier 自动格式化,并把格式化结果更新到本次提交的暂存区;未暂存的其他文件不进入格式化范围。格式化或暂存恢复失败时提交会中止,应先处理失败原因并重新检查 staged diff,不能等 CI 再暴露格式问题。
仓库级 Git `pre-commit` hook 通过 `lint-staged`,只对当前已暂存的 `*.js``*.mjs``*.cjs``*.ts``*.tsx` 文件依次运行 ESLint autofix 和 Prettier,并把修复结果更新到本次提交的暂存区;ESLint wrapper 会按仓库配置过滤 ignored 文件,避免 ignored warning 与 `--max-warnings 0` 组合造成误阻塞。未暂存的其他文件不进入处理范围,修复或暂存恢复失败时提交会中止,应先处理失败原因并重新检查 staged diff,不能等 CI 再暴露 import 排序或格式问题。
部分暂存同一 TS / TSX 文件时,`lint-staged` 会临时隐藏该文件未暂存的改动,以暂存快照执行格式化,随后恢复未暂存内容。因此提交前后都应分别检查 `git diff --cached``git diff`,确认格式化后的暂存内容属于本次提交,未暂存工作没有被误带入;若恢复产生冲突,先人工整理暂存边界再重新提交。
部分暂存同一 JS / TS 文件时,`lint-staged` 会临时隐藏该文件未暂存的改动,以暂存快照执行修复和格式化,随后恢复未暂存内容。因此提交前后都应分别检查 `git diff --cached``git diff`,确认修复后的暂存内容属于本次提交,未暂存工作没有被误带入;若恢复产生冲突,先人工整理暂存边界再重新提交。
`git commit --no-verify` 会绕过该 hook,只允许在已明确原因的紧急场景使用。绕过时仍须对本次暂存的 TS / TSX 文件手动执行等价的 Prettier 格式化、重新暂存并核对 staged diff`--no-verify` 不代表可以跳过格式化或其他提交门禁
`Repository checks` 的唯一仓库入口是 `npm run check:repository-ci`,依次运行 `npm run lint`、生产构建、内容检查和基线到候选提交的空白差异检查。Gitea `Repository checks` job 和本地 master `pre-push` 必须共同调用该入口,禁止各自复制或删减子命令;本地 hook 还会确认待推 master SHA 等于当前 `HEAD` 且已跟踪工作树干净,无法确认时失败关闭。普通 feature 分支 push 不运行这条重门禁,进入 master 前仍以 PR required checks 为权威
`git commit --no-verify``git push --no-verify` 都会绕过本地 hook,只允许在已明确原因的紧急场景使用;绕过不代表可以跳过等价门禁。真正阻止红提交进入 master 依赖 Gitea 分支保护:禁止日常直接 push,统一经 PR,并要求 `Repository checks``Frontend tests``Backend tests``Native shell tests` 四个当前 head context 全部成功后合并。本地 hook 只负责提前反馈,不能替代服务端分支保护。
前端原则:
@@ -236,7 +236,7 @@ npm run check
仓库级 Gitea Actions 工作流固定为 `.gitea/workflows/project-ci.yml`,在向 `master``codex/ai-game-creator-app` 推送、创建或更新 PR,以及手工触发时运行。工作流拆成四个必须通过的 job:
- `Repository checks`:执行 `npm run lint`、主站与后台生产构建、内容数据检查和提交差异空白检查。
- `Repository checks`调用唯一入口 `npm run check:repository-ci`执行 `npm run lint`、主站与后台生产构建、内容数据检查和提交差异空白检查。本地 master `pre-push` 复用同一入口,禁止在 workflow 与 hook 中维护两份近似命令。
- `Frontend tests`:按根 lockfile 与 `apps/ai-game-creator-shell/package-lock.json` 分别执行干净的 `npm ci`,再独立执行根 `npm run test``npm run bgfilter-worker:smoke-test``npm run check:production-health-patrol``npm run check:production-api-release``npm run check:production-api-deploy`,让 Vitest、Node test smoke harness 及不依赖真实服务的生产巡检 / 发布 / 部署行为 fixture 在 Gitea job 中持续执行;其中 `.test.mjs` 使用 Node test runner,不依赖 Vitest 的 `scripts/**/*.test.ts` 收集规则。
- `Backend tests`:先对 `server-rs/Cargo.lock` 执行带 5 次整命令级有界重试的 `cargo fetch --locked`,再执行 `npm run check:server-rs-ddd``cargo test --locked --workspace --no-fail-fast``api-server --all-targets` 编译和 `spacetime-module` 编译;依赖准备必须位于会触发 Cargo build 的 DDD / 产物边界门禁之前,避免锁新增依赖未命中镜像缓存时绕过既有下载重试。runner 安装 `ffmpeg`,避免视频抽帧测试因工具缺失提前返回。依赖真实服务或密钥的测试必须显式 `ignored`,不能让普通 PR job访问现场环境。
- `Native shell tests`:按根 lockfile 与 AI 游戏创作壳独立 lockfile 安装依赖后执行 `npm run check:native-shells`,覆盖微信壳、Expo 和 Tauri 的完整验收,并确认桌面壳与 AI 游戏创作壳的 `Cargo.lock` 都没有被构建过程改写。`codex/ai-game-creator-app` 分支的同名脚本还会执行 `npm run ai-game-creator-shell:check` 和 AI 游戏创作壳 release build smoke;共享 Agent Runtime 后台锁 suite 固定 `--test-threads=1`,不能用并行偶发失败后的逐项通过替代整套稳定门禁。
@@ -268,6 +268,8 @@ bash scripts/gitea-ci-job-image.sh load-runner
workflow 首次成功运行后,在 Gitea `master` 分支保护中把 `Project CI / Repository checks (pull_request)``Project CI / Frontend tests (pull_request)``Project CI / Backend tests (pull_request)``Project CI / Native shell tests (pull_request)` 四个完整 context 都设为合并必需检查,并从最近一周已上报 context 表复核名称后再保存。不能只填裸 job 名,否则无法匹配 Gitea 实际上报的 `<workflow> / <job> (<event>)`。只提交 workflow 文件不会自动创建 runner,也不会自动修改分支保护;如果 Actions 长时间停留在等待状态,先到仓库或组织的 Actions runner 页面确认存在在线、带 `genarrative-ci` 标签的 runner,再检查精确 Image ID 是否已装入内层 Docker。
master 日常交付必须禁止直接 push,只允许经 PR 在当前 head 的四个 required context 全绿后合并;本地 `pre-commit` 的 staged ESLint/Prettier 和 master `pre-push` 的 Repository checks parity 只用于提前发现问题,可被 `--no-verify` 绕过,不能充当服务端权威门禁。紧急直推白名单如需保留,应按人员和时限最小化,并要求执行同一 `npm run check:repository-ci <base> <head>` 后回读 push CI。
视觉小说负向扫描与验收门禁:
```bash
+8 -2
View File
@@ -40,7 +40,9 @@
"preview": "node scripts/vite-cli.mjs preview",
"clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
"check:encoding": "node scripts/check-encoding.mjs",
"check:pre-commit-format": "node --test scripts/pre-commit-format.test.mjs",
"check:git-hooks": "node --test scripts/git-hooks.test.mjs",
"check:pre-commit-format": "npm run check:git-hooks",
"check:repository-ci": "bash scripts/check-repository-ci.sh",
"check:rustfmt": "cargo fmt --all --manifest-path server-rs/Cargo.toml -- --check",
"check:spacetime-schema": "node scripts/check-spacetime-schema-guard.mjs",
"check:production-ops": "node scripts/check-production-ops-guardrails.mjs",
@@ -96,6 +98,7 @@
"format": "prettier --write .",
"format:check": "prettier --check .",
"format:staged": "lint-staged",
"check:pre-push-master": "bash scripts/pre-push-master.sh",
"test": "vitest run",
"test:watch": "vitest",
"container:init": "node scripts/container-compose.mjs init",
@@ -210,7 +213,10 @@
"zustand": "^5.0.14"
},
"lint-staged": {
"*.{ts,tsx}": "prettier --write"
"*.{js,mjs,cjs,ts,tsx}": [
"node scripts/lint-staged-eslint.mjs",
"prettier --write"
]
},
"devDependencies": {
"@colbymchenry/codegraph": "^0.8.0",
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
set -euo pipefail
base_ref="${SPACETIME_SCHEMA_BASE_REF:-${1:-}}"
head_ref="${REPOSITORY_CI_HEAD_REF:-${2:-HEAD}}"
if [[ -z "${base_ref}" ]]; then
echo '[repository-ci] 缺少比较基线;请设置 SPACETIME_SCHEMA_BASE_REF 或传入第一个参数。' >&2
exit 1
fi
git cat-file -e "${base_ref}^{commit}" 2>/dev/null || {
echo "[repository-ci] 比较基线不可用: ${base_ref}" >&2
exit 1
}
git cat-file -e "${head_ref}^{commit}" 2>/dev/null || {
echo "[repository-ci] 待检查提交不可用: ${head_ref}" >&2
exit 1
}
echo "[repository-ci] base=${base_ref} head=$(git rev-parse "${head_ref}")"
SPACETIME_SCHEMA_BASE_REF="${base_ref}" npm run lint
npm run build
npm run check:content
git diff --check "${base_ref}"..."${head_ref}"
+259
View File
@@ -0,0 +1,259 @@
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import {
chmodSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { delimiter, dirname, join, resolve } from 'node:path';
import { test } from 'node:test';
import { fileURLToPath } from 'node:url';
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const packageJson = JSON.parse(
readFileSync(join(repoRoot, 'package.json'), 'utf8'),
);
test('pre-commit hook fixes staged imports and formatting without swallowing unstaged work', () => {
assert.equal(packageJson.scripts.prepare, 'husky');
assert.equal(packageJson.scripts['format:staged'], 'lint-staged');
assert.deepEqual(packageJson['lint-staged'], {
'*.{js,mjs,cjs,ts,tsx}': [
'node scripts/lint-staged-eslint.mjs',
'prettier --write',
],
});
assert.equal(
readFileSync(join(repoRoot, '.husky', 'pre-commit'), 'utf8'),
'npm run format:staged\n',
);
const tempRepo = mkdtempSync(join(tmpdir(), 'genarrative-git-hooks-'));
try {
git(tempRepo, 'init', '--quiet');
git(tempRepo, 'config', 'user.email', 'git-hooks-test@example.invalid');
git(tempRepo, 'config', 'user.name', 'Git Hooks Test');
writeFileSync(
join(tempRepo, '.eslintrc.cjs'),
`module.exports = ${JSON.stringify({
root: true,
ignorePatterns: ['ignored/**'],
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
plugins: ['simple-import-sort'],
rules: { 'simple-import-sort/imports': 'error' },
})};\n`,
);
writeFileSync(
join(tempRepo, '.prettierrc.json'),
JSON.stringify({ singleQuote: true, semi: true, trailingComma: 'all' }),
);
symlinkSync(
join(repoRoot, 'node_modules'),
join(tempRepo, 'node_modules'),
'dir',
);
const sourcePath = join(tempRepo, 'sample.ts');
const partialPath = join(tempRepo, 'partial.ts');
const ignoredDir = join(tempRepo, 'ignored');
const ignoredPath = join(ignoredDir, 'legacy.ts');
mkdirSync(ignoredDir);
writeFileSync(
sourcePath,
"import { alpha } from './alpha';\nimport { zebra } from './zebra';\n\nvoid alpha;\nvoid zebra;\n",
);
writeFileSync(partialPath, 'const original = 1;\nconst keep = 2;\n');
writeFileSync(
ignoredPath,
"import { zebra } from './zebra';\nimport { alpha } from './alpha';\nvoid zebra; void alpha;\n",
);
git(
tempRepo,
'add',
'sample.ts',
'partial.ts',
'ignored/legacy.ts',
'.eslintrc.cjs',
'.prettierrc.json',
);
git(
tempRepo,
'-c',
'commit.gpgsign=false',
'commit',
'--quiet',
'-m',
'baseline',
);
writeFileSync(
sourcePath,
"import { zebra } from './zebra';\nimport { alpha } from './alpha';\nconst staged={value:1}\nvoid zebra; void alpha; void staged;\n",
);
writeFileSync(partialPath, 'const original={value:1}\nconst keep = 2;\n');
writeFileSync(
ignoredPath,
"import { zebra } from './zebra';\nimport { alpha } from './alpha';\nvoid zebra; void alpha;\n// staged ignored change\n",
);
git(tempRepo, 'add', 'sample.ts', 'partial.ts', 'ignored/legacy.ts');
writeFileSync(
partialPath,
'const original={value:1}\nconst keep={unstaged:true}\n',
);
const lintStagedConfig = {
'*.{js,mjs,cjs,ts,tsx}': [
`node ${JSON.stringify(join(repoRoot, 'scripts', 'lint-staged-eslint.mjs'))}`,
'prettier --write',
],
};
const lintStaged = spawnSync(
process.execPath,
[
join(repoRoot, 'node_modules', 'lint-staged', 'bin', 'lint-staged.js'),
'--config',
'-',
],
{
cwd: tempRepo,
encoding: 'utf8',
env: {
...process.env,
PATH: `${join(repoRoot, 'node_modules', '.bin')}${delimiter}${process.env.PATH ?? ''}`,
},
input: JSON.stringify(lintStagedConfig),
},
);
assert.equal(
lintStaged.status,
0,
`${lintStaged.stdout ?? ''}${lintStaged.stderr ?? ''}`,
);
assert.equal(
git(tempRepo, 'show', ':sample.ts'),
"import { alpha } from './alpha';\nimport { zebra } from './zebra';\nconst staged = { value: 1 };\nvoid zebra;\nvoid alpha;\nvoid staged;\n",
);
assert.equal(
git(tempRepo, 'show', ':partial.ts'),
'const original = { value: 1 };\nconst keep = 2;\n',
);
assert.equal(
readFileSync(partialPath, 'utf8'),
'const original = { value: 1 };\nconst keep={unstaged:true}\n',
);
assert.equal(
git(tempRepo, 'show', ':ignored/legacy.ts'),
"import { zebra } from './zebra';\nimport { alpha } from './alpha';\nvoid zebra;\nvoid alpha;\n// staged ignored change\n",
);
} finally {
rmSync(tempRepo, { force: true, recursive: true });
}
});
test('pre-push runs repository parity only for master updates', () => {
const tempDir = mkdtempSync(join(tmpdir(), 'genarrative-pre-push-'));
try {
const binDir = join(tempDir, 'bin');
mkdirSync(binDir);
const npmLog = join(tempDir, 'npm.log');
const fakeNpm = join(binDir, 'npm');
const fakeGit = join(binDir, 'git');
writeFileSync(
fakeNpm,
`#!/usr/bin/env bash\nprintf '%s\\n' "$*" >> "${npmLog}"\n`,
);
chmodSync(fakeNpm, 0o755);
writeFileSync(
fakeGit,
'#!/usr/bin/env bash\n' +
'if [[ "$1" == "rev-parse" && "$2" == "HEAD" ]]; then\n' +
' printf "%s\\n" "1111111111111111111111111111111111111111"\n' +
' exit 0\n' +
'fi\n' +
'if [[ "$1" == "diff" ]]; then exit 0; fi\n' +
'exit 1\n',
);
chmodSync(fakeGit, 0o755);
const env = {
...process.env,
PATH: `${binDir}${delimiter}${process.env.PATH ?? ''}`,
};
const hook = join(repoRoot, 'scripts', 'pre-push-master.sh');
const featurePush = spawnSync('bash', [hook, 'origin', 'example.invalid'], {
cwd: repoRoot,
encoding: 'utf8',
env,
input:
'refs/heads/feature 1111111111111111111111111111111111111111 refs/heads/feature 2222222222222222222222222222222222222222\n',
});
assert.equal(featurePush.status, 0, featurePush.stderr);
assert.equal(readFileOrEmpty(npmLog), '');
const masterPush = spawnSync('bash', [hook, 'origin', 'example.invalid'], {
cwd: repoRoot,
encoding: 'utf8',
env,
input:
'refs/heads/master 1111111111111111111111111111111111111111 refs/heads/master 2222222222222222222222222222222222222222\n',
});
assert.equal(masterPush.status, 0, masterPush.stderr);
assert.equal(
readFileSync(npmLog, 'utf8'),
'run check:repository-ci -- 2222222222222222222222222222222222222222 1111111111111111111111111111111111111111\n',
);
} finally {
rmSync(tempDir, { force: true, recursive: true });
}
});
test('Gitea Repository checks and master pre-push share the same repository command', () => {
const workflow = readFileSync(
join(repoRoot, '.gitea', 'workflows', 'project-ci.yml'),
'utf8',
);
const repositoryScript = readFileSync(
join(repoRoot, 'scripts', 'check-repository-ci.sh'),
'utf8',
);
const prePushHook = readFileSync(
join(repoRoot, '.husky', 'pre-push'),
'utf8',
);
assert.match(workflow, /run: npm run check:repository-ci/u);
assert.equal(
(workflow.match(/npm run check:repository-ci/gu) ?? []).length,
1,
);
assert.match(repositoryScript, /npm run lint/u);
assert.match(
repositoryScript,
/SPACETIME_SCHEMA_BASE_REF="\$\{base_ref\}" npm run lint/u,
);
assert.match(repositoryScript, /npm run build/u);
assert.match(repositoryScript, /npm run check:content/u);
assert.match(repositoryScript, /git diff --check/u);
assert.equal(prePushHook, 'npm run check:pre-push-master -- "$@"\n');
});
function readFileOrEmpty(path) {
try {
return readFileSync(path, 'utf8');
} catch (error) {
if (error?.code === 'ENOENT') {
return '';
}
throw error;
}
}
function git(cwd, ...args) {
return execFileSync('git', args, { cwd, encoding: 'utf8' });
}
+34
View File
@@ -0,0 +1,34 @@
import process from 'node:process';
import { ESLint } from 'eslint';
const eslint = new ESLint({ fix: true });
const candidates = [];
for (const filePath of process.argv.slice(2)) {
if (!(await eslint.isPathIgnored(filePath))) {
candidates.push(filePath);
}
}
if (candidates.length === 0) {
process.exit(0);
}
const results = await eslint.lintFiles(candidates);
await ESLint.outputFixes(results);
const formatter = await eslint.loadFormatter('stylish');
const output = formatter.format(results);
if (output) {
process.stderr.write(output);
}
const errorCount = results.reduce((sum, result) => sum + result.errorCount, 0);
const warningCount = results.reduce(
(sum, result) => sum + result.warningCount,
0,
);
if (errorCount > 0 || warningCount > 0) {
process.exitCode = 1;
}
-91
View File
@@ -1,91 +0,0 @@
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { delimiter, dirname, join, resolve } from 'node:path';
import { test } from 'node:test';
import { fileURLToPath } from 'node:url';
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const packageJson = JSON.parse(
readFileSync(join(repoRoot, 'package.json'), 'utf8'),
);
test('pre-commit hook 仅格式化暂存的 TypeScript 快照', () => {
assert.equal(packageJson.scripts.prepare, 'husky');
assert.equal(packageJson.scripts['format:staged'], 'lint-staged');
assert.deepEqual(packageJson['lint-staged'], {
'*.{ts,tsx}': 'prettier --write',
});
assert.equal(
readFileSync(join(repoRoot, '.husky', 'pre-commit'), 'utf8'),
'npm run format:staged\n',
);
const tempRepo = mkdtempSync(
join(tmpdir(), 'genarrative-pre-commit-format-'),
);
try {
git(tempRepo, 'init', '--quiet');
git(tempRepo, 'config', 'user.email', 'pre-commit-test@example.invalid');
git(tempRepo, 'config', 'user.name', 'Pre-commit Test');
const sourcePath = join(tempRepo, 'sample.ts');
writeFileSync(sourcePath, 'const original = 1;\nconst keep = 2;\n');
git(tempRepo, 'add', 'sample.ts');
git(
tempRepo,
'-c',
'commit.gpgsign=false',
'commit',
'--quiet',
'-m',
'baseline',
);
writeFileSync(sourcePath, 'const original={value:1}\nconst keep = 2;\n');
git(tempRepo, 'add', 'sample.ts');
writeFileSync(
sourcePath,
'const original={value:1}\nconst keep={unstaged:true}\n',
);
const lintStaged = spawnSync(
process.execPath,
[
join(repoRoot, 'node_modules', 'lint-staged', 'bin', 'lint-staged.js'),
'--config',
'-',
],
{
cwd: tempRepo,
encoding: 'utf8',
env: {
...process.env,
PATH: `${join(repoRoot, 'node_modules', '.bin')}${delimiter}${process.env.PATH ?? ''}`,
},
input: JSON.stringify(packageJson['lint-staged']),
},
);
assert.equal(
lintStaged.status,
0,
`${lintStaged.stdout ?? ''}${lintStaged.stderr ?? ''}`,
);
assert.equal(
git(tempRepo, 'show', ':sample.ts'),
'const original = { value: 1 };\nconst keep = 2;\n',
);
assert.equal(
readFileSync(sourcePath, 'utf8'),
'const original = { value: 1 };\nconst keep={unstaged:true}\n',
);
} finally {
rmSync(tempRepo, { force: true, recursive: true });
}
});
function git(cwd, ...args) {
return execFileSync('git', args, { cwd, encoding: 'utf8' });
}
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
set -euo pipefail
remote_name="${1:-origin}"
remote_url="${2:-}"
master_update=false
master_local_sha=''
master_remote_sha=''
while read -r local_ref local_sha remote_ref remote_sha; do
if [[ "${remote_ref}" == 'refs/heads/master' && "${local_sha}" != '0000000000000000000000000000000000000000' ]]; then
master_update=true
master_local_sha="${local_sha}"
master_remote_sha="${remote_sha}"
fi
done
if [[ "${master_update}" != true ]]; then
exit 0
fi
if [[ -z "${master_remote_sha}" || "${master_remote_sha}" == '0000000000000000000000000000000000000000' ]]; then
master_remote_sha="$(git rev-parse "refs/remotes/${remote_name}/master" 2>/dev/null || true)"
fi
if [[ -z "${master_remote_sha}" ]]; then
echo "[pre-push] 无法确定 ${remote_name}/master 比较基线;remote=${remote_url:-unknown}" >&2
exit 1
fi
if [[ "$(git rev-parse HEAD)" != "${master_local_sha}" ]]; then
echo '[pre-push] master 待推提交不是当前 HEAD,无法对候选内容执行可靠门禁。' >&2
exit 1
fi
if ! git diff --quiet || ! git diff --cached --quiet; then
echo '[pre-push] 工作树或暂存区存在已跟踪改动,无法保证检查内容与 master 待推提交一致。' >&2
exit 1
fi
echo "[pre-push] 推送 master,执行 Repository checksbase=${master_remote_sha}"
npm run check:repository-ci -- "${master_remote_sha}" "${master_local_sha}"