dsh-project-flow 0.9.2 → 0.10.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.
- package/CHANGELOG.md +0 -0
- package/README.md +25 -0
- package/checks/assertion.mjs +104 -0
- package/checks/command.mjs +416 -0
- package/checks/requirement.mjs +91 -0
- package/commands/slash.mjs +754 -0
- package/commands/steer.mjs +43 -0
- package/config/settings.mjs +217 -0
- package/docs/DETAIL.md +2 -0
- package/docs/FEATURES.md +9 -6
- package/docs/anchors/file-whitelist.md +1 -1
- package/http/routes.mjs +252 -0
- package/index.js +173 -8538
- package/issues/issue.mjs +322 -0
- package/package.json +16 -1
- package/persistence/lock.mjs +67 -0
- package/persistence/log.mjs +43 -0
- package/persistence/recovery.mjs +118 -0
- package/persistence/state.mjs +202 -0
- package/pricing/estimate.mjs +72 -0
- package/prompts/rules.mjs +192 -0
- package/rollback/ledger.mjs +237 -0
- package/runner/pipeline.mjs +1190 -0
- package/runner/stage.mjs +370 -0
- package/runner/tools/context.mjs +64 -0
- package/runner/tools/decorate-cost.mjs +49 -0
- package/runner/tools/doctor.mjs +59 -0
- package/runner/tools/estimate.mjs +63 -0
- package/runner/tools/execute-run.mjs +255 -0
- package/runner/tools/models.mjs +55 -0
- package/runner/tools/resume.mjs +136 -0
- package/runner/tools/rollback.mjs +291 -0
- package/runner/tools/run.mjs +262 -0
- package/runner/tools/set.mjs +65 -0
- package/runner/tools/snapshots.mjs +83 -0
- package/runner/tools/status.mjs +70 -0
- package/runner/tools.mjs +94 -0
- package/shared/constants.mjs +273 -0
- package/shared/tool.mjs +32 -0
- package/shared/util.mjs +231 -0
- package/snapshot/repo.mjs +452 -0
- package/state/registry.mjs +40 -0
- package/tests/aesthetic.test.mjs +20 -12
- package/tests/apply-wiring.test.mjs +172 -0
- package/tests/assertions-e2e.mjs +2 -1
- package/tests/atomic-write.test.mjs +129 -0
- package/tests/client-bundle.test.mjs +3 -3
- package/tests/command-whitelist.test.mjs +135 -0
- package/tests/contract.test.mjs +2 -2
- package/tests/desktop.test.mjs +2 -2
- package/tests/domains.test.mjs +10 -7
- package/tests/e2e.mjs +2 -1
- package/tests/extra-phase.test.mjs +2 -2
- package/tests/feedback.test.mjs +2 -1
- package/tests/flow-gate.test.mjs +16 -56
- package/tests/issues-e2e.mjs +2 -1
- package/tests/panel-independence.test.mjs +2 -2
- package/tests/panel-report.test.mjs +2 -2
- package/tests/paths.mjs +70 -1
- package/tests/preview-path.test.mjs +2 -1
- package/tests/qa-assertions.test.mjs +10 -3
- package/tests/run-all.mjs +6 -0
- package/tests/snapshot-core.test.mjs +234 -0
- package/tests/stage-model.test.mjs +2 -2
- package/tests/steer-command.test.mjs +151 -0
- package/tests/stop-resume.test.mjs +7 -2
- package/tests/watch-root.test.mjs +2 -1
- package/ui/prompt.mjs +101 -0
- package/workspace/models.mjs +111 -0
- package/workspace/panel.mjs +359 -0
- package/workspace/paths.mjs +393 -0
- package/workspace/resume.mjs +107 -0
package/shared/util.mjs
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 小工具:时间、原子写、错误取信、YAML 标量、段落切片。没有业务含义。
|
|
3
|
+
*/
|
|
4
|
+
import { writeFile, rename, rm, readFile, stat } from 'node:fs/promises'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { createHash } from 'node:crypto'
|
|
7
|
+
import { readFileSync } from 'node:fs'
|
|
8
|
+
import { DEFAULT_CHECK_TAIL_CHARS } from './constants.mjs'
|
|
9
|
+
|
|
10
|
+
export function nowIso() {
|
|
11
|
+
return new Date().toISOString()
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 原子写:先写 tmp 再 rename。
|
|
16
|
+
*
|
|
17
|
+
* rename 在 Windows 上会因为目标被别的句柄占着而失败,这时退回到直接覆盖:
|
|
18
|
+
* 覆盖成功就是成功了,不再把原来的 rename 错误抛出去——文件已经是新内容,
|
|
19
|
+
* 却告诉调用方「没写成」,上层只会白重试一遍,重试时还可能读到半截状态。
|
|
20
|
+
* 只有覆盖也失败,才抛覆盖那个错误。
|
|
21
|
+
*
|
|
22
|
+
* io 只给测试注入用;生产调用不传。
|
|
23
|
+
*/
|
|
24
|
+
export async function writeFileAtomic(path, text, io = {}) {
|
|
25
|
+
const write = io.writeFile ?? writeFile
|
|
26
|
+
const move = io.rename ?? rename
|
|
27
|
+
const remove = io.rm ?? rm
|
|
28
|
+
const tmp = `${path}.tmp-${process.pid}-${Date.now()}`
|
|
29
|
+
await write(tmp, text, 'utf8')
|
|
30
|
+
try {
|
|
31
|
+
await move(tmp, path)
|
|
32
|
+
return
|
|
33
|
+
} catch {
|
|
34
|
+
try {
|
|
35
|
+
await write(path, text, 'utf8')
|
|
36
|
+
} catch (writeError) {
|
|
37
|
+
await remove(tmp, { force: true }).catch(() => {})
|
|
38
|
+
throw writeError
|
|
39
|
+
}
|
|
40
|
+
await remove(tmp, { force: true }).catch(() => {})
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function messageOf(error) {
|
|
45
|
+
if (error instanceof Error) return error.message
|
|
46
|
+
return String(error)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function sleep(ms, signal) {
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
if (signal?.aborted === true) {
|
|
52
|
+
reject(new Error('aborted'))
|
|
53
|
+
return
|
|
54
|
+
}
|
|
55
|
+
const finish = () => {
|
|
56
|
+
clearTimeout(timer)
|
|
57
|
+
signal?.removeEventListener('abort', onAbort)
|
|
58
|
+
}
|
|
59
|
+
const onAbort = () => {
|
|
60
|
+
finish()
|
|
61
|
+
reject(new Error('aborted'))
|
|
62
|
+
}
|
|
63
|
+
const timer = setTimeout(() => {
|
|
64
|
+
finish()
|
|
65
|
+
resolve()
|
|
66
|
+
}, ms)
|
|
67
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function isAlive(pid) {
|
|
72
|
+
if (typeof pid !== 'number' || pid <= 0) return false
|
|
73
|
+
try {
|
|
74
|
+
process.kill(pid, 0)
|
|
75
|
+
return true
|
|
76
|
+
} catch (error) {
|
|
77
|
+
return error?.code === 'EPERM'
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function textOf(output) {
|
|
82
|
+
if (!Array.isArray(output)) return ''
|
|
83
|
+
return output
|
|
84
|
+
.filter(block => block !== null && typeof block === 'object' && block.type === 'text')
|
|
85
|
+
.map(block => block.text)
|
|
86
|
+
.join('\n')
|
|
87
|
+
.trim()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function parseJsonBlock(text, marker) {
|
|
91
|
+
const fence = /```json\s*([\s\S]*?)```/gi
|
|
92
|
+
const blocks = []
|
|
93
|
+
let match
|
|
94
|
+
while ((match = fence.exec(text)) !== null) blocks.push(match[1].trim())
|
|
95
|
+
|
|
96
|
+
const parse = raw => {
|
|
97
|
+
if (raw === '') return undefined
|
|
98
|
+
try {
|
|
99
|
+
return JSON.parse(raw)
|
|
100
|
+
} catch {
|
|
101
|
+
const start = raw.indexOf('{')
|
|
102
|
+
const end = raw.lastIndexOf('}')
|
|
103
|
+
if (start === -1 || end === -1 || end <= start) return undefined
|
|
104
|
+
try {
|
|
105
|
+
return JSON.parse(raw.slice(start, end + 1))
|
|
106
|
+
} catch {
|
|
107
|
+
return undefined
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (blocks.length > 0) {
|
|
113
|
+
if (marker !== undefined) {
|
|
114
|
+
for (let index = blocks.length - 1; index >= 0; index -= 1) {
|
|
115
|
+
const parsed = parse(blocks[index])
|
|
116
|
+
if (parsed !== null && typeof parsed === 'object' && marker in parsed) return parsed
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
for (let index = blocks.length - 1; index >= 0; index -= 1) {
|
|
120
|
+
const parsed = parse(blocks[index])
|
|
121
|
+
if (parsed !== undefined) return parsed
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return parse((blocks.at(-1) ?? text).trim())
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export const filled = value => typeof value === 'string' && value.trim() !== ''
|
|
128
|
+
|
|
129
|
+
export function splitFrontMatter(text) {
|
|
130
|
+
if (typeof text !== 'string') return { front: '', body: '' }
|
|
131
|
+
const trimmed = text.replace(/^\uFEFF/u, '')
|
|
132
|
+
if (!trimmed.startsWith('---')) return { front: '', body: trimmed }
|
|
133
|
+
const firstBreak = trimmed.indexOf('\n')
|
|
134
|
+
if (firstBreak === -1) return { front: '', body: trimmed }
|
|
135
|
+
const end = trimmed.indexOf('\n---', firstBreak)
|
|
136
|
+
if (end === -1) return { front: '', body: trimmed }
|
|
137
|
+
return {
|
|
138
|
+
front: trimmed.slice(firstBreak + 1, end),
|
|
139
|
+
body: trimmed.slice(end + 4).replace(/^\n+/u, ''),
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function unquoteScalar(value) {
|
|
144
|
+
const text = typeof value === 'string' ? value.trim() : ''
|
|
145
|
+
if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) {
|
|
146
|
+
try {
|
|
147
|
+
return String(JSON.parse(text))
|
|
148
|
+
} catch {
|
|
149
|
+
return text.slice(1, -1)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (text.length >= 2 && text.startsWith("'") && text.endsWith("'")) return text.slice(1, -1)
|
|
153
|
+
return text
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function quoteScalar(value) {
|
|
157
|
+
const text = typeof value === 'string' ? value : String(value ?? '')
|
|
158
|
+
return text === '' ? "''" : JSON.stringify(text)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function extractSection(text, heading, prefix = false) {
|
|
162
|
+
if (typeof text !== 'string' || text === '') return ''
|
|
163
|
+
const index = text.indexOf(heading)
|
|
164
|
+
if (index === -1) return ''
|
|
165
|
+
if (prefix) return text.slice(0, index).trim()
|
|
166
|
+
return text.slice(index + heading.length).trim()
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function withoutHeading(text) {
|
|
170
|
+
if (typeof text !== 'string') return ''
|
|
171
|
+
const match = /^#\s[^\n]*\n+/u.exec(text)
|
|
172
|
+
return (match === null ? text : text.slice(match[0].length)).trim()
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function tailOf(text, limit) {
|
|
176
|
+
const value = typeof text === 'string' ? text : ''
|
|
177
|
+
const max = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : DEFAULT_CHECK_TAIL_CHARS
|
|
178
|
+
return value.length <= max ? value : value.slice(value.length - max)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function normalizePaths(raw) {
|
|
182
|
+
if (!Array.isArray(raw)) return []
|
|
183
|
+
return raw
|
|
184
|
+
.map(item => (typeof item === 'string' ? item.trim() : ''))
|
|
185
|
+
.map(item => item.replace(/^\.\//u, '').replace(/\\/gu, '/'))
|
|
186
|
+
.filter(item => item !== '' && !item.startsWith('/') && !/^[a-zA-Z]:/u.test(item) && !item.includes('..'))
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function normalizeIssueText(value) {
|
|
190
|
+
return String(value ?? '').replace(/\s+/gu, ' ').trim()
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function stateDir(cwd, project) {
|
|
194
|
+
return join(cwd, '.project-flow', project)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export async function fileSha256(path) {
|
|
198
|
+
try {
|
|
199
|
+
const data = await readFile(path)
|
|
200
|
+
return createHash('sha256').update(data).digest('hex')
|
|
201
|
+
} catch {
|
|
202
|
+
return null
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function fileSha256Sync(path) {
|
|
207
|
+
try {
|
|
208
|
+
const data = readFileSync(path)
|
|
209
|
+
return createHash('sha256').update(data).digest('hex')
|
|
210
|
+
} catch {
|
|
211
|
+
return null
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export async function dirExists(path) {
|
|
216
|
+
try {
|
|
217
|
+
return (await stat(path)).isDirectory()
|
|
218
|
+
} catch {
|
|
219
|
+
return false
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export const PKG_VERSION = (() => {
|
|
224
|
+
try {
|
|
225
|
+
const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
|
|
226
|
+
return typeof pkg.version === 'string' ? pkg.version : ''
|
|
227
|
+
} catch {
|
|
228
|
+
return ''
|
|
229
|
+
}
|
|
230
|
+
})()
|
|
231
|
+
|
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 快照仓:单独一棵 git 树,和用户的 .git 隔开;保留上限到线自动清理。
|
|
3
|
+
*/
|
|
4
|
+
import { readdir, stat, mkdir, writeFile, rm, rmdir } from 'node:fs/promises'
|
|
5
|
+
import { basename, dirname, join, relative } from 'node:path'
|
|
6
|
+
import { execFile } from 'node:child_process'
|
|
7
|
+
import { DEFAULT_SNAPSHOT_EXCLUDES, SNAPSHOT_MAX_BYTES, SNAPSHOT_MAX_FILES } from '../shared/constants.mjs'
|
|
8
|
+
import { messageOf, normalizePaths, stateDir } from '../shared/util.mjs'
|
|
9
|
+
|
|
10
|
+
export async function measureWorkspace(dir, excludes) {
|
|
11
|
+
const skip = new Set(excludes.map(line => line.replace(/\/$/u, '')))
|
|
12
|
+
let files = 0
|
|
13
|
+
let bytes = 0
|
|
14
|
+
let queue = [{ path: '', depth: 0 }]
|
|
15
|
+
while (queue.length > 0) {
|
|
16
|
+
const next = []
|
|
17
|
+
for (const current of queue) {
|
|
18
|
+
let dirents
|
|
19
|
+
try {
|
|
20
|
+
dirents = await readdir(current.path === '' ? dir : join(dir, current.path), { withFileTypes: true })
|
|
21
|
+
} catch {
|
|
22
|
+
continue
|
|
23
|
+
}
|
|
24
|
+
for (const dirent of dirents) {
|
|
25
|
+
const relative = current.path === '' ? dirent.name : `${current.path}/${dirent.name}`
|
|
26
|
+
if (dirent.isDirectory()) {
|
|
27
|
+
if (skip.has(dirent.name)) continue
|
|
28
|
+
if (current.depth + 1 > 6) continue
|
|
29
|
+
next.push({ path: relative, depth: current.depth + 1 })
|
|
30
|
+
continue
|
|
31
|
+
}
|
|
32
|
+
if (!dirent.isFile()) continue
|
|
33
|
+
files += 1
|
|
34
|
+
if (files > SNAPSHOT_MAX_FILES) return { files, bytes, over: 'files' }
|
|
35
|
+
try {
|
|
36
|
+
bytes += (await stat(join(dir, relative))).size
|
|
37
|
+
} catch {
|
|
38
|
+
// A file that vanished mid-walk contributes nothing.
|
|
39
|
+
}
|
|
40
|
+
if (bytes > SNAPSHOT_MAX_BYTES) return { files, bytes, over: 'bytes' }
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
queue = next
|
|
44
|
+
}
|
|
45
|
+
return { files, bytes, over: '' }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function git(args, options = {}) {
|
|
49
|
+
const { cwd, timeoutMs = 120000 } = options
|
|
50
|
+
return new Promise(resolve => {
|
|
51
|
+
execFile('git', args, {
|
|
52
|
+
cwd,
|
|
53
|
+
timeout: timeoutMs,
|
|
54
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
55
|
+
windowsHide: true,
|
|
56
|
+
env: {
|
|
57
|
+
...process.env,
|
|
58
|
+
// A user-level git config must not hijack the snapshot repo.
|
|
59
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
60
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
61
|
+
GIT_OPTIONAL_LOCKS: '0',
|
|
62
|
+
},
|
|
63
|
+
}, (error, stdout, stderr) => {
|
|
64
|
+
resolve({
|
|
65
|
+
ok: error === null || error === undefined,
|
|
66
|
+
code: error?.code ?? 0,
|
|
67
|
+
stdout: typeof stdout === 'string' ? stdout : String(stdout ?? ''),
|
|
68
|
+
stderr: typeof stderr === 'string' ? stderr : String(stderr ?? ''),
|
|
69
|
+
message: error === undefined ? '' : messageOf(error),
|
|
70
|
+
})
|
|
71
|
+
})
|
|
72
|
+
})
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function snapshotRepo(cwd, project) {
|
|
76
|
+
return join(stateDir(cwd, project), 'snap.git')
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export let gitProbe
|
|
80
|
+
|
|
81
|
+
export async function gitAvailable() {
|
|
82
|
+
if (gitProbe === undefined) {
|
|
83
|
+
const result = await git(['--version'], { timeoutMs: 15000 })
|
|
84
|
+
gitProbe = result.ok && /git version/u.test(result.stdout)
|
|
85
|
+
}
|
|
86
|
+
return gitProbe
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function snapshotCommand(cwd, project, args, options = {}) {
|
|
90
|
+
const dir = snapshotRepo(cwd, project)
|
|
91
|
+
return git([`--git-dir=${dir}`, `--work-tree=${cwd}`, ...args], { cwd, ...options })
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function ensureSnapshotRepo(cwd, project, excludes) {
|
|
95
|
+
const dir = snapshotRepo(cwd, project)
|
|
96
|
+
await mkdir(dir, { recursive: true })
|
|
97
|
+
const head = await git(['--git-dir', dir, 'rev-parse', '--git-dir'], { cwd })
|
|
98
|
+
if (!head.ok) {
|
|
99
|
+
const init = await git(['init', '--bare', '--quiet', dir], { cwd })
|
|
100
|
+
if (!init.ok) return { ok: false, reason: `初始化快照仓库失败:${init.stderr.trim() || init.message}` }
|
|
101
|
+
// A bare repo with core.worktree set is contradictory: git warns on every
|
|
102
|
+
// command. Clearing core.bare keeps `--work-tree` working without the noise.
|
|
103
|
+
await git(['--git-dir', dir, 'config', 'core.bare', 'false'], { cwd })
|
|
104
|
+
await git(['--git-dir', dir, 'config', 'core.worktree', cwd], { cwd })
|
|
105
|
+
await git(['--git-dir', dir, 'config', 'user.name', 'dsh-project-flow'], { cwd })
|
|
106
|
+
await git(['--git-dir', dir, 'config', 'user.email', 'project-flow@localhost'], { cwd })
|
|
107
|
+
await git(['--git-dir', dir, 'config', 'core.autocrlf', 'false'], { cwd })
|
|
108
|
+
await git(['--git-dir', dir, 'config', 'core.safecrlf', 'false'], { cwd })
|
|
109
|
+
} else {
|
|
110
|
+
// The repo already exists, but it may carry an `index.lock` from a git
|
|
111
|
+
// process that was killed mid-snapshot. Nothing of ours runs concurrently
|
|
112
|
+
// here, so a lock at this point is always stale and would otherwise make
|
|
113
|
+
// every later snapshot of this project fail forever.
|
|
114
|
+
await clearStaleIndexLock(cwd, project)
|
|
115
|
+
}
|
|
116
|
+
// 中文路径一律按字面输出,不转成 "\346\226\207" 那种八进制转义。
|
|
117
|
+
// 放在 init 分支之外:每次调用都设一遍,因为 log / read-tree / checkout
|
|
118
|
+
// 这些不经过 snapshotDiff 的调用也会碰到同一个路径。
|
|
119
|
+
await git(['--git-dir', dir, 'config', 'core.quotepath', 'false'], { cwd })
|
|
120
|
+
const list = excludes.length === 0 ? DEFAULT_SNAPSHOT_EXCLUDES : excludes
|
|
121
|
+
await mkdir(join(dir, 'info'), { recursive: true })
|
|
122
|
+
await writeFile(join(dir, 'info', 'exclude'), `${list.join('\n')}\n`, 'utf8')
|
|
123
|
+
return { ok: true, dir }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function snapshotLabel(label) {
|
|
127
|
+
return String(label ?? '').replace(/\r?\n/gu, ' ').trim().slice(0, 200) || '未命名快照'
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export async function takeSnapshot(cwd, project, label, options = {}) {
|
|
131
|
+
const { excludes = DEFAULT_SNAPSHOT_EXCLUDES, allowEmpty = false, keep } = options
|
|
132
|
+
if (await gitAvailable() !== true) {
|
|
133
|
+
return { ok: false, reason: '这台机器上没有可用的 git,快照与回滚不可用' }
|
|
134
|
+
}
|
|
135
|
+
const prepared = await ensureSnapshotRepo(cwd, project, excludes)
|
|
136
|
+
if (prepared.ok !== true) return prepared
|
|
137
|
+
|
|
138
|
+
// Refuse before staging a tree that cannot finish: a timed-out `git add` is
|
|
139
|
+
// not harmless, it dies holding `index.lock` and breaks the next snapshot too.
|
|
140
|
+
const size = await measureWorkspace(cwd, excludes)
|
|
141
|
+
if (size.over !== '') {
|
|
142
|
+
// The walk stops early once a limit is crossed, so these are lower bounds,
|
|
143
|
+
// not totals; say so rather than reporting a misleadingly small count.
|
|
144
|
+
const detail = size.over === 'files'
|
|
145
|
+
? `文件数已超过上限 ${SNAPSHOT_MAX_FILES}`
|
|
146
|
+
: `体积已超过上限 ${Math.round(SNAPSHOT_MAX_BYTES / 1024 / 1024)} MB`
|
|
147
|
+
return {
|
|
148
|
+
ok: false,
|
|
149
|
+
reason: `工作区${detail}(扫到 ${size.files} 个文件时已 ${(size.bytes / 1024 / 1024 / 1024).toFixed(1)} GB,未扫完),`
|
|
150
|
+
+ '打快照会超时并留下锁文件,因此跳过。用 snapshotExcludes 排掉大目录后可恢复回滚能力。',
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const add = await snapshotCommand(cwd, project, ['add', '-A'], { timeoutMs: 600000 })
|
|
155
|
+
if (!add.ok) {
|
|
156
|
+
// A killed process leaves `index.lock` behind, and every later snapshot of
|
|
157
|
+
// this project then fails forever with "File exists". The lock is only ours
|
|
158
|
+
// to clear when no git is running against this snapshot repo, so retry once
|
|
159
|
+
// after removing it; the operation is idempotent, so a retry is safe.
|
|
160
|
+
if (/index\.lock/iu.test(add.stderr) && await clearStaleIndexLock(cwd, project)) {
|
|
161
|
+
const retried = await snapshotCommand(cwd, project, ['add', '-A'], { timeoutMs: 600000 })
|
|
162
|
+
if (retried.ok) return finishSnapshot(cwd, project, label, { allowEmpty, keep })
|
|
163
|
+
return { ok: false, reason: `暂存工作区失败:${retried.stderr.trim() || retried.message}` }
|
|
164
|
+
}
|
|
165
|
+
return { ok: false, reason: `暂存工作区失败:${add.stderr.trim() || add.message}` }
|
|
166
|
+
}
|
|
167
|
+
return finishSnapshot(cwd, project, label, { allowEmpty, keep })
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export async function clearStaleIndexLock(cwd, project) {
|
|
171
|
+
try {
|
|
172
|
+
await rm(join(snapshotRepo(cwd, project), 'index.lock'), { force: true })
|
|
173
|
+
return true
|
|
174
|
+
} catch {
|
|
175
|
+
return false
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export async function pruneSnapshots(cwd, project, keep) {
|
|
180
|
+
if (await gitAvailable() !== true) return { ok: false, reason: '没有可用的 git' }
|
|
181
|
+
if (!Number.isInteger(keep) || keep <= 0) return { ok: true, pruned: 0, count: undefined }
|
|
182
|
+
|
|
183
|
+
const total = await snapshotCommand(cwd, project, ['rev-list', '--count', 'HEAD'])
|
|
184
|
+
if (!total.ok) return { ok: false, reason: '读不到快照数量' }
|
|
185
|
+
const count = Number(total.stdout.trim())
|
|
186
|
+
if (!Number.isFinite(count) || count <= keep) return { ok: true, pruned: 0, count }
|
|
187
|
+
|
|
188
|
+
const head = await snapshotCommand(cwd, project, ['rev-parse', 'HEAD'])
|
|
189
|
+
if (!head.ok) return { ok: false, reason: '读不到 HEAD' }
|
|
190
|
+
|
|
191
|
+
// 第 keep 个提交(从 1 数):它将成为新的「最早那一张」。
|
|
192
|
+
const boundary = await snapshotCommand(cwd, project, ['rev-list', `--max-count=1`, `--skip=${keep - 1}`, 'HEAD'])
|
|
193
|
+
if (!boundary.ok || boundary.stdout.trim() === '') return { ok: true, pruned: 0, count }
|
|
194
|
+
const boundarySha = boundary.stdout.trim()
|
|
195
|
+
|
|
196
|
+
// 用 boundary 那棵树造一个没有父提交的新根,再把边界点之后的提交接到它上面。
|
|
197
|
+
const tree = await snapshotCommand(cwd, project, ['rev-parse', `${boundarySha}^{tree}`])
|
|
198
|
+
if (!tree.ok) return { ok: false, reason: '读不到边界提交的树' }
|
|
199
|
+
const root = await snapshotCommand(cwd, project, ['commit-tree', tree.stdout.trim(), '-m', snapshotLabel('更早的快照已截断')])
|
|
200
|
+
if (!root.ok) return { ok: false, reason: '造新根失败' }
|
|
201
|
+
|
|
202
|
+
// cherry-pick 的形态太重,这里用最朴素的办法:只保留最近 keep 个 commit 的
|
|
203
|
+
// 树内容,把它们逐个接到新根上。数量不大(keep 默认 40),够用且可回退。
|
|
204
|
+
const recent = await snapshotCommand(cwd, project, ['rev-list', `--max-count=${keep - 1}`, boundarySha])
|
|
205
|
+
if (!recent.ok) return { ok: false, reason: '读不到要保留的提交' }
|
|
206
|
+
let parent = root.stdout.trim()
|
|
207
|
+
for (const sha of recent.stdout.trim().split('\n').filter(line => line !== '').reverse()) {
|
|
208
|
+
const t = await snapshotCommand(cwd, project, ['rev-parse', `${sha}^{tree}`])
|
|
209
|
+
if (!t.ok) continue
|
|
210
|
+
const subject = await snapshotCommand(cwd, project, ['log', '-1', '--pretty=format:%s', sha])
|
|
211
|
+
const next = await snapshotCommand(cwd, project, [
|
|
212
|
+
'commit-tree', t.stdout.trim(), '-p', parent, '-m', subject.ok ? subject.stdout.trim() : '快照',
|
|
213
|
+
])
|
|
214
|
+
if (!next.ok) continue
|
|
215
|
+
parent = next.stdout.trim()
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const moved = await snapshotCommand(cwd, project, ['reset', '--soft', parent])
|
|
219
|
+
if (!moved.ok) {
|
|
220
|
+
// 没动过 HEAD 的话这里根本不会失败;真失败了就把 HEAD 拉回原处。
|
|
221
|
+
await snapshotCommand(cwd, project, ['reset', '--soft', head.stdout.trim()])
|
|
222
|
+
return { ok: false, reason: '接新根失败,已回到截断前' }
|
|
223
|
+
}
|
|
224
|
+
await snapshotCommand(cwd, project, ['gc', '--prune=now', '--quiet'], { timeoutMs: 300000 })
|
|
225
|
+
const after = await snapshotCommand(cwd, project, ['rev-list', '--count', 'HEAD'])
|
|
226
|
+
return { ok: true, pruned: count - keep, count: after.ok ? Number(after.stdout.trim()) : undefined }
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export async function finishSnapshot(cwd, project, label, options = {}) {
|
|
230
|
+
const { allowEmpty = false, keep } = options
|
|
231
|
+
const head = await snapshotCommand(cwd, project, ['rev-parse', 'HEAD'])
|
|
232
|
+
const diff = await snapshotCommand(cwd, project, ['diff', '--cached', '--quiet'])
|
|
233
|
+
const dirty = !diff.ok // `--quiet` exits 1 when there are staged changes
|
|
234
|
+
if (!dirty && !allowEmpty && head.ok) {
|
|
235
|
+
return { ok: true, commit: head.stdout.trim(), reused: true }
|
|
236
|
+
}
|
|
237
|
+
const commit = await snapshotCommand(cwd, project, ['commit', '--quiet', '--allow-empty', '-m', snapshotLabel(label)], { timeoutMs: 600000 })
|
|
238
|
+
if (!commit.ok) {
|
|
239
|
+
return { ok: false, reason: `建立快照失败:${commit.stderr.trim() || commit.message}` }
|
|
240
|
+
}
|
|
241
|
+
const after = await snapshotCommand(cwd, project, ['rev-parse', 'HEAD'])
|
|
242
|
+
// 顺手压一次历史:失败不影响这次快照已经建好这件事。
|
|
243
|
+
let pruned
|
|
244
|
+
if (Number.isInteger(keep) && keep > 0) {
|
|
245
|
+
pruned = await pruneSnapshots(cwd, project, keep).catch(() => undefined)
|
|
246
|
+
}
|
|
247
|
+
return { ok: true, commit: after.stdout.trim(), reused: false, ...(pruned === undefined ? {} : { pruned }) }
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export async function listSnapshots(cwd, project, limit = 50) {
|
|
251
|
+
if (await gitAvailable() !== true) return []
|
|
252
|
+
const result = await snapshotCommand(cwd, project, [
|
|
253
|
+
'log', `--max-count=${limit}`,
|
|
254
|
+
'--pretty=format:%H%x09%cI%x09%s',
|
|
255
|
+
])
|
|
256
|
+
if (!result.ok) return []
|
|
257
|
+
return result.stdout
|
|
258
|
+
.split(/\r?\n/u)
|
|
259
|
+
.filter(line => line.trim() !== '')
|
|
260
|
+
.map(line => {
|
|
261
|
+
const [commit, at, ...rest] = line.split('\t')
|
|
262
|
+
return { commit, at, label: rest.join('\t') }
|
|
263
|
+
})
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export async function resolveSnapshot(cwd, project, rev) {
|
|
267
|
+
if (typeof rev !== 'string' || rev.trim() === '') return undefined
|
|
268
|
+
const result = await snapshotCommand(cwd, project, ['rev-parse', '--verify', `${rev.trim()}^{commit}`])
|
|
269
|
+
if (!result.ok) return undefined
|
|
270
|
+
return result.stdout.trim()
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** git 遇到带特殊字符的路径时会整体加一对引号包起来;只去外壳,不做复杂反转义。 */
|
|
274
|
+
function unquoteGitPath(raw) {
|
|
275
|
+
const text = String(raw ?? '')
|
|
276
|
+
if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) return text.slice(1, -1)
|
|
277
|
+
return text
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* 工作区相对快照的差异,**含从未被跟踪过的新文件**。
|
|
282
|
+
*
|
|
283
|
+
* 只跑 `git diff <commit>` 是不够的:那比较的是提交和索引,一个从没 add 过的
|
|
284
|
+
* 文件两边都没有,于是它既不出现、回滚时也不会被删掉——「新建的文件回滚后
|
|
285
|
+
* 还在」就是这么来的。未跟踪文件靠 `ls-files --others` 单独列一遍补上。
|
|
286
|
+
*
|
|
287
|
+
* 两条命令都关掉 quotepath:默认 git 会把中文路径输出成 "\346\226\207"
|
|
288
|
+
* 这样的八进制转义,拿这种字符串去 rm / checkout 一定找不到文件。
|
|
289
|
+
*/
|
|
290
|
+
export async function snapshotDiff(cwd, project, commit) {
|
|
291
|
+
const entries = []
|
|
292
|
+
const seen = new Set()
|
|
293
|
+
const push = (status, path) => {
|
|
294
|
+
if (path === '' || seen.has(path)) return
|
|
295
|
+
seen.add(path)
|
|
296
|
+
entries.push({ status, path })
|
|
297
|
+
}
|
|
298
|
+
const map = { A: '新增', M: '修改', D: '删除', T: '类型变化' }
|
|
299
|
+
|
|
300
|
+
const tracked = await snapshotCommand(cwd, project, [
|
|
301
|
+
'-c', 'core.quotepath=false', 'diff', '--name-status', '--no-renames', commit, '--',
|
|
302
|
+
], { timeoutMs: 300000 })
|
|
303
|
+
if (tracked.ok) {
|
|
304
|
+
for (const line of tracked.stdout.split(/\r?\n/u)) {
|
|
305
|
+
if (line.trim() === '') continue
|
|
306
|
+
const [status, ...rest] = line.split('\t')
|
|
307
|
+
push(map[status?.[0]] ?? status, unquoteGitPath(rest.join('\t').trim()))
|
|
308
|
+
}
|
|
309
|
+
} else {
|
|
310
|
+
// 主查询失败就照旧返回空表,不拿未跟踪那半截去猜「整体差异」——
|
|
311
|
+
// 半份清单会被上层当成完整清单,比空表更容易让人做错决定。
|
|
312
|
+
return []
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// 未跟踪清单查失败时只交上面那半截:老 git、index.lock 都不该让整份 diff
|
|
316
|
+
// 变空——空 diff 会被上层读成「工作区和快照一致」。
|
|
317
|
+
const untracked = await snapshotCommand(cwd, project, [
|
|
318
|
+
'-c', 'core.quotepath=false', 'ls-files', '--others', '--exclude-standard',
|
|
319
|
+
], { timeoutMs: 300000 })
|
|
320
|
+
if (untracked.ok) {
|
|
321
|
+
for (const line of untracked.stdout.split('\n')) {
|
|
322
|
+
// 这里不 trim:文件名本身可能就以空格开头或结尾,而 git 不会为空格加引号。
|
|
323
|
+
push('新增', unquoteGitPath(line.replace(/\r$/u, '')))
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return entries
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* 这一轮实施到底动了哪些文件。
|
|
331
|
+
*
|
|
332
|
+
* 模型自述的 files 优先(它知道自己的意图);没写才退回快照 diff。
|
|
333
|
+
* 以前这段逻辑只活在 pipeline 里,没法单测,也没法在别处复用。
|
|
334
|
+
*/
|
|
335
|
+
export async function attemptFiles(cwd, project, before, claimed) {
|
|
336
|
+
const paths = normalizePaths(claimed)
|
|
337
|
+
if (paths.length > 0) return paths
|
|
338
|
+
if (before === '') return []
|
|
339
|
+
return (await snapshotDiff(cwd, project, before)).map(entry => entry.path)
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export async function restorePaths(cwd, project, commit, paths) {
|
|
343
|
+
const missing = []
|
|
344
|
+
let restored = 0
|
|
345
|
+
for (const path of paths) {
|
|
346
|
+
const result = await snapshotCommand(cwd, project, ['checkout', commit, '--', path], { timeoutMs: 300000 })
|
|
347
|
+
if (result.ok) restored += 1
|
|
348
|
+
else missing.push(path)
|
|
349
|
+
}
|
|
350
|
+
return { ok: missing.length === 0, restored, missing }
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export async function restoreAll(cwd, project, commit) {
|
|
354
|
+
// The diff has to be taken *before* the reset: afterwards the index equals the
|
|
355
|
+
// target tree, so files created since the snapshot look merely untracked and
|
|
356
|
+
// `git diff <commit>` stops naming them.
|
|
357
|
+
const before = await snapshotDiff(cwd, project, commit)
|
|
358
|
+
const read = await snapshotCommand(cwd, project, ['read-tree', '-u', '--reset', commit], { timeoutMs: 600000 })
|
|
359
|
+
if (!read.ok) {
|
|
360
|
+
return { ok: false, reason: `回滚失败:${read.stderr.trim() || read.message}` }
|
|
361
|
+
}
|
|
362
|
+
// `read-tree -u` removes what the index carried, but a file that was never
|
|
363
|
+
// staged survives; anything the diff called new is deleted explicitly.
|
|
364
|
+
const extra = before.filter(entry => entry.status === '新增').map(entry => entry.path)
|
|
365
|
+
let removed = 0
|
|
366
|
+
const failed = []
|
|
367
|
+
const deleted = []
|
|
368
|
+
for (const path of extra) {
|
|
369
|
+
try {
|
|
370
|
+
await rm(join(cwd, path), { force: true })
|
|
371
|
+
removed += 1
|
|
372
|
+
deleted.push(path)
|
|
373
|
+
} catch {
|
|
374
|
+
// 删不掉的不在这里判失败:剩下的差异由调用方回滚后再跑一次 diff 复查,
|
|
375
|
+
// 那才是「如实报告」的地方,这里谎报成功比失败更糟。
|
|
376
|
+
failed.push(path)
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
// 只清「因为这次删除才变空」的目录:非空目录、.git、.project-flow、cwd
|
|
380
|
+
// 本身都不会被碰(见 pruneEmptyParents 的停止条件)。
|
|
381
|
+
const prunedDirs = await pruneEmptyParents(cwd, deleted)
|
|
382
|
+
return { ok: true, removed, changes: before, failed, prunedDirs }
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* 删掉一批文件之后,把它们因此变空的父目录一路收上去。
|
|
387
|
+
*
|
|
388
|
+
* 新建的文件常常带出自己的目录(src/new/a.ts 回滚后 src/new 只剩空壳),
|
|
389
|
+
* 空目录不算差异、却会被用户当成回滚没干净。停止条件四条,缺一条就可能
|
|
390
|
+
* 把不该删的东西删掉:到 cwd 为止、不越出 cwd、不碰 .git / .project-flow、
|
|
391
|
+
* 目录非空就停。
|
|
392
|
+
*/
|
|
393
|
+
export async function pruneEmptyParents(cwd, paths) {
|
|
394
|
+
const pruned = []
|
|
395
|
+
for (const path of paths) {
|
|
396
|
+
let dir = dirname(join(cwd, path))
|
|
397
|
+
for (let depth = 0; depth < 64; depth += 1) {
|
|
398
|
+
const rel = relative(cwd, dir)
|
|
399
|
+
if (rel === '' || rel.startsWith('..')) break
|
|
400
|
+
const name = basename(dir)
|
|
401
|
+
if (name === '.git' || name === '.project-flow') break
|
|
402
|
+
try {
|
|
403
|
+
if ((await readdir(dir)).length > 0) break
|
|
404
|
+
} catch {
|
|
405
|
+
break
|
|
406
|
+
}
|
|
407
|
+
try {
|
|
408
|
+
await rmdir(dir)
|
|
409
|
+
} catch {
|
|
410
|
+
break
|
|
411
|
+
}
|
|
412
|
+
pruned.push(rel.replace(/\\/gu, '/'))
|
|
413
|
+
dir = dirname(dir)
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
return pruned
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* 只回滚指定的这些路径(precise 模式)。
|
|
421
|
+
*
|
|
422
|
+
* 快照里不存在的(新增)删掉,其余 checkout 回来。和 restoreAll 的区别是
|
|
423
|
+
* 只碰清单里的路径,用户同一时间手改的别的文件不受影响。
|
|
424
|
+
*/
|
|
425
|
+
export async function restorePrecise(cwd, project, commit, paths, changes) {
|
|
426
|
+
const list = Array.isArray(changes) ? changes : await snapshotDiff(cwd, project, commit)
|
|
427
|
+
const wanted = normalizePaths(paths)
|
|
428
|
+
const scoped = list.filter(entry => wanted.includes(entry.path))
|
|
429
|
+
const added = scoped.filter(entry => entry.status === '新增').map(entry => entry.path)
|
|
430
|
+
const existing = wanted.filter(path => !added.includes(path))
|
|
431
|
+
const restored = await restorePaths(cwd, project, commit, existing)
|
|
432
|
+
const failed = [...restored.missing]
|
|
433
|
+
let removed = 0
|
|
434
|
+
for (const path of added) {
|
|
435
|
+
try {
|
|
436
|
+
await rm(join(cwd, path), { force: true })
|
|
437
|
+
removed += 1
|
|
438
|
+
} catch {
|
|
439
|
+
failed.push(path)
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
const prunedDirs = await pruneEmptyParents(cwd, added)
|
|
443
|
+
return {
|
|
444
|
+
ok: failed.length === 0,
|
|
445
|
+
restored: restored.restored,
|
|
446
|
+
removed,
|
|
447
|
+
failed,
|
|
448
|
+
prunedDirs,
|
|
449
|
+
reason: failed.length === 0 ? undefined : `这些文件没能还原:${failed.join('、')}`,
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|