gatelight 0.18.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,233 @@
1
+ // eslint 生效的规则:对仓库里每个代码文件,用项目自己装的 eslint 的程序接口(ESLint 的 calculateConfigForFile、isPathIgnored)
2
+ // 算它实际用的规则,分叉点那一版和现在比(eslint 的配置是代码,读文件读不出规则)。路径都传绝对路径:相对路径会被当成忽略。
3
+ // 每个文件都算,不挑代表文件:按目录加的覆盖、忽略,挑代表文件会漏。实测 1500 个文件 0.3 秒。
4
+ // 算放松的:规则没了、关了、error 降成 warn;上限类规则(行数、复杂度、嵌套、参数)数字调大;别的规则改了参数(判断不了方向);
5
+ // 文件变成不被 lint(被忽略、配置不再覆盖它);reportUnusedDisableDirectives 降级或关掉。新加规则、调严的不算。
6
+ // 只比两边都有的文件:这次新加的文件没有"原来"。
7
+
8
+ import { createRequire } from 'node:module'
9
+ import { dirname, join } from 'node:path'
10
+ import { pathToFileURL } from 'node:url'
11
+ import type { ConfirmItem } from '../base/confirm.ts'
12
+
13
+ /** 一个文件生效的规则;不被 lint(被忽略、配置没覆盖它)时是 undefined。 */
14
+ export interface Effective {
15
+ /** 规则名 → [级别 0/1/2, ...参数]。 */
16
+ rules: Record<string, unknown[]>
17
+ /** 没用的 eslint-disable 注释报不报:0 关、1 警告、2 报错。 */
18
+ unusedDirectives: number
19
+ }
20
+
21
+ /** 文件(相对仓库根目录)→ 生效的规则。 */
22
+ export type FileRules = Map<string, Effective | undefined>
23
+
24
+ /** eslint 查的代码文件。 */
25
+ export const isCode = (path: string): boolean => /\.[cm]?[jt]sx?$/.test(path)
26
+
27
+ interface EslintInstance {
28
+ isPathIgnored(path: string): Promise<boolean>
29
+ calculateConfigForFile(path: string): Promise<{ rules?: Record<string, unknown>; linterOptions?: { reportUnusedDisableDirectives?: unknown } } | undefined>
30
+ }
31
+ type EslintClass = new (options: { cwd: string; overrideConfigFile: string }) => EslintInstance
32
+
33
+ /** 项目自己装的 eslint:从工作区里配置文件所在的目录往上找(根目录装的也找得到)。找不到时抛错。 */
34
+ export async function loadEslint(root: string, config: string): Promise<EslintClass> {
35
+ const require = createRequire(join(root, dirname(config), 'noop.js'))
36
+ let entry: string
37
+ try {
38
+ entry = require.resolve('eslint')
39
+ } catch {
40
+ throw new Error('项目里没装 eslint(从配置文件所在的目录往上找不到),先装好依赖')
41
+ }
42
+ const module = (await import(pathToFileURL(entry).href)) as { ESLint?: EslintClass }
43
+ if (typeof module.ESLint !== 'function') throw new Error(`${entry} 里没有 ESLint 的程序接口`)
44
+ return module.ESLint
45
+ }
46
+
47
+ /** 级别写法统一成数字。 */
48
+ function level(value: unknown): number {
49
+ if (value === 'error' || value === 2) return 2
50
+ if (value === 'warn' || value === 1) return 1
51
+ if (value === true) return 2
52
+ return 0
53
+ }
54
+
55
+ /** 在 tree(仓库或分叉点的临时 worktree)里算这些文件(相对 tree)生效的规则。算不出来时抛错。 */
56
+ export async function fileRules(eslint: EslintClass, tree: string, config: string, files: string[]): Promise<FileRules> {
57
+ const instance = new eslint({ cwd: tree, overrideConfigFile: join(tree, config) })
58
+ const result: FileRules = new Map()
59
+ for (const file of files) {
60
+ const path = join(tree, file)
61
+ if (await instance.isPathIgnored(path)) {
62
+ result.set(file, undefined)
63
+ continue
64
+ }
65
+ const computed = await instance.calculateConfigForFile(path)
66
+ if (!computed) {
67
+ result.set(file, undefined)
68
+ continue
69
+ }
70
+ const rules: Record<string, unknown[]> = {}
71
+ for (const [name, setting] of Object.entries(computed.rules ?? {})) {
72
+ const [severity, ...options] = Array.isArray(setting) ? setting : [setting]
73
+ rules[name] = [level(severity), ...options]
74
+ }
75
+ result.set(file, { rules, unusedDirectives: level(computed.linterOptions?.reportUnusedDisableDirectives) })
76
+ }
77
+ return result
78
+ }
79
+
80
+ /** 键按字母排的 JSON:参数一样、写的顺序不同算一样。 */
81
+ export function stable(value: unknown): string {
82
+ return JSON.stringify(value, (_key, item: unknown) =>
83
+ typeof item === 'object' && item !== null && !Array.isArray(item)
84
+ ? Object.fromEntries(Object.entries(item as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
85
+ : item,
86
+ )
87
+ }
88
+
89
+ /** 上限类规则:数字越大越松。what 是白话的名字,unit 是单位,then 是调大以后意味着什么;fallback 是不写数字时规则自己的默认值。 */
90
+ const LIMITS: Record<string, { what: string; unit: string; then: string; fallback: number }> = {
91
+ 'max-lines': { what: '单个文件的行数上限', unit: '行', then: '以后一个文件可以写得更长,更难读', fallback: 300 },
92
+ 'max-lines-per-function': { what: '函数长度上限', unit: '行', then: '以后一个函数可以写得更长,更难读', fallback: 50 },
93
+ complexity: { what: '函数复杂度上限(分支的多少)', unit: '', then: '以后一个函数里可以有更多分支,更难读、更难测', fallback: 20 },
94
+ 'max-depth': { what: '代码嵌套层数上限', unit: '层', then: '以后代码可以嵌套得更深,更难读', fallback: 4 },
95
+ 'max-params': { what: '函数参数个数上限', unit: '个', then: '以后函数可以带更多参数,更难用对', fallback: 3 },
96
+ 'max-nested-callbacks': { what: '回调嵌套层数上限', unit: '层', then: '以后回调可以套得更深,更难读', fallback: 10 },
97
+ }
98
+
99
+ /** 常见规则的白话说明:弹窗给用户看,用户不认得规则名。没列的只写规则名。 */
100
+ const RULE_PLAIN: Record<string, string> = {
101
+ '@eslint-community/eslint-comments/require-description': '"这里不查"的注释要写理由',
102
+ '@eslint-community/eslint-comments/no-unused-disable': '用不上的"这里不查"注释要删掉',
103
+ '@typescript-eslint/ban-ts-comment': '不许用注释关掉类型检查',
104
+ '@typescript-eslint/no-explicit-any': '不许用 any 跳过类型',
105
+ '@typescript-eslint/no-unused-vars': '不许有没用的变量和导入',
106
+ '@typescript-eslint/no-non-null-assertion': '不许用 ! 断定值不为空',
107
+ 'no-unused-vars': '不许有没用的变量',
108
+ 'no-console': '不许留调试用的 console',
109
+ 'no-debugger': '不许留 debugger',
110
+ eqeqeq: '比较要用 === 不用 ==',
111
+ 'react-hooks/rules-of-hooks': 'React hooks 的调用规则',
112
+ 'react-hooks/exhaustive-deps': 'React hooks 的依赖要写全',
113
+ }
114
+
115
+ /** 规则在弹窗里的叫法:白话(规则名),没有白话的只写规则名。 */
116
+ export function ruleName(rule: string): string {
117
+ const plain = RULE_PLAIN[rule] ?? LIMITS[rule]?.what
118
+ return plain ? `${plain}(${rule})` : rule
119
+ }
120
+
121
+ /** 上限类规则的数字和别的参数(别的参数改了判断不了方向)。 */
122
+ function limitOf(rule: string, options: unknown[]): { max: number; rest: string } {
123
+ const [first] = options
124
+ if (typeof first === 'number') return { max: first, rest: stable(options.slice(1)) }
125
+ if (typeof first === 'object' && first !== null && !Array.isArray(first)) {
126
+ const { max, maximum, ...rest } = first as Record<string, unknown>
127
+ const value = typeof max === 'number' ? max : typeof maximum === 'number' ? maximum : LIMITS[rule]!.fallback
128
+ return { max: value, rest: stable([rest, ...options.slice(1)]) }
129
+ }
130
+ return { max: LIMITS[rule]!.fallback, rest: stable(options.slice(1)) }
131
+ }
132
+
133
+ const LEVEL_NAMES = ['关掉', '警告', '报错']
134
+
135
+ /** 一处放松:同一处改动出现在几个文件上时合成一项。 */
136
+ interface Change {
137
+ before: string
138
+ after: string
139
+ text: string
140
+ }
141
+
142
+ /** 一个文件上规则的放松(before 是分叉点那一版,now 是现在,两边都被 lint)。 */
143
+ function changesOf(before: Effective, now: Effective): Change[] {
144
+ const changes: Change[] = []
145
+ for (const [rule, was] of Object.entries(before.rules)) {
146
+ const [wasLevel = 0, ...wasOptions] = was as [number, ...unknown[]]
147
+ if (wasLevel === 0) continue
148
+ const is = now.rules[rule]
149
+ const [isLevel = 0, ...isOptions] = (is ?? [0]) as [number, ...unknown[]]
150
+ const pair = { before: stable(['rule', rule, was]), after: stable(['rule', rule, is ?? null]) }
151
+ if (isLevel === 0) {
152
+ changes.push({ ...pair, text: `lint 规则 ${ruleName(rule)} ${is ? '关掉了' : '没了'}:以后不再查这一条` })
153
+ continue
154
+ }
155
+ if (isLevel < wasLevel) {
156
+ changes.push({ ...pair, text: `lint 规则 ${ruleName(rule)} 从报错降成了警告:以后违反它也能通过检查` })
157
+ continue
158
+ }
159
+ const limit = LIMITS[rule]
160
+ if (limit) {
161
+ const old = limitOf(rule, wasOptions)
162
+ const current = limitOf(rule, isOptions)
163
+ if (old.rest !== current.rest) changes.push({ ...pair, text: changedText(rule, wasOptions, isOptions) })
164
+ else if (current.max > old.max) {
165
+ const unit = limit.unit ? ` ${limit.unit}` : ' '
166
+ changes.push({ ...pair, text: `${limit.what}(${rule})从 ${old.max}${unit}调到 ${current.max}${unit.trimEnd()}:${limit.then}` })
167
+ }
168
+ continue
169
+ }
170
+ if (stable(wasOptions) !== stable(isOptions)) changes.push({ ...pair, text: changedText(rule, wasOptions, isOptions) })
171
+ }
172
+ if (now.unusedDirectives < before.unusedDirectives) {
173
+ changes.push({
174
+ before: stable(['unusedDirectives', before.unusedDirectives]),
175
+ after: stable(['unusedDirectives', now.unusedDirectives]),
176
+ text: `没用了的"这里不查"注释(eslint-disable)从${LEVEL_NAMES[before.unusedDirectives]}改成${LEVEL_NAMES[now.unusedDirectives]}(reportUnusedDisableDirectives):以后用不上的这类注释可以留在代码里`,
177
+ })
178
+ }
179
+ return changes
180
+ }
181
+
182
+ function changedText(rule: string, was: unknown[], is: unknown[]): string {
183
+ return [`lint 规则 ${ruleName(rule)} 的参数改了,程序看不出是改松还是改紧`, `原来:${stable(was)}`, `现在:${stable(is)}`].join('\n')
184
+ }
185
+
186
+ /** 列出来的文件最多几个。 */
187
+ const SHOWN = 20
188
+
189
+ /** 几个文件说成一句:个数,太多的只列前几个。files 已排好序。 */
190
+ export function fileList(files: string[], shown = 3): string {
191
+ return files.length <= shown ? files.join('、') : `${files.slice(0, shown).join('、')} 等 ${files.length} 个文件`
192
+ }
193
+
194
+ /**
195
+ * 两边都有的文件上的放松:同一处规则改动合成一项,写明影响多少文件;原来被 lint、现在不被 lint 的文件合成一项。
196
+ * 文字里的文件只取分叉点上就有的,这次新加文件不会让同意过的项重问。
197
+ */
198
+ export function eslintItems(before: FileRules, now: FileRules): ConfirmItem[] {
199
+ const merged = new Map<string, { change: Change; files: string[] }>()
200
+ const dropped: string[] = []
201
+ for (const [file, rules] of now) {
202
+ const was = before.get(file)
203
+ if (!was) continue
204
+ if (!rules) {
205
+ dropped.push(file)
206
+ continue
207
+ }
208
+ for (const change of changesOf(was, rules)) {
209
+ const key = `${change.before}\0${change.after}`
210
+ const found = merged.get(key)
211
+ if (found) found.files.push(file)
212
+ else merged.set(key, { change, files: [file] })
213
+ }
214
+ }
215
+ const items: ConfirmItem[] = [...merged.values()].map(({ change, files }) => ({
216
+ before: change.before,
217
+ after: change.after,
218
+ text: `${change.text}\n影响的代码:${fileList(files.sort())}`,
219
+ }))
220
+ if (dropped.length) {
221
+ dropped.sort()
222
+ items.push({
223
+ before: stable(['linted', dropped]),
224
+ after: stable(['not-linted', dropped]),
225
+ text: [
226
+ `${dropped.length} 个文件不再被 lint(被忽略了,或 eslint 配置不再覆盖它们):以后这些代码 lint 一条也不查`,
227
+ ...dropped.slice(0, SHOWN),
228
+ ...(dropped.length > SHOWN ? [`……还有 ${dropped.length - SHOWN} 个`] : []),
229
+ ].join('\n'),
230
+ })
231
+ }
232
+ return items
233
+ }
@@ -0,0 +1,86 @@
1
+ // 分叉点那一版的代码:比 eslint、tsconfig 生效的配置时,要在分叉点那一版上真的跑一遍工具(配置是代码,读不出来)。
2
+ // 在系统临时目录(仓库的 .git 之外)建一个分叉点的临时 worktree,把工作区里现有的 node_modules(根目录和各子包的)
3
+ // 链接到它的对应位置:工具、插件都用现在装着的那一份。工作区根目录没有自己的 node_modules、靠上层目录的
4
+ // (比如建在主目录里的 worktree),根目录链到 node 从工作区往上找到的那一份:临时 worktree 不在那条路上。用完 git worktree remove --force 并删目录;中途出错、被中断也收拾。
5
+ // 建 worktree 时不跑项目的 git 钩子(post-checkout 这类),也不碰任何分支(--detach)。
6
+
7
+ import { execFileSync } from 'node:child_process'
8
+ import { lstatSync, mkdtempSync, rmSync, statSync, symlinkSync } from 'node:fs'
9
+ import { tmpdir } from 'node:os'
10
+ import { dirname, join, parse } from 'node:path'
11
+ import { filesNow } from '../base/git.ts'
12
+
13
+ export interface ForkTree {
14
+ /** 临时 worktree 的根目录。 */
15
+ root: string
16
+ }
17
+
18
+ const isDir = (path: string): boolean => statSync(path, { throwIfNoEntry: false })?.isDirectory() === true
19
+
20
+ /** 工作区里有 package.json 的目录(相对仓库根目录,根目录是 ''),不算 node_modules 里面的。 */
21
+ function packageDirs(root: string): string[] {
22
+ const dirs = new Set([''])
23
+ for (const path of filesNow(root)) {
24
+ if (path === 'package.json' || path.endsWith('/package.json')) {
25
+ if (!path.split('/').includes('node_modules')) dirs.add(path === 'package.json' ? '' : dirname(path))
26
+ }
27
+ }
28
+ return [...dirs]
29
+ }
30
+
31
+ /** 子包 sub 用的 node_modules:它自己的;根目录没有自己的,用 node 从根目录往上找到的第一个。都没有是 undefined。 */
32
+ function modulesOf(root: string, sub: string): string | undefined {
33
+ const own = join(root, sub, 'node_modules')
34
+ if (isDir(own)) return own
35
+ if (sub !== '') return undefined
36
+ for (let dir = dirname(root); dir !== parse(dir).root; dir = dirname(dir)) {
37
+ if (isDir(join(dir, 'node_modules'))) return join(dir, 'node_modules')
38
+ }
39
+ return undefined
40
+ }
41
+
42
+ function gitQuiet(cwd: string, args: string[]): void {
43
+ execFileSync('git', ['-c', 'core.hooksPath=/dev/null', ...args], { cwd, stdio: ['ignore', 'ignore', 'pipe'] })
44
+ }
45
+
46
+ /**
47
+ * 在分叉点的临时 worktree 里做 fn,做完(不管成没成)都收掉。建不起来时抛错,由调用的地方当成"算不出来"。
48
+ * 被 SIGINT、SIGTERM、SIGHUP 中断时先收掉再以 130 退出。
49
+ */
50
+ export async function withForkTree<T>(root: string, fork: string, fn: (tree: ForkTree) => Promise<T>): Promise<T> {
51
+ const dir = mkdtempSync(join(tmpdir(), 'codekeep-'))
52
+ const tree = join(dir, 'tree')
53
+ let added = false
54
+ const cleanup = (): void => {
55
+ if (added) {
56
+ try {
57
+ gitQuiet(root, ['worktree', 'remove', '--force', tree])
58
+ } catch {
59
+ // 下面删了目录,git 会在 worktree prune 时清掉登记
60
+ }
61
+ added = false
62
+ }
63
+ rmSync(dir, { recursive: true, force: true })
64
+ }
65
+ const interrupted = (): void => {
66
+ cleanup()
67
+ process.exit(130)
68
+ }
69
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const
70
+ for (const signal of signals) process.on(signal, interrupted)
71
+ try {
72
+ added = true
73
+ gitQuiet(root, ['worktree', 'add', '--detach', '--quiet', tree, fork])
74
+ for (const sub of packageDirs(root)) {
75
+ const source = modulesOf(root, sub)
76
+ const target = join(tree, sub, 'node_modules')
77
+ // 分叉点上没有这个目录(这次新加的包)就不用链;已经有的(提交进仓库的)不动
78
+ if (!source || !isDir(join(tree, sub)) || lstatSync(target, { throwIfNoEntry: false })) continue
79
+ symlinkSync(source, target, 'dir')
80
+ }
81
+ return await fn({ root: tree })
82
+ } finally {
83
+ for (const signal of signals) process.off(signal, interrupted)
84
+ cleanup()
85
+ }
86
+ }
@@ -0,0 +1,29 @@
1
+ // 整组里"代码规范"的部分(base/module.ts 的 fullPart):接入了的仓库在测试之前跑一次 codekeep check。
2
+ // 它随插件一起装,不用在本机另外登记;没接入的仓库没有这一段。
3
+
4
+ import { fileURLToPath } from 'node:url'
5
+ import { quoted } from '../base/execute.ts'
6
+ import { forkPoint } from '../base/git.ts'
7
+ import type { FullPart } from '../base/module.ts'
8
+ import type { Repo } from '../base/repo.ts'
9
+ import { joined } from './config.ts'
10
+
11
+ /** 这个插件里的 codekeep 命令:用完整路径,不靠 PATH 上碰巧有哪一版。 */
12
+ const BIN = fileURLToPath(new URL('../../bin/codekeep', import.meta.url))
13
+
14
+ export function fullPart(repo: Repo): FullPart {
15
+ // 按分叉点也算接入:删掉 .codekeep/ 躲不过检查
16
+ if (!joined(repo.root, forkPoint(repo.root).commit)) return { steps: [] }
17
+ return {
18
+ steps: [
19
+ {
20
+ kind: 'keep',
21
+ name: '代码规范的检查(codekeep check)',
22
+ title: '代码规范的检查(codekeep check)',
23
+ header: '代码规范的检查:codekeep check',
24
+ command: `${quoted(BIN)} check`,
25
+ args: [],
26
+ },
27
+ ],
28
+ }
29
+ }
@@ -0,0 +1,13 @@
1
+ // "代码规范"这个检查模块交给底座的入口(见 base/module.ts):底座只通过这里知道它。
2
+ // 它在项目里的配置是 .codekeep/ 目录,没有这个目录的仓库里它不出声、不加检查。
3
+ // 第一期只有会话说明和整组里的一段:不在改文件时拦(lint 自己会报),不加停止门(整组兜底)。
4
+
5
+ import type { Module } from '../base/module.ts'
6
+ import { fullPart } from './full.ts'
7
+ import { brief } from './session.ts'
8
+
9
+ export const keep: Module = {
10
+ name: 'keep',
11
+ brief,
12
+ fullPart,
13
+ }
@@ -0,0 +1,163 @@
1
+ // 读文件就能比的放松:.codekeep/config.json、eslint 的批量豁免文件、gitleaks 的忽略文件和配置、biome 的配置。和分叉点那一版比,
2
+ // 放松的列成条目交给底座的用户确认(base/confirm.ts);收紧的(加检查、豁免变少)不问。
3
+ // eslint、tsconfig 生效的配置要跑工具才算得出来,见 eslint.ts、tsconfig.ts。
4
+ //
5
+ // 每一项的改之前、改成什么写成能区分同一项改动的内容:同一条检查的同一次改命令在哪个分支上都是同一项,共用一次同意;
6
+ // 删的、改的是另一份内容,就是另一项,要重新同意。
7
+
8
+ import type { ConfirmItem } from '../base/confirm.ts'
9
+ import type { Judging } from '../base/judging.ts'
10
+ import { hash } from '../base/records.ts'
11
+ import { CONFIG_PATH, type Config, KEEP_DIR } from './config.ts'
12
+ import { ruleName, stable } from './eslint.ts'
13
+
14
+ /** gitleaks 的忽略文件和配置(仓库根目录;gitleaks 在仓库根目录跑时用的就是这两个)。 */
15
+ export const GITLEAKS_IGNORE = '.gitleaksignore'
16
+ export const GITLEAKS_CONFIG = '.gitleaks.toml'
17
+ /** biome 的配置(仓库根目录)。第一期不比 biome 生效的规则,改了就按"程序看不出"问。 */
18
+ export const BIOME_CONFIGS = ['biome.json', 'biome.jsonc']
19
+
20
+ /** 删掉整个配置:before 是分叉点上能用的配置。 */
21
+ export function removedItem(before: Config, hasDir: boolean): ConfirmItem {
22
+ return {
23
+ before: stable(before),
24
+ after: '',
25
+ text: `${hasDir ? `删掉了配置文件 ${CONFIG_PATH}` : `删掉了整个 ${KEEP_DIR}/ 目录`}:以后不再跑规范检查(类型检查、lint、格式${before.secrets ? '、密钥扫描' : ''}),规范改松了也没人发现`,
26
+ }
27
+ }
28
+
29
+ /** .codekeep/config.json 里放松的地方。 */
30
+ export function configItems(before: Config, now: Config): ConfirmItem[] {
31
+ const items: ConfirmItem[] = []
32
+ for (const check of before.checks) {
33
+ // 命令一样的照样在跑,换了名字也不算放松
34
+ if (now.checks.some(item => item.command === check.command)) continue
35
+ const same = now.checks.find(item => item.name === check.name)
36
+ if (same) {
37
+ items.push({
38
+ before: stable(['check', check.name, check.command]),
39
+ after: stable(['check', same.name, same.command]),
40
+ text: [`规范检查"${check.name}"的命令改了,程序看不出是改松还是改紧`, `原来:${check.command}`, `现在:${same.command}`].join('\n'),
41
+ })
42
+ } else {
43
+ items.push({
44
+ before: stable(['check', check.name, check.command]),
45
+ after: '',
46
+ text: [`删掉了规范检查"${check.name}":以后整组里不再跑它`, `原来的命令:${check.command}`].join('\n'),
47
+ })
48
+ }
49
+ }
50
+ if (before.eslint) {
51
+ if (!now.eslint) {
52
+ items.push({ before: stable(['eslint', before.eslint]), after: '', text: '不再比 eslint 生效的规则(删掉了 eslint 一项):以后 lint 规则改松了程序看不出来' })
53
+ } else {
54
+ if (now.eslint.config !== before.eslint.config) {
55
+ items.push({
56
+ before: stable(['eslint.config', before.eslint.config]),
57
+ after: stable(['eslint.config', now.eslint.config]),
58
+ text: `拿来比规则的 eslint 配置文件从 ${before.eslint.config} 换成了 ${now.eslint.config}:程序看不出两份是不是一回事,lint 实际用的可能不是这一份`,
59
+ })
60
+ }
61
+ if (now.eslint.suppressions !== before.eslint.suppressions) {
62
+ items.push({
63
+ before: stable(['eslint.suppressions', before.eslint.suppressions]),
64
+ after: stable(['eslint.suppressions', now.eslint.suppressions]),
65
+ text: `eslint 的批量豁免文件从 ${before.eslint.suppressions} 换成了 ${now.eslint.suppressions}:换过去的那份里豁免了什么没和原来的比`,
66
+ })
67
+ }
68
+ }
69
+ }
70
+ for (const tsconfig of before.tsconfig.filter(path => !now.tsconfig.includes(path))) {
71
+ items.push({ before: stable(['tsconfig', tsconfig]), after: '', text: `不再比 ${tsconfig} 的严格选项:以后这份类型检查配置改松了程序看不出来` })
72
+ }
73
+ if (before.prettier && !now.prettier) {
74
+ items.push({ before: stable(['prettier', true]), after: stable(['prettier', false]), text: '不再比格式检查查哪些文件(关掉了 prettier 一项):以后往忽略文件里加路径、躲开格式检查,程序看不出来' })
75
+ }
76
+ if (before.secrets && !now.secrets) items.push({ before: stable(['secrets', true]), after: stable(['secrets', false]), text: '关掉了密钥扫描(secrets):以后提交里带了密钥、密码,整组不再拦' })
77
+ return items
78
+ }
79
+
80
+ /** 批量豁免文件:文件 → 规则 → 豁免了几处。读不出来时是 undefined。 */
81
+ type Suppressions = Map<string, number>
82
+
83
+ function suppressionsOf(text: string): Suppressions | undefined {
84
+ try {
85
+ const raw = JSON.parse(text) as unknown
86
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined
87
+ const counts: Suppressions = new Map()
88
+ for (const [file, rules] of Object.entries(raw as Record<string, unknown>)) {
89
+ if (typeof rules !== 'object' || rules === null) return undefined
90
+ for (const [rule, entry] of Object.entries(rules as Record<string, unknown>)) {
91
+ const count = (entry as { count?: unknown } | null)?.count
92
+ if (typeof count !== 'number') return undefined
93
+ counts.set(`${file}\0${rule}`, count)
94
+ }
95
+ }
96
+ return counts
97
+ } catch {
98
+ return undefined
99
+ }
100
+ }
101
+
102
+ /** 列出来的最多几处。 */
103
+ const SHOWN = 20
104
+
105
+ /** eslint 的批量豁免文件里,哪条规则、哪个文件豁免的数量变多了:合成一项。 */
106
+ export function suppressionsItem(path: string, judging: Judging): ConfirmItem | undefined {
107
+ if (judging.now === undefined) return undefined
108
+ const now = suppressionsOf(judging.now)
109
+ const before = judging.before === undefined ? new Map<string, number>() : suppressionsOf(judging.before)
110
+ if (!now || !before) {
111
+ if (judging.before === judging.now) return undefined
112
+ return {
113
+ before: hash(judging.before),
114
+ after: hash(judging.now),
115
+ text: `eslint 的批量豁免文件 ${path} 改了,${!now ? '现在这一版' : '分叉点那一版'}读不出来,程序看不出是不是多豁免了`,
116
+ }
117
+ }
118
+ const more = [...now].filter(([key, count]) => count > (before.get(key) ?? 0)).sort(([a], [b]) => (a < b ? -1 : 1))
119
+ if (more.length === 0) return undefined
120
+ const lines = more.slice(0, SHOWN).map(([key, count]) => {
121
+ const [file, rule] = key.split('\0')
122
+ return `${file}:${ruleName(rule ?? '')} 从 ${before.get(key) ?? 0} 处变成 ${count} 处`
123
+ })
124
+ if (more.length > SHOWN) lines.push(`……还有 ${more.length - SHOWN} 处`)
125
+ return {
126
+ before: stable(more.map(([key]) => [key, before.get(key) ?? 0])),
127
+ after: stable(more),
128
+ text: [`eslint 的批量豁免文件 ${path} 多豁免了 ${more.length} 处:这些地方违反了规则也照样通过`, ...lines].join('\n'),
129
+ }
130
+ }
131
+
132
+ /** .gitleaksignore 的条目(每行一条,# 开头的是注释)。 */
133
+ const entries = (text: string | undefined): string[] =>
134
+ (text ?? '')
135
+ .split('\n')
136
+ .map(line => line.trim())
137
+ .filter(line => line !== '' && !line.startsWith('#'))
138
+
139
+ /** gitleaks 的忽略文件多了条目、配置改了(配置是 TOML,程序看不出方向,改了就问)。 */
140
+ export function gitleaksItems(ignore: Judging, config: Judging): ConfirmItem[] {
141
+ const items: ConfirmItem[] = []
142
+ const before = entries(ignore.before)
143
+ const added = [...new Set(entries(ignore.now).filter(line => !before.includes(line)))].sort()
144
+ if (added.length) {
145
+ items.push({
146
+ before: '',
147
+ after: stable(['gitleaksignore', added]),
148
+ text: [`${GITLEAKS_IGNORE} 新加了 ${added.length} 条忽略:扫密钥时这些发现不再算`, ...added.slice(0, SHOWN), ...(added.length > SHOWN ? [`……还有 ${added.length - SHOWN} 条`] : [])].join('\n'),
149
+ })
150
+ }
151
+ if (config.before !== config.now) {
152
+ const what = config.before === undefined ? '新加了' : config.now === undefined ? '删掉了' : '改了'
153
+ items.push({ before: hash(config.before), after: hash(config.now), text: `gitleaks 的配置 ${GITLEAKS_CONFIG} ${what},程序看不出扫密钥是改松还是改紧` })
154
+ }
155
+ return items
156
+ }
157
+
158
+ /** biome 的配置改了(新加、删掉、改了内容):第一期不比它生效的规则,程序看不出方向,改了就问。 */
159
+ export function biomeItem(path: string, config: Judging): ConfirmItem | undefined {
160
+ if (config.before === config.now) return undefined
161
+ const what = config.before === undefined ? '新加了' : config.now === undefined ? '删掉了' : '改了'
162
+ return { before: hash(config.before), after: hash(config.now), text: `biome 的配置 ${path} ${what},程序看不出 lint、格式规则是改松还是改紧` }
163
+ }
@@ -0,0 +1,58 @@
1
+ // 格式检查查哪些文件:用项目自己装的 prettier 的程序接口(getFileInfo),对仓库里每个文件(git 收的)算格式检查
2
+ // 查不查(被 .prettierignore、.gitignore 忽略的不查,认不出写法的不查),分叉点那一版和现在比。
3
+ // 算放松的:原来查、现在不查了的文件(往忽略文件里加了路径)。只比两边都有的文件。
4
+ // prettier 的写法选项(单引号、行宽这些)改了只是换风格,不算放松。
5
+
6
+ import { createRequire } from 'node:module'
7
+ import { join } from 'node:path'
8
+ import { pathToFileURL } from 'node:url'
9
+ import type { ConfirmItem } from '../base/confirm.ts'
10
+ import { stable } from './eslint.ts'
11
+
12
+ /** prettier 在仓库根目录跑时读的忽略文件(相对仓库根目录)。 */
13
+ const IGNORE_FILES = ['.gitignore', '.prettierignore']
14
+
15
+ type GetFileInfo = (path: string, options: { ignorePath: string[] }) => Promise<{ ignored: boolean; inferredParser: string | null }>
16
+
17
+ /** 项目自己装的 prettier(从仓库根目录往上找)。找不到时抛错。 */
18
+ export async function loadPrettier(root: string): Promise<GetFileInfo> {
19
+ let entry: string
20
+ try {
21
+ entry = createRequire(join(root, 'noop.js')).resolve('prettier')
22
+ } catch {
23
+ throw new Error('项目里没装 prettier(从仓库根目录往上找不到),先装好依赖')
24
+ }
25
+ const module = (await import(pathToFileURL(entry).href)) as { getFileInfo?: GetFileInfo; default?: { getFileInfo?: GetFileInfo } }
26
+ const getFileInfo = module.getFileInfo ?? module.default?.getFileInfo
27
+ if (typeof getFileInfo !== 'function') throw new Error(`${entry} 里没有 getFileInfo 的程序接口`)
28
+ return getFileInfo
29
+ }
30
+
31
+ /** 在 tree(仓库或分叉点的临时 worktree)里,这些文件(相对 tree)中格式检查查的那些。算不出来时抛错。 */
32
+ export async function checkedFiles(getFileInfo: GetFileInfo, tree: string, files: string[]): Promise<Set<string>> {
33
+ const ignorePath = IGNORE_FILES.map(file => join(tree, file))
34
+ const checked = new Set<string>()
35
+ for (const file of files) {
36
+ const info = await getFileInfo(join(tree, file), { ignorePath })
37
+ if (!info.ignored && info.inferredParser !== null) checked.add(file)
38
+ }
39
+ return checked
40
+ }
41
+
42
+ /** 列出来的文件最多几个。 */
43
+ const SHOWN = 20
44
+
45
+ /** 原来查、现在不查了的文件,合成一项。now 只含两边都有的文件里现在查的;compared 是两边都有的文件。 */
46
+ export function prettierItem(before: Set<string>, now: Set<string>, compared: string[]): ConfirmItem | undefined {
47
+ const dropped = compared.filter(file => before.has(file) && !now.has(file)).sort()
48
+ if (dropped.length === 0) return undefined
49
+ return {
50
+ before: stable(['format-checked', dropped]),
51
+ after: stable(['format-unchecked', dropped]),
52
+ text: [
53
+ `${dropped.length} 个文件不再做格式检查(被 .prettierignore 之类的忽略了):以后这些文件格式乱了也照样通过`,
54
+ ...dropped.slice(0, SHOWN),
55
+ ...(dropped.length > SHOWN ? [`……还有 ${dropped.length - SHOWN} 个`] : []),
56
+ ].join('\n'),
57
+ }
58
+ }
@@ -0,0 +1,63 @@
1
+ // 扫密钥:secrets 开着时,用 gitleaks 扫这次改动——分叉点之后的提交(gitleaks git --log-opts "<分叉点>..HEAD"),
2
+ // 加上没提交的改动(--pre-commit:已暂存、没暂存的,没跟踪的新文件也算)。只扫这次的,旧提交里的不管。
3
+ // 没提交的那一份用一份临时的索引:从 HEAD 读出来,把没跟踪的新文件登记成"要加的"(git add -N),
4
+ // gitleaks 跑的 git diff 就是工作区相对 HEAD 的全部改动。真实的索引不动。
5
+ // gitleaks 用仓库根目录的 .gitleaks.toml、.gitleaksignore(改松要用户同意,见 loosen.ts);外面环境变量指的配置不认。
6
+ // 找不到 gitleaks 不自己装,说怎么装。输出里的密钥打码(--redact)。
7
+ // 代码里的 gitleaks:allow 注释不认(--ignore-gitleaks-allow):它是不写理由、不用确认的"这里不查";确实不是密钥的进 .gitleaksignore,要用户同意。
8
+
9
+ import { execFileSync, spawnSync } from 'node:child_process'
10
+ import { mkdtempSync, rmSync } from 'node:fs'
11
+ import { tmpdir } from 'node:os'
12
+ import { join } from 'node:path'
13
+
14
+ export type SecretsResult = { ok: true } | { missing: true } | { leaks: true } | { problem: string }
15
+
16
+ /** gitleaks 的可执行文件:PATH 上的,没有再看 Homebrew 的位置。 */
17
+ function findGitleaks(): string | undefined {
18
+ const found = spawnSync('/bin/sh', ['-c', 'command -v gitleaks'], { encoding: 'utf8' }).stdout.trim()
19
+ if (found) return found
20
+ return ['/opt/homebrew/bin/gitleaks', '/usr/local/bin/gitleaks'].find(path => spawnSync(path, ['version']).status === 0)
21
+ }
22
+
23
+ const { GITLEAKS_CONFIG: _config, GITLEAKS_CONFIG_TOML: _toml, ...env } = process.env
24
+
25
+ /** 跑一次 gitleaks,输出照原样给出来。返回退出码:0 没扫出、1 扫出了,别的是没跑成。 */
26
+ function gitleaks(bin: string, root: string, args: string[], extraEnv: Record<string, string> = {}): number | null {
27
+ const r = spawnSync(bin, ['git', ...args, '--ignore-gitleaks-allow', '--redact', '--no-banner', '--no-color', '--verbose', '--exit-code', '1', root], {
28
+ cwd: root,
29
+ env: { ...env, ...extraEnv },
30
+ stdio: ['ignore', 'inherit', 'inherit'],
31
+ })
32
+ return r.status
33
+ }
34
+
35
+ export function scanSecrets(root: string, fork: string): SecretsResult {
36
+ const bin = findGitleaks()
37
+ if (!bin) return { missing: true }
38
+ console.log(`== 扫密钥:分叉点 ${fork.slice(0, 10)} 之后的提交`)
39
+ const committed = gitleaks(bin, root, ['--log-opts', `${fork}..HEAD`])
40
+ if (committed !== 0 && committed !== 1) return { problem: `gitleaks 扫提交时没跑成(退出码 ${committed})` }
41
+
42
+ console.log('== 扫密钥:没提交的改动')
43
+ const dir = mkdtempSync(join(tmpdir(), 'codekeep-index-'))
44
+ let pending: number | null
45
+ try {
46
+ const indexEnv = { GIT_INDEX_FILE: join(dir, 'index') }
47
+ const git = (args: string[], input?: string): void => {
48
+ execFileSync('git', args, { cwd: root, env: { ...process.env, ...indexEnv }, input, stdio: ['pipe', 'ignore', 'pipe'] })
49
+ }
50
+ git(['read-tree', 'HEAD'])
51
+ git(['update-index', '-q', '--refresh'])
52
+ // 对着临时索引列:已暂存、还没提交的新文件不在 HEAD 里,也要登记进来
53
+ const untracked = execFileSync('git', ['ls-files', '-z', '--others', '--exclude-standard'], { cwd: root, encoding: 'utf8', env: { ...process.env, ...indexEnv } })
54
+ if (untracked) git(['add', '--intent-to-add', '--pathspec-from-file=-', '--pathspec-file-nul'], untracked)
55
+ pending = gitleaks(bin, root, ['--pre-commit'], indexEnv)
56
+ } catch (error) {
57
+ return { problem: `准备扫没提交的改动时出错:${(error as Error).message.split('\n')[0]}` }
58
+ } finally {
59
+ rmSync(dir, { recursive: true, force: true })
60
+ }
61
+ if (pending !== 0 && pending !== 1) return { problem: `gitleaks 扫没提交的改动时没跑成(退出码 ${pending})` }
62
+ return committed === 1 || pending === 1 ? { leaks: true } : { ok: true }
63
+ }