gatelight 0.18.1 → 0.19.2

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])
package/src/wall/check.ts CHANGED
@@ -6,19 +6,23 @@ import { readFileSync, writeFileSync } from 'node:fs'
6
6
  import { join } from 'node:path'
7
7
  import { askUser } from '../base/confirm.ts'
8
8
  import { EXIT } from '../base/exit.ts'
9
+ import { pathsAt } from '../base/git.ts'
9
10
  import type { Repo } from '../base/repo.ts'
10
11
  import { CONFIG_PATH } from './config.ts'
11
12
  import { unreadSql } from './database.ts'
12
13
  import { codeRoleSwitches, migrationViolations } from './dbrules.ts'
13
14
  import { type ChangeFacts, type ProjectImports, readChanges, readImports } from './layermap.ts'
14
15
  import { miniprogramRefs } from './miniprogram.ts'
15
- import type { Layout } from './layout.ts'
16
+ import type { Layout, Module } from './layout.ts'
16
17
  import { looseningItems } from './loosen.ts'
17
18
  import { layoutOf, type Project } from './project.ts'
19
+ import { statements } from './sql.ts'
18
20
  import {
19
21
  BLOCKING_RULES,
20
22
  behaviorHints,
21
23
  entryExports,
24
+ existingChangeHints,
25
+ type MigrationAlter,
22
26
  type Hint,
23
27
  importViolations,
24
28
  RULE_NAMES,
@@ -121,13 +125,14 @@ export function analyze(project: Project, repo: Repo): Report {
121
125
  }
122
126
  let changes: ChangeFacts | undefined
123
127
  if (project.base && imports.ok) {
124
- const read = readChanges(project.root, project.base.commit)
125
- if (read.ok) {
126
- changes = read.value
128
+ const changed = readChanges(project.root, project.base.commit)
129
+ if (changed.ok) {
130
+ changes = changed.value
127
131
  report.behavior = behaviorHints(layout, changes)
132
+ report.behavior.push(...existingChangeHints(layout, changes, freshModules(project.root, project.base.commit, layout), migrationAlters(project.root, project.base.commit, layout, read)))
128
133
  report.entryExports = entryExports(layout, changes)
129
134
  } else {
130
- report.changesProblem = read.problem
135
+ report.changesProblem = changed.problem
131
136
  }
132
137
  }
133
138
  report.unchecked = [
@@ -138,6 +143,21 @@ export function analyze(project: Project, repo: Repo): Report {
138
143
  return report
139
144
  }
140
145
 
146
+ /** 这次新建的模块:分叉点上还没有它的目录。 */
147
+ function freshModules(root: string, base: string, layout: Layout): Set<string> {
148
+ const existed = pathsAt(root, base, layout.modules.map(module => module.dir))
149
+ return new Set(layout.modules.filter(module => !existed.has(module.dir)).map(module => module.id))
150
+ }
151
+
152
+ /** 已有模块这次新加的迁移里,改、删已有对象的句子(函数正文里的不算)。 */
153
+ function migrationAlters(root: string, base: string, layout: Layout, read: (path: string) => string): MigrationAlter[] {
154
+ const owned = layout.databases.flatMap(database => database.migrations).filter((migration): migration is { path: string; module: Module } => migration.module !== undefined)
155
+ const existed = pathsAt(root, base, owned.map(migration => migration.path))
156
+ return owned
157
+ .filter(migration => !existed.has(migration.path))
158
+ .flatMap(({ path, module }) => statements(read(path)).filter(statement => statement.alters && !statement.inFunction).map(statement => ({ module, path, line: statement.line })))
159
+ }
160
+
141
161
  /** R1–R3、R5、R6 都查了:配置能用、layermap imports 跑成了。只有这样的检查,越界列表才完整。 */
142
162
  function complete(report: Report): boolean {
143
163
  return report.configProblems.length === 0 && !report.removed && report.layermapProblem === undefined
package/src/wall/rules.ts CHANGED
@@ -3,7 +3,8 @@
3
3
  // R2 循环 模块之间有回环 拦
4
4
  // R3 方向反了 共享层引用模块或装配层;模块引用装配层;被管的代码引用 outside 或测试文件; 拦
5
5
  // 一个应用引用另一个应用的代码;外面一层的共享层引用任何应用的代码
6
- // R4 改已有行为 改了 B 已有导出函数的实现,A 在这次改动里新增了对它的调用 只提示
6
+ // R4 改已有行为 改了 B 已有导出函数的实现,A 在这次改动里新增了对它的调用; 只提示
7
+ // 这次新建了模块,同时改了已有模块里已有的声明、在它的新迁移里改删已有的对象
7
8
  // R5 没有归属 代码文件不在模块、共享层、装配层、映射和 outside 里 拦
8
9
  // R6 数据库越界 迁移文件那部分在 database.ts,库里的现状在 dbcheck.ts 拦
9
10
  // R1、R2、R3、R5、R6 看项目当前的全部代码;R4 和"入口新增导出"看这次改动(和分叉点比)。
@@ -17,7 +18,7 @@ import { type App, type ExceptionRule, field, moduleId, type Scheme } from './co
17
18
  import { posix } from 'node:path'
18
19
  import { inEntryLanguage, isCode, isStylesheet, UNREAD_DIRECTORIES } from './files.ts'
19
20
  import type { ChangeFacts, ProjectImports } from './layermap.ts'
20
- import { label, type Layout, type Owner } from './layout.ts'
21
+ import { label, type Layout, type Module, type Owner } from './layout.ts'
21
22
 
22
23
  export type Rule = 'R1' | 'R2' | 'R3' | 'R5' | 'R6'
23
24
 
@@ -338,19 +339,28 @@ export function unownedFiles(layout: Layout, files: readonly string[]): Violatio
338
339
  })
339
340
  }
340
341
 
342
+ type ChangedDeclaration = ChangeFacts['declarations'][number]
343
+
344
+ /** 这次改动里,同一个应用里别的模块新增的、对这个已有导出声明的调用(应用之间的调用另由 R3 拦)。 */
345
+ function newCallsFromOthers(layout: Layout, changes: ChangeFacts, declaration: ChangedDeclaration): ChangeFacts['calls'] {
346
+ const owner = layout.owner(declaration.path)
347
+ if (!declaration.exported || owner.kind !== 'module') return []
348
+ return changes.calls.filter(call => {
349
+ if (call.to !== declaration.path || call.declaration !== declaration.declaration) return false
350
+ const caller = layout.owner(call.from)
351
+ return caller.kind === 'module' && caller.app === owner.app && caller.name !== owner.name
352
+ })
353
+ }
354
+
341
355
  /** R4:这次改了 B 模块已有的导出函数的实现,同时 A 模块在这次改动里新增了对它的调用。只提示。 */
342
356
  export function behaviorHints(layout: Layout, changes: ChangeFacts): Hint[] {
343
357
  const hints: Hint[] = []
344
358
  for (const declaration of changes.declarations) {
345
- if (!declaration.exported) continue
346
359
  const owner = layout.owner(declaration.path)
347
360
  if (owner.kind !== 'module') continue
348
361
  const callee = moduleId(owner.app, owner.name)
349
- for (const call of changes.calls) {
350
- if (call.to !== declaration.path || call.declaration !== declaration.declaration) continue
351
- // 只看同一个应用里别的模块:应用之间的调用另由 R3 拦
352
- const caller = layout.owner(call.from)
353
- if (caller.kind !== 'module' || caller.app !== owner.app || caller.name === owner.name) continue
362
+ for (const call of newCallsFromOthers(layout, changes, declaration)) {
363
+ const caller = layout.owner(call.from) as Extract<Owner, { kind: 'module' }>
354
364
  hints.push({
355
365
  where: `${callee} 模块的 ${declaration.declaration}(${declaration.path}:${declaration.line})这次改了实现,${moduleId(caller.app, caller.name)} 模块在 ${site(call)} 新增了对它的调用`,
356
366
  fix: `为新功能就在 ${callee} 新增一个函数,不要给旧函数加分支;是正常的重构(比如改了签名、同时更新调用处)就不用管。`,
@@ -360,6 +370,52 @@ export function behaviorHints(layout: Layout, changes: ChangeFacts): Hint[] {
360
370
  return hints
361
371
  }
362
372
 
373
+ /** 新迁移里改、删已有对象的一句:所在的模块、位置。 */
374
+ export interface MigrationAlter {
375
+ module: Module
376
+ path: string
377
+ line: number
378
+ }
379
+
380
+ /**
381
+ * R4 的另一种:这次新建了模块,同一个应用里已有的模块又被改了已有的东西(声明、迁移里改删已有的对象)。
382
+ * 新模块要的应该在对方新增;改对方已有的,常是在对方的名单、类型、常量、约束、映射表里加上新模块的名字,
383
+ * 对方因此认识了用它的模块。这种依赖写在字符串里,看引用查不出来,模块之间经装配层接线时也没有调用可查,所以按"改了已有的"提示。
384
+ * 已经按调用提示过的(上面的 behaviorHints)不再列。
385
+ */
386
+ export function existingChangeHints(layout: Layout, changes: ChangeFacts, fresh: ReadonlySet<string>, alters: readonly MigrationAlter[]): Hint[] {
387
+ const freshIn = (app: string | undefined): string[] => layout.modules.filter(module => module.app === app && fresh.has(module.id)).map(module => module.id)
388
+ const touched = new Map<string, { app: string | undefined; id: string; where: string[] }>()
389
+ // 同一处(key)只说一次,位置写第一次见到的
390
+ const seen = new Set<string>()
391
+ const add = (app: string | undefined, id: string, key: string, where: string): void => {
392
+ if (seen.has(key)) return
393
+ seen.add(key)
394
+ const found = touched.get(id) ?? { app, id, where: [] }
395
+ found.where.push(where)
396
+ touched.set(id, found)
397
+ }
398
+ for (const declaration of changes.declarations) {
399
+ const owner = layout.owner(declaration.path)
400
+ if (owner.kind !== 'module') continue
401
+ const id = moduleId(owner.app, owner.name)
402
+ if (fresh.has(id) || freshIn(owner.app).length === 0) continue
403
+ // 对象字面量的属性报成 PAGES.deposit 这样,同一个文件里按顶层的名字说一次
404
+ const name = declaration.declaration.split('.')[0] as string
405
+ if (newCallsFromOthers(layout, changes, declaration).length) continue
406
+ add(owner.app, id, `${declaration.path}\0${name}`, `${name}(${declaration.path}:${declaration.line})`)
407
+ }
408
+ // 一个迁移文件只说一次,位置写第一句
409
+ for (const alter of alters) {
410
+ if (fresh.has(alter.module.id) || freshIn(alter.module.app).length === 0) continue
411
+ add(alter.module.app, alter.module.id, alter.path, `迁移里改、删了已有的对象(${alter.path}:${alter.line})`)
412
+ }
413
+ return [...touched.values()].map(({ app, id, where }) => ({
414
+ where: `这次新建了 ${freshIn(app).join('、')} 模块,同时改了已有的 ${id} 模块里已有的:${where.join('、')}`,
415
+ fix: `新模块要的在 ${id} 新增,不改它已有的。是在 ${id} 的名单、类型、常量、约束、映射表里加上新模块的名字的(${id} 因此认识了用它的模块),改成 ${id} 收一个值,或者由装配层接进来;是正常的重构就不用管。`,
416
+ }))
417
+ }
418
+
363
419
  /** 这次改动给哪些模块的入口新增了引用(转导出也算 import):不算违规,留作试点数据。 */
364
420
  export function entryExports(layout: Layout, changes: ChangeFacts): Hint[] {
365
421
  return changes.imports
@@ -121,7 +121,7 @@ function singleRules(scheme: Scheme): string[] {
121
121
  return [
122
122
  `- 模块根目录:${or(app.roots)},下面每个子目录是一个模块。新功能默认在模块根目录下新建一个模块目录,不用登记、不用问人。`,
123
123
  `- 要别的模块的能力,只从它的入口(模块目录下第一层的 ${app.entry.join('、')})引用;入口里没有,就在对方入口新增导出,作为单独的一小步。`,
124
- '- 不给别的模块的已有函数加分支:为新功能在对方新增一个函数。模块之间不能成环。',
124
+ '- 不给别的模块的已有函数加分支:为新功能在对方新增一个函数。不在别的模块的名单、类型、常量、映射表、数据库约束里写上新功能的名字:改成对方收一个值,或由装配层接进来。模块之间不能成环。',
125
125
  `- 共享层(${or(app.shared)})只放真正通用的东西,不能引用模块和装配层;装配层(${or(app.app)})把各模块接起来,别人不能引用它。正式代码不引用 outside(${or(scheme.outside)})和测试文件。`,
126
126
  ...databaseLines(scheme),
127
127
  ...CHECK_LINES,
@@ -135,7 +135,7 @@ function groupedRules(scheme: Scheme): string[] {
135
135
  `- 这个仓库有 ${scheme.apps.length} 个应用(${scheme.apps.map(app => app.name).join('、')}),每个应用各有一套模块,模块名只在应用内唯一,写成 应用名/模块名。应用之间不能引用代码(引用对方的模块、共享层、装配层都不行):几个应用共用的代码放进外面一层的共享层(${or(scheme.shared)}),它不能引用任何应用的代码;应用之间通过接口打交道。`,
136
136
  `- 模块根目录(${each(app => or(app.roots))}),下面每个子目录是一个模块。新功能默认在所在应用的模块根目录下新建一个模块目录,不用登记、不用问人。`,
137
137
  `- 要同一个应用里别的模块的能力,只从它的入口(模块目录下第一层的文件,${each(app => or(app.entry))})引用;入口里没有,就在对方入口新增导出,作为单独的一小步。`,
138
- '- 不给别的模块的已有函数加分支:为新功能在对方新增一个函数。同一个应用里的模块之间不能成环。',
138
+ '- 不给别的模块的已有函数加分支:为新功能在对方新增一个函数。不在别的模块的名单、类型、常量、映射表、数据库约束里写上新功能的名字:改成对方收一个值,或由装配层接进来。同一个应用里的模块之间不能成环。',
139
139
  `- 每个应用的共享层(${each(app => or(app.shared))})只放这个应用里真正通用的东西,不能引用模块和装配层;装配层(${each(app => or(app.app))})把这个应用的各模块接起来,别人不能引用它。正式代码不引用 outside(${or(scheme.outside)})和测试文件。`,
140
140
  ...databaseLines(scheme),
141
141
  ...CHECK_LINES,
package/src/wall/sql.ts CHANGED
@@ -11,6 +11,7 @@
11
11
  // setsSearchPath 这句改了 search_path(SET、RESET search_path,set_config('search_path', …))
12
12
  // switchesRole 这句切了身份(SET ROLE、RESET ROLE、SET SESSION AUTHORIZATION、set_config('role', …),也包括角色、库上设的 role;建函数、改函数时设的不算)
13
13
  // schemas 这句建的 schema(CREATE SCHEMA)
14
+ // alters 这句改、删已有的对象(ALTER、DROP、CREATE OR REPLACE 开头)
14
15
  // 不解析完整语法:切词(注释、字符串、带引号的名字、$$ 正文)后按分号分句,在句子里认几种固定的写法。
15
16
  // 函数、DO 块的正文当成 SQL 再读一遍,得到的句子单独列出(别名只在自己的句子里起作用)。
16
17
  // 拼出来再执行的 SQL(EXECUTE '...')是字符串,读不到。
@@ -58,6 +59,8 @@ export interface Statement {
58
59
  switchesRole: boolean
59
60
  /** CREATE SCHEMA 建的 schema。 */
60
61
  schemas: Name[]
62
+ /** 改、删已有的对象:ALTER、DROP、CREATE OR REPLACE 开头的句子。 */
63
+ alters: boolean
61
64
  }
62
65
 
63
66
  const WORD_START = /[A-Za-z_\u0080-\uffff]/
@@ -206,11 +209,12 @@ const KINDS = new Set(['table', 'view', 'function', 'procedure', 'sequence', 'ty
206
209
  const MODIFIERS = new Set(['or', 'replace', 'global', 'local', 'temp', 'temporary', 'unlogged', 'foreign', 'recursive', 'materialized', 'unique', 'concurrently'])
207
210
 
208
211
  function statement(tokens: Token[]): Statement[] {
209
- const found: Statement = { line: tokens[0]?.line ?? 0, refs: [], targets: [], writes: [], tables: [], view: false, aliases: [], relations: [], setsSearchPath: false, switchesRole: false, schemas: [], inFunction: false }
212
+ const found: Statement = { line: tokens[0]?.line ?? 0, refs: [], targets: [], writes: [], tables: [], view: false, aliases: [], relations: [], setsSearchPath: false, switchesRole: false, schemas: [], inFunction: false, alters: false }
210
213
  const nested: Statement[] = []
211
214
  const creates = isWord(tokens[0], 'create')
212
215
  let at = 1
213
216
  if (creates && isWord(tokens[at], 'or') && isWord(tokens[at + 1], 'replace')) at += 2
217
+ found.alters = isWord(tokens[0], 'alter', 'drop') || at === 3
214
218
  const isFunction = creates && isWord(tokens[at], 'function', 'procedure')
215
219
  // DO 块的正文是句子里第一个字符串(DO $$…$$、DO LANGUAGE x '…')
216
220
  let doBody = isWord(tokens[0], 'do')