gatelight 0.18.1 → 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,139 @@
1
+ // "代码规范"在项目里的配置:.codekeep/config.json。没有 .codekeep/ 目录的仓库没接入,它不出声、不加检查。
2
+ // checks 规范检查的命令(类型检查、lint、格式),直接写工具命令,不经过项目的脚本;整组里依次跑
3
+ // eslint 拿来比"生效的规则"的 eslint:config 是配置文件(按它对每个代码文件算生效的规则),
4
+ // suppressions 是批量豁免文件(eslint --suppress-all 生成的,不写就是仓库根目录的 eslint-suppressions.json)
5
+ // prettier 开着时比格式检查查哪些文件(prettier 在仓库根目录跑,查 git 收的文件)
6
+ // tsconfig 拿来比严格选项的 tsconfig 文件
7
+ // secrets 开着时整组里用 gitleaks 扫这次的提交和没提交的改动
8
+ // 这份配置是评判用的配置(base/judging.ts),走"用户同意后生效":改松的地方见 loosen.ts。
9
+
10
+ import { existsSync } from 'node:fs'
11
+ import { join, posix } from 'node:path'
12
+ import { fileNow, hasFile } from '../base/git.ts'
13
+
14
+ export const KEEP_DIR = '.codekeep'
15
+ export const CONFIG_PATH = `${KEEP_DIR}/config.json`
16
+ /** eslint 批量豁免文件的默认位置(eslint 自己的默认名字,相对仓库根目录)。 */
17
+ export const DEFAULT_SUPPRESSIONS = 'eslint-suppressions.json'
18
+
19
+ export interface Check {
20
+ name: string
21
+ command: string
22
+ }
23
+
24
+ export interface EslintConfig {
25
+ config: string
26
+ suppressions: string
27
+ }
28
+
29
+ export interface Config {
30
+ checks: Check[]
31
+ eslint?: EslintConfig
32
+ tsconfig: string[]
33
+ prettier: boolean
34
+ secrets: boolean
35
+ }
36
+
37
+ export interface Parsed {
38
+ config?: Config
39
+ problems: string[]
40
+ }
41
+
42
+ /** 接入了:分叉点或工作区里有 .codekeep/。 */
43
+ export function joined(root: string, fork?: string): boolean {
44
+ return existsSync(join(root, KEEP_DIR)) || (fork !== undefined && hasFile(root, fork, KEEP_DIR))
45
+ }
46
+
47
+ const KEYS = ['checks', 'eslint', 'tsconfig', 'prettier', 'secrets']
48
+ const ESLINT_KEYS = ['config', 'suppressions']
49
+
50
+ const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
51
+
52
+ /** 仓库里的相对路径:去掉开头的 ./;不能是绝对路径,不能有 ..、空段、通配。 */
53
+ function relativePath(value: unknown): string | undefined {
54
+ if (typeof value !== 'string') return undefined
55
+ const plain = value.replace(/^(?:\.\/)+/, '')
56
+ if (plain === '' || plain.startsWith('/') || plain.includes('\\') || /[*?[\]{}]/.test(plain)) return undefined
57
+ if (plain.split('/').some(segment => segment === '' || segment === '.' || segment === '..')) return undefined
58
+ return posix.normalize(plain) === plain ? plain : undefined
59
+ }
60
+
61
+ /**
62
+ * 读配置的文字,只看写法(字段、类型、路径的写法),不看文件在不在:分叉点那一版也用它读。
63
+ * 工作区这一版另用 missingFiles 查写到的文件在不在。
64
+ */
65
+ export function parseConfig(text: string): Parsed {
66
+ let raw: unknown
67
+ try {
68
+ raw = JSON.parse(text)
69
+ } catch (error) {
70
+ return { problems: [`${CONFIG_PATH} 不是合法的 JSON:${(error as Error).message}`] }
71
+ }
72
+ if (!isRecord(raw)) return { problems: [`${CONFIG_PATH} 应该是一个对象`] }
73
+ const problems: string[] = []
74
+ const extra = Object.keys(raw).filter(key => !KEYS.includes(key))
75
+ if (extra.length) problems.push(`${CONFIG_PATH} 有未知字段 ${extra.map(key => `"${key}"`).join('、')}(认得的有 ${KEYS.join('、')})`)
76
+
77
+ const checks: Check[] = []
78
+ if (!Array.isArray(raw.checks) || raw.checks.length === 0) {
79
+ problems.push(`${CONFIG_PATH} 的 "checks" 要写成非空数组,每条 { "name": 名字, "command": 命令 }`)
80
+ } else {
81
+ raw.checks.forEach((item: unknown, index) => {
82
+ const where = `checks 的第 ${index + 1} 条`
83
+ if (!isRecord(item)) return void problems.push(`${where} 应该是 { "name": 名字, "command": 命令 }`)
84
+ const unknown = Object.keys(item).filter(key => key !== 'name' && key !== 'command')
85
+ if (unknown.length) problems.push(`${where} 有未知字段 ${unknown.map(key => `"${key}"`).join('、')}`)
86
+ const { name, command } = item
87
+ if (typeof name !== 'string' || name.trim() === '' || /[\n\r]/.test(name)) return void problems.push(`${where} 要写名字(name,一行)`)
88
+ if (typeof command !== 'string' || command.trim() === '') return void problems.push(`${where}(${name})要写命令(command)`)
89
+ if (checks.some(check => check.name === name.trim())) return void problems.push(`${where} 的名字 "${name}" 和前面的重复了`)
90
+ checks.push({ name: name.trim(), command: command.trim() })
91
+ })
92
+ }
93
+
94
+ let eslint: EslintConfig | undefined
95
+ if (raw.eslint !== undefined) {
96
+ const value = raw.eslint
97
+ if (!isRecord(value)) problems.push(`${CONFIG_PATH} 的 "eslint" 应该是 { "config": 配置文件, "suppressions": 豁免文件(可选) }`)
98
+ else {
99
+ const unknown = Object.keys(value).filter(key => !ESLINT_KEYS.includes(key))
100
+ if (unknown.length) problems.push(`${CONFIG_PATH} 的 "eslint" 有未知字段 ${unknown.map(key => `"${key}"`).join('、')}`)
101
+ const config = relativePath(value.config)
102
+ if (config === undefined) problems.push(`${CONFIG_PATH} 的 "eslint.config" 要写 eslint 配置文件(仓库里的相对路径,比如 "eslint.config.mjs")`)
103
+ const suppressions = value.suppressions === undefined ? DEFAULT_SUPPRESSIONS : relativePath(value.suppressions)
104
+ if (suppressions === undefined) problems.push(`${CONFIG_PATH} 的 "eslint.suppressions" 要写批量豁免文件(仓库里的相对路径)`)
105
+ if (config !== undefined && suppressions !== undefined) eslint = { config, suppressions }
106
+ }
107
+ }
108
+
109
+ const tsconfig = raw.tsconfig === undefined ? [] : paths(raw.tsconfig, 'tsconfig', 'tsconfig 文件', problems)
110
+ for (const key of ['prettier', 'secrets']) {
111
+ if (raw[key] !== undefined && typeof raw[key] !== 'boolean') problems.push(`${CONFIG_PATH} 的 "${key}" 要写 true 或 false`)
112
+ }
113
+
114
+ if (problems.length || tsconfig === undefined) return { problems }
115
+ return { config: { checks, ...(eslint ? { eslint } : {}), tsconfig, prettier: raw.prettier === true, secrets: raw.secrets === true }, problems }
116
+ }
117
+
118
+ /** 一组仓库里的文件:非空数组,不重复。 */
119
+ function paths(value: unknown, name: string, what: string, problems: string[]): string[] | undefined {
120
+ if (!Array.isArray(value) || value.length === 0) {
121
+ problems.push(`${CONFIG_PATH} 的 "${name}" 要写成非空数组,每项是${what}(仓库里的相对路径)`)
122
+ return undefined
123
+ }
124
+ const found = problems.length
125
+ const result: string[] = []
126
+ for (const item of value) {
127
+ const path = relativePath(item)
128
+ if (path === undefined) problems.push(`${name} 里的 ${JSON.stringify(item)} 要写${what}(仓库里的相对路径,不用通配)`)
129
+ else if (result.includes(path)) problems.push(`${name} 里的 "${path}" 写了两次`)
130
+ else result.push(path)
131
+ }
132
+ return problems.length > found ? undefined : result
133
+ }
134
+
135
+ /** 工作区这一版配置里写到、却不在的文件(批量豁免文件可以还没有)。 */
136
+ export function missingFiles(root: string, config: Config): string[] {
137
+ const listed = [...(config.eslint ? [config.eslint.config] : []), ...config.tsconfig]
138
+ return listed.filter(path => fileNow(root, path) === undefined).map(path => `${CONFIG_PATH} 里写的 ${path} 不在(要写仓库里现有的文件)`)
139
+ }
@@ -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
+ }