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,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
+ }
@@ -0,0 +1,22 @@
1
+ // "代码规范"说给 agent 的话,经底座的钩子送出去(base/module.ts 的 brief):会话开始时说几句规范的约定。
2
+ // 没有改文件前的拦截和停止门:lint 自己会报,规范检查在落地前的整组里跑(见 full.ts)。
3
+
4
+ import { existsSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import type { Repo } from '../base/repo.ts'
7
+ import { CONFIG_PATH, KEEP_DIR } from './config.ts'
8
+
9
+ export function guide(label = '这个仓库'): string[] {
10
+ return [
11
+ `${label}用 codekeep 管代码规范(${KEEP_DIR}/):`,
12
+ `1. 类型检查、lint、格式检查由 codekeep 在整组(testpace full)里跑,命令和要比的配置写在 ${CONFIG_PATH}。`,
13
+ '2. 不改松规范:不关规则、不把 error 降成 warn、不调高长度和复杂度上限、不加忽略的路径、不关严格类型选项、不往批量豁免文件里加条目。确实要改,整组会要用户确认:先在对话里用白话讲清改了哪条、为什么只能这样。',
14
+ '3. 代码里"这里不查"的注释(eslint-disable、@ts-expect-error 这类)必须写理由,比如 // eslint-disable-next-line 规则名 -- 理由;能改代码就改代码,不加这种注释。',
15
+ '4. 提交里不放密钥、密码;测试用的假值写得一眼能看出是假的(比如 test-password-not-real)。',
16
+ ]
17
+ }
18
+
19
+ /** 会话说明:接入了"代码规范"的仓库(工作区里有 .codekeep/)才说。 */
20
+ export function brief(label: string, repo?: Repo): string[] {
21
+ return repo && existsSync(join(repo.root, KEEP_DIR)) ? guide(label) : []
22
+ }
@@ -0,0 +1,115 @@
1
+ // tsconfig 生效的选项:用项目自己装的 typescript 跑 tsc --showConfig(extends 合并好、strict 展开好),分叉点那一版和现在比。
2
+ // 算放松的:严格类的选项从开变成关,开了 skipLibCheck,include 少了、exclude 多了。别的选项不比。
3
+
4
+ import { execFileSync } from 'node:child_process'
5
+ import { readFileSync } from 'node:fs'
6
+ import { createRequire } from 'node:module'
7
+ import { dirname, join } from 'node:path'
8
+ import type { ConfirmItem } from '../base/confirm.ts'
9
+ import { stable } from './eslint.ts'
10
+
11
+ /** 严格类的选项和它查的是什么(白话)。strict 开着时没写的前几项跟着开。 */
12
+ const STRICT: Record<string, string> = {
13
+ strict: '严格类型检查的总开关',
14
+ noImplicitAny: '推断不出类型的地方不许悄悄当成 any',
15
+ strictNullChecks: '可能是空值(null、undefined)的地方要先判断',
16
+ strictFunctionTypes: '函数参数的类型要对得上',
17
+ strictBindCallApply: 'bind、call、apply 的参数要对得上',
18
+ strictPropertyInitialization: '类的属性要在构造时赋值',
19
+ strictBuiltinIteratorReturn: '内置迭代器的返回值按严格的类型算',
20
+ noImplicitThis: 'this 的类型要明确',
21
+ alwaysStrict: '按 JavaScript 严格模式解析',
22
+ useUnknownInCatchVariables: 'catch 到的错误当成 unknown,用之前要先判断',
23
+ noUncheckedIndexedAccess: '按下标、键取值可能取不到,要先判断',
24
+ noImplicitReturns: '函数的每个分支都要 return',
25
+ noFallthroughCasesInSwitch: 'switch 的分支不许漏写 break',
26
+ noUnusedLocals: '不许有没用的变量',
27
+ noUnusedParameters: '不许有没用的参数',
28
+ noImplicitOverride: '覆盖父类的方法要写 override',
29
+ exactOptionalPropertyTypes: '可选属性不许随手赋 undefined',
30
+ }
31
+ /** strict 开着时跟着开的(没单独写时)。 */
32
+ const STRICT_FAMILY = [
33
+ 'noImplicitAny',
34
+ 'strictNullChecks',
35
+ 'strictFunctionTypes',
36
+ 'strictBindCallApply',
37
+ 'strictPropertyInitialization',
38
+ 'strictBuiltinIteratorReturn',
39
+ 'noImplicitThis',
40
+ 'alwaysStrict',
41
+ 'useUnknownInCatchVariables',
42
+ ]
43
+
44
+ /** 拿来比的那几样。 */
45
+ export interface TsSettings {
46
+ /** 开着的严格类选项。 */
47
+ strict: string[]
48
+ skipLibCheck: boolean
49
+ include: string[]
50
+ exclude: string[]
51
+ }
52
+
53
+ /**
54
+ * 项目自己装的 tsc:从工作区里这个 tsconfig 所在的目录往上找 typescript,按它 package.json 的 bin 找到 tsc。
55
+ * 不直接找 typescript/bin/tsc:TypeScript 7 的 package.json 写了 exports,没导出 bin/ 下的文件。找不到时抛错。
56
+ */
57
+ export function findTsc(root: string, tsconfig: string): string {
58
+ let manifest: string
59
+ try {
60
+ manifest = createRequire(join(root, dirname(tsconfig), 'noop.js')).resolve('typescript/package.json')
61
+ } catch {
62
+ throw new Error('项目里没装 typescript(从 tsconfig 所在的目录往上找不到),先装好依赖')
63
+ }
64
+ const { bin } = JSON.parse(readFileSync(manifest, 'utf8')) as { bin?: string | Record<string, string> }
65
+ const tsc = typeof bin === 'string' ? bin : bin?.tsc
66
+ if (!tsc) throw new Error(`${manifest} 里没写 tsc 命令(bin)`)
67
+ return join(dirname(manifest), tsc)
68
+ }
69
+
70
+ const strings = (value: unknown): string[] => (Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [])
71
+
72
+ /** 在 tree(仓库或分叉点的临时 worktree)里算一个 tsconfig 生效的选项。算不出来时抛错。 */
73
+ export function tsSettings(tsc: string, tree: string, tsconfig: string): TsSettings {
74
+ let out: string
75
+ try {
76
+ out = execFileSync(process.execPath, [tsc, '--showConfig', '-p', join(tree, tsconfig)], { cwd: tree, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 120_000, maxBuffer: 256 * 1024 * 1024 })
77
+ } catch (error) {
78
+ const output = `${(error as { stdout?: string }).stdout ?? ''}${(error as { stderr?: string }).stderr ?? ''}`.trim()
79
+ throw new Error(`tsc --showConfig 没跑成:${output.split('\n')[0] || (error as Error).message}`)
80
+ }
81
+ const shown = JSON.parse(out) as { compilerOptions?: Record<string, unknown>; include?: unknown; exclude?: unknown }
82
+ const options = shown.compilerOptions ?? {}
83
+ const on = (name: string): boolean => {
84
+ const value = options[name]
85
+ if (typeof value === 'boolean') return value
86
+ return STRICT_FAMILY.includes(name) && options.strict === true
87
+ }
88
+ return {
89
+ strict: Object.keys(STRICT).filter(on),
90
+ skipLibCheck: options.skipLibCheck === true,
91
+ include: strings(shown.include),
92
+ exclude: strings(shown.exclude),
93
+ }
94
+ }
95
+
96
+ /** 一个 tsconfig 的放松合成一项,一行一处。 */
97
+ export function tsconfigItem(tsconfig: string, before: TsSettings, now: TsSettings): ConfirmItem | undefined {
98
+ const lines: string[] = []
99
+ const off = before.strict.filter(name => !now.strict.includes(name))
100
+ // 关掉 strict 时跟着关掉的几项并成一行说
101
+ const along = off.includes('strict') ? off.filter(name => STRICT_FAMILY.includes(name)) : []
102
+ if (off.includes('strict')) lines.push(`关掉了 strict(${STRICT.strict})${along.length ? `,跟着关掉了 ${along.join('、')}` : ''}:以后这些类型问题都不再报`)
103
+ for (const name of off.filter(name => name !== 'strict' && !along.includes(name))) lines.push(`关掉了 ${name}(${STRICT[name]}):以后这类问题类型检查不再报`)
104
+ if (now.skipLibCheck && !before.skipLibCheck) lines.push('开了 skipLibCheck:以后不检查依赖库和 .d.ts 文件里的类型声明')
105
+ const dropped = before.include.filter(rule => !now.include.includes(rule))
106
+ if (dropped.length) lines.push(`include 去掉了 ${dropped.map(rule => `"${rule}"`).join('、')}:这些文件可能不再做类型检查`)
107
+ const excluded = now.exclude.filter(rule => !before.exclude.includes(rule))
108
+ if (excluded.length) lines.push(`exclude 新加了 ${excluded.map(rule => `"${rule}"`).join('、')}:这些文件可能不再做类型检查`)
109
+ if (lines.length === 0) return undefined
110
+ return {
111
+ before: stable(['tsconfig', tsconfig, before]),
112
+ after: stable(['tsconfig', tsconfig, now]),
113
+ text: [`类型检查的配置 ${tsconfig} 改松了:`, ...lines].join('\n'),
114
+ }
115
+ }
package/src/modules.ts CHANGED
@@ -1,10 +1,11 @@
1
- // 装配:把这个插件里的检查模块登记给底座。命令行入口(cli.ts、testcraft.ts、modwall.ts)、钩子入口(hooks/testpace.ts)和测试都先引用这个文件。
1
+ // 装配:把这个插件里的检查模块登记给底座。命令行入口(cli.ts、testcraft.ts、modwall.ts、codekeep.ts)、钩子入口(hooks/testpace.ts)和测试都先引用这个文件。
2
2
  // 底座(base/)不引用模块,模块之间也不互相引用;知道有哪些模块的只有这里。
3
3
  // 顺序就是整组里各段的先后(检查在前、全部测试在后)和会话说明里各模块的先后。
4
4
 
5
5
  import { registerModules } from './base/module.ts'
6
6
  import { craft } from './craft/index.ts'
7
+ import { keep } from './keep/index.ts'
7
8
  import { pace } from './pace/index.ts'
8
9
  import { wall } from './wall/index.ts'
9
10
 
10
- registerModules([wall, craft, pace])
11
+ registerModules([wall, craft, keep, pace])