dsh-timeback 0.7.1 → 0.7.3
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/README.md +19 -6
- package/client.js +878 -47
- package/docs/MARKET.md +2 -2
- package/index.js +30 -0
- package/package.json +1 -1
- package/src/registry.js +59 -0
- package/src/service.js +111 -3
- package/src/snapshots.js +59 -21
package/docs/MARKET.md
CHANGED
|
@@ -78,12 +78,12 @@ dshmarket;要让所有人的 dshmarket 搜到,必须走下一节的公共目
|
|
|
78
78
|
|
|
79
79
|
## 4. npm(已发布 0.6.0)
|
|
80
80
|
|
|
81
|
-
`dsh-timeback@0.7.
|
|
81
|
+
`dsh-timeback@0.7.3` 已发布到官方 npm(<https://www.npmjs.com/package/dsh-timeback>),
|
|
82
82
|
用户可以直接安装/固定版本:
|
|
83
83
|
|
|
84
84
|
```bash
|
|
85
85
|
dsh plugin --profile web add dsh-timeback
|
|
86
|
-
dsh plugin --profile web add dsh-timeback@0.7.
|
|
86
|
+
dsh plugin --profile web add dsh-timeback@0.7.3
|
|
87
87
|
```
|
|
88
88
|
|
|
89
89
|
awesome 目录 CI 会从 npm 自动补充映射,之后市场安装和更新会走 registry。发布流程参考:
|
package/index.js
CHANGED
|
@@ -284,6 +284,8 @@ export function apply(ctx, rawConfig) {
|
|
|
284
284
|
'checkpoint',
|
|
285
285
|
'status',
|
|
286
286
|
'set-workspace',
|
|
287
|
+
'set-workspace-paths',
|
|
288
|
+
'workspace-tree',
|
|
287
289
|
'workspaces',
|
|
288
290
|
'prune',
|
|
289
291
|
'notes-list',
|
|
@@ -368,6 +370,34 @@ export function apply(ctx, rawConfig) {
|
|
|
368
370
|
)
|
|
369
371
|
return
|
|
370
372
|
}
|
|
373
|
+
if (action === 'workspace-tree') {
|
|
374
|
+
writeJson(
|
|
375
|
+
res,
|
|
376
|
+
200,
|
|
377
|
+
await service.listWorkspaceTree({
|
|
378
|
+
sessionId: typeof body.sessionId === 'string' && body.sessionId !== '' ? body.sessionId : undefined,
|
|
379
|
+
cwd: typeof body.cwd === 'string' && body.cwd !== '' ? body.cwd : undefined,
|
|
380
|
+
}),
|
|
381
|
+
req,
|
|
382
|
+
)
|
|
383
|
+
return
|
|
384
|
+
}
|
|
385
|
+
if (action === 'set-workspace-paths') {
|
|
386
|
+
writeJson(
|
|
387
|
+
res,
|
|
388
|
+
200,
|
|
389
|
+
{
|
|
390
|
+
ok: true,
|
|
391
|
+
...(await service.setWorkspacePaths({
|
|
392
|
+
sessionId: typeof body.sessionId === 'string' && body.sessionId !== '' ? body.sessionId : undefined,
|
|
393
|
+
cwd: typeof body.cwd === 'string' && body.cwd !== '' ? body.cwd : undefined,
|
|
394
|
+
excludePaths: Array.isArray(body.excludePaths) ? body.excludePaths : [],
|
|
395
|
+
})),
|
|
396
|
+
},
|
|
397
|
+
req,
|
|
398
|
+
)
|
|
399
|
+
return
|
|
400
|
+
}
|
|
371
401
|
if (action === 'board-canvas') {
|
|
372
402
|
writeJson(res, 200, await service.saveBoardCanvas(body.canvas ?? {}), req)
|
|
373
403
|
return
|
package/package.json
CHANGED
package/src/registry.js
CHANGED
|
@@ -36,6 +36,30 @@ export function workspaceContains(root, cwd) {
|
|
|
36
36
|
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
/** Normalize user-picked excluded paths: repo-relative, POSIX, ancestor-collapsed. */
|
|
40
|
+
export function normalizeExcludePaths(list) {
|
|
41
|
+
if (!Array.isArray(list)) return []
|
|
42
|
+
const seen = new Set()
|
|
43
|
+
const paths = []
|
|
44
|
+
for (const raw of list.slice(0, 1000)) {
|
|
45
|
+
if (typeof raw !== 'string' || raw === '') continue
|
|
46
|
+
const normalized = raw.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '')
|
|
47
|
+
if (!isSafeExclude(normalized)) continue
|
|
48
|
+
if (seen.has(normalized)) continue
|
|
49
|
+
seen.add(normalized)
|
|
50
|
+
paths.push(normalized)
|
|
51
|
+
}
|
|
52
|
+
// A parent exclusion already covers descendants.
|
|
53
|
+
return paths.filter((candidate) => !paths.some((other) => other !== candidate && (candidate === other || candidate.startsWith(`${other}/`)))).sort()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Whether a workspace-relative exclusion path is safe to pass to git. */
|
|
57
|
+
function isSafeExclude(value) {
|
|
58
|
+
if (!value || value.startsWith('/') || value.startsWith(':')) return false
|
|
59
|
+
if (/^[A-Za-z]:[\\/]/.test(value)) return false
|
|
60
|
+
return !value.split('/').some((segment) => segment === '..' || segment === '')
|
|
61
|
+
}
|
|
62
|
+
|
|
39
63
|
/** One registry failure with a stable code for the UI. */
|
|
40
64
|
export class RegistryError extends Error {
|
|
41
65
|
constructor(message, code = 'registry/failed') {
|
|
@@ -241,6 +265,38 @@ export class CheckpointRegistry {
|
|
|
241
265
|
.sort((left, right) => left.path.localeCompare(right.path))
|
|
242
266
|
}
|
|
243
267
|
|
|
268
|
+
/**
|
|
269
|
+
* Recording selection for the enabled workspace root covering `cwd`.
|
|
270
|
+
* @param cwd - absolute directory.
|
|
271
|
+
* @returns {{root: string|null, excludePaths: string[]}}
|
|
272
|
+
*/
|
|
273
|
+
workspaceSelection(cwd) {
|
|
274
|
+
const key = workspaceKey(cwd)
|
|
275
|
+
let root = null
|
|
276
|
+
for (const workspacePath of Object.keys(this.state?.workspaces ?? {})) {
|
|
277
|
+
if (!workspaceContains(workspacePath, key)) continue
|
|
278
|
+
if (root === null || workspacePath.length > root.length) root = workspacePath
|
|
279
|
+
}
|
|
280
|
+
if (root === null) return { root: null, excludePaths: [] }
|
|
281
|
+
return { root, excludePaths: [...(this.state?.workspaces?.[root]?.excludePaths ?? [])] }
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Persist which paths of an enabled workspace are excluded from snapshots.
|
|
286
|
+
* @param cwd - absolute directory.
|
|
287
|
+
* @param excludePaths - workspace-relative paths to exclude (empty = all).
|
|
288
|
+
* @returns {Promise<{path: string, excludePaths: string[]}>}
|
|
289
|
+
*/
|
|
290
|
+
async setWorkspaceExcludePaths(cwd, excludePaths) {
|
|
291
|
+
await this.open()
|
|
292
|
+
const key = workspaceKey(cwd)
|
|
293
|
+
this.state.workspaces ||= {}
|
|
294
|
+
if (!this.state.workspaces[key]) this.state.workspaces[key] = { enabledAt: this.now() }
|
|
295
|
+
this.state.workspaces[key].excludePaths = normalizeExcludePaths(excludePaths)
|
|
296
|
+
await this.flush()
|
|
297
|
+
return { path: key, excludePaths: [...this.state.workspaces[key].excludePaths] }
|
|
298
|
+
}
|
|
299
|
+
|
|
244
300
|
/**
|
|
245
301
|
* The most specific recording policy that covers `cwd`: the longest matching
|
|
246
302
|
* enabled root or explicitly disabled subdirectory.
|
|
@@ -355,6 +411,9 @@ function normalizeState(parsed) {
|
|
|
355
411
|
}
|
|
356
412
|
if (!record || typeof record !== 'object') map[workspacePath] = map === state.workspaces ? { enabledAt: Date.now() } : { disabledAt: Date.now() }
|
|
357
413
|
}
|
|
414
|
+
for (const record of Object.values(state.workspaces)) {
|
|
415
|
+
record.excludePaths = normalizeExcludePaths(record.excludePaths)
|
|
416
|
+
}
|
|
358
417
|
}
|
|
359
418
|
// A path cannot be both enabled and excluded; latest write wins on load.
|
|
360
419
|
for (const workspacePath of Object.keys(state.excluded)) {
|
package/src/service.js
CHANGED
|
@@ -147,6 +147,25 @@ export class TimebackService {
|
|
|
147
147
|
return this.registry.isWorkspaceEnabled(await this.canonicalDir(cwd))
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
+
/**
|
|
151
|
+
* Translate the workspace-root selection onto one capture directory.
|
|
152
|
+
* @param cwd - directory whose tree is snapshotted.
|
|
153
|
+
* @returns {Promise<{root: string|null, excludePaths: string[], excludedAll: boolean}>}
|
|
154
|
+
*/
|
|
155
|
+
async selectionFor(cwd) {
|
|
156
|
+
await this.registry.open()
|
|
157
|
+
const selection = this.registry.workspaceSelection(cwd)
|
|
158
|
+
if (!selection.root || selection.excludePaths.length === 0) return { ...selection, excludedAll: false }
|
|
159
|
+
const relative = path.relative(selection.root, await this.canonicalDir(cwd)).split(path.sep).join('/')
|
|
160
|
+
if (relative === '' || relative === '.') return { ...selection, excludedAll: false }
|
|
161
|
+
const translated = []
|
|
162
|
+
for (const excluded of selection.excludePaths) {
|
|
163
|
+
if (excluded === relative || relative.startsWith(`${excluded}/`)) return { ...selection, excludePaths: [], excludedAll: true }
|
|
164
|
+
if (excluded.startsWith(`${relative}/`)) translated.push(excluded.slice(relative.length + 1))
|
|
165
|
+
}
|
|
166
|
+
return { ...selection, excludePaths: translated, excludedAll: false }
|
|
167
|
+
}
|
|
168
|
+
|
|
150
169
|
/**
|
|
151
170
|
* Describe the workspace of one directory for the panel.
|
|
152
171
|
* @param cwd - absolute directory, or null when the session has none.
|
|
@@ -164,15 +183,87 @@ export class TimebackService {
|
|
|
164
183
|
}
|
|
165
184
|
root = this.registry.workspaceRootFor(await this.canonicalDir(cwd))
|
|
166
185
|
}
|
|
186
|
+
const selection = cwd ? this.registry.workspaceSelection(await this.canonicalDir(cwd)) : { root: null, excludePaths: [] }
|
|
167
187
|
return {
|
|
168
188
|
cwd: cwd ?? null,
|
|
169
189
|
exists,
|
|
170
190
|
root,
|
|
191
|
+
selectionRoot: selection.root,
|
|
171
192
|
mode: this.captureMode,
|
|
172
193
|
enabled: await this.recordingEnabled(cwd),
|
|
194
|
+
excludePaths: [...selection.excludePaths],
|
|
173
195
|
enabledWorkspaces: this.captureMode === 'workspace' ? this.registry.workspaces() : [],
|
|
174
|
-
|
|
196
|
+
// Only show opt-outs that actually override an enabled parent workspace;
|
|
197
|
+
// a plain "recording is off" workspace is the default state, not an
|
|
198
|
+
// interesting subdirectory override.
|
|
199
|
+
excludedWorkspaces:
|
|
200
|
+
this.captureMode === 'workspace'
|
|
201
|
+
? this.registry.excludedWorkspaces().filter((entry) =>
|
|
202
|
+
this.registry.workspaces().some((root) => root.path !== entry.path && workspaceContains(root.path, entry.path)),
|
|
203
|
+
)
|
|
204
|
+
: [],
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* List the files/directories the user can choose for one workspace.
|
|
210
|
+
* @param input - `{ sessionId?, cwd? }`.
|
|
211
|
+
* @returns {Promise<object>} flat tree plus the current selection.
|
|
212
|
+
*/
|
|
213
|
+
async listWorkspaceTree(input) {
|
|
214
|
+
await this.start()
|
|
215
|
+
const cwd = await this.resolveWorkspace(input ?? {})
|
|
216
|
+
const selection = this.registry.workspaceSelection(await this.canonicalDir(cwd))
|
|
217
|
+
const root = selection.root ?? cwd
|
|
218
|
+
const skip = new Set(['.git', 'node_modules', '.venv', 'venv', '__pycache__', '.pytest_cache', '.cache'])
|
|
219
|
+
const entries = []
|
|
220
|
+
const walk = async (dir, prefix, depth) => {
|
|
221
|
+
if (depth > 10 || entries.length >= 2000) return
|
|
222
|
+
let items
|
|
223
|
+
try {
|
|
224
|
+
items = await fs.readdir(dir, { withFileTypes: true })
|
|
225
|
+
} catch {
|
|
226
|
+
return
|
|
227
|
+
}
|
|
228
|
+
items.sort((left, right) => Number(right.isDirectory()) - Number(left.isDirectory()) || left.name.localeCompare(right.name))
|
|
229
|
+
for (const item of items) {
|
|
230
|
+
if (entries.length >= 2000) return
|
|
231
|
+
if (skip.has(item.name)) continue
|
|
232
|
+
const relative = prefix === '' ? item.name : `${prefix}/${item.name}`
|
|
233
|
+
if (item.isDirectory()) {
|
|
234
|
+
entries.push({ path: relative, type: 'dir' })
|
|
235
|
+
await walk(path.join(dir, item.name), relative, depth + 1)
|
|
236
|
+
} else {
|
|
237
|
+
entries.push({ path: relative, type: 'file' })
|
|
238
|
+
}
|
|
239
|
+
}
|
|
175
240
|
}
|
|
241
|
+
await walk(root, '', 0)
|
|
242
|
+
return { ok: true, cwd, root, excludePaths: [...selection.excludePaths], entries }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Persist the files/directories selected for snapshots.
|
|
247
|
+
* @param input - `{ sessionId?, cwd?, excludePaths }`.
|
|
248
|
+
* @returns {Promise<object>} the updated workspace state.
|
|
249
|
+
*/
|
|
250
|
+
async setWorkspacePaths(input) {
|
|
251
|
+
await this.start()
|
|
252
|
+
const resolved = await this.resolveWorkspace(input ?? {})
|
|
253
|
+
if (this.captureMode !== 'workspace') {
|
|
254
|
+
throw new TimebackError(
|
|
255
|
+
this.captureMode === 'off'
|
|
256
|
+
? '插件配置 capture=off 已关闭自动记录;请修改插件配置后再开启'
|
|
257
|
+
: '插件配置 capture=all 已对所有工作区开启记录,无需单独勾选',
|
|
258
|
+
'timeback/capture-mode-fixed',
|
|
259
|
+
)
|
|
260
|
+
}
|
|
261
|
+
await this.registry.open()
|
|
262
|
+
const root = this.registry.workspaceRootFor(await this.canonicalDir(resolved)) ?? resolved
|
|
263
|
+
await this.registry.setWorkspaceEnabled(root, true)
|
|
264
|
+
const saved = await this.registry.setWorkspaceExcludePaths(root, input?.excludePaths)
|
|
265
|
+
const workspace = await this.workspaceStatus(resolved)
|
|
266
|
+
return { workspace, workspaces: workspace.enabledWorkspaces, ...saved }
|
|
176
267
|
}
|
|
177
268
|
|
|
178
269
|
/** Persist the reason a workspace could not be snapshotted for this Session. */
|
|
@@ -315,14 +406,21 @@ export class TimebackService {
|
|
|
315
406
|
if (!cwd) return null
|
|
316
407
|
const checkpointId = `cp-${randomUUID()}`
|
|
317
408
|
await this.registry.ensureSession({ sessionId: record.sessionId, cwd })
|
|
409
|
+
const selection = await this.selectionFor(cwd)
|
|
410
|
+
if (selection.excludedAll) return null
|
|
318
411
|
const snapshot = await this.store.capture({
|
|
319
412
|
cwd,
|
|
320
413
|
sessionId: record.sessionId,
|
|
321
414
|
checkpointId,
|
|
322
415
|
previousTree: record.beforeCheckpoint?.snapshot?.tree ?? record.lastTree,
|
|
416
|
+
excludePaths: selection.excludePaths,
|
|
323
417
|
signal: this.lifetime?.signal,
|
|
324
418
|
})
|
|
325
|
-
const result = {
|
|
419
|
+
const result = {
|
|
420
|
+
checkpointId,
|
|
421
|
+
snapshot: { tree: snapshot.tree, cwd: snapshot.cwd, repoId: snapshot.repoId, excludePaths: selection.excludePaths },
|
|
422
|
+
files: snapshot.files,
|
|
423
|
+
}
|
|
326
424
|
record.afterSnapshot = result
|
|
327
425
|
return result
|
|
328
426
|
})().catch((error) => {
|
|
@@ -341,11 +439,18 @@ export class TimebackService {
|
|
|
341
439
|
const sessionId = String(input.session.id)
|
|
342
440
|
await this.registry.ensureSession({ sessionId, cwd: input.cwd })
|
|
343
441
|
const checkpointId = `cp-${randomUUID()}`
|
|
442
|
+
const selection = Array.isArray(input.excludePaths)
|
|
443
|
+
? { ...(await this.selectionFor(input.cwd)), excludePaths: input.excludePaths, excludedAll: false }
|
|
444
|
+
: await this.selectionFor(input.cwd)
|
|
445
|
+
if (selection.excludedAll) {
|
|
446
|
+
throw new TimebackError('当前工作区没有选中任何要记录的路径', 'timeback/selection-empty')
|
|
447
|
+
}
|
|
344
448
|
const snapshot = await this.store.capture({
|
|
345
449
|
cwd: input.cwd,
|
|
346
450
|
sessionId,
|
|
347
451
|
checkpointId,
|
|
348
452
|
previousTree: input.previousTree,
|
|
453
|
+
excludePaths: selection.excludePaths,
|
|
349
454
|
signal: this.lifetime?.signal,
|
|
350
455
|
})
|
|
351
456
|
const checkpoint = await this.registry.addCheckpoint(sessionId, {
|
|
@@ -355,7 +460,7 @@ export class TimebackService {
|
|
|
355
460
|
seq: input.seq,
|
|
356
461
|
label: input.label,
|
|
357
462
|
prompt: input.prompt,
|
|
358
|
-
snapshot: { tree: snapshot.tree, cwd: snapshot.cwd, repoId: snapshot.repoId },
|
|
463
|
+
snapshot: { tree: snapshot.tree, cwd: snapshot.cwd, repoId: snapshot.repoId, excludePaths: selection.excludePaths },
|
|
359
464
|
files: snapshot.files,
|
|
360
465
|
boardVersion: this.notes?.version ?? null,
|
|
361
466
|
})
|
|
@@ -583,6 +688,7 @@ export class TimebackService {
|
|
|
583
688
|
const workingSession = this.liveSession(sessionId)
|
|
584
689
|
if (!workingSession) throw new TimebackError('源会话未打开,无法获取当前工作区状态;请先打开该会话再回退文件', 'timeback/source-closed')
|
|
585
690
|
const record = this.records.get(sessionId)
|
|
691
|
+
const checkpointSelection = Array.isArray(checkpoint.snapshot?.excludePaths) ? checkpoint.snapshot.excludePaths : []
|
|
586
692
|
try {
|
|
587
693
|
safety = await this.capture({
|
|
588
694
|
session: workingSession,
|
|
@@ -593,6 +699,7 @@ export class TimebackService {
|
|
|
593
699
|
label: null,
|
|
594
700
|
prompt: null,
|
|
595
701
|
previousTree: record?.lastTree ?? null,
|
|
702
|
+
excludePaths: checkpointSelection,
|
|
596
703
|
})
|
|
597
704
|
} catch (error) {
|
|
598
705
|
const wrapped = this.toUserError(error)
|
|
@@ -603,6 +710,7 @@ export class TimebackService {
|
|
|
603
710
|
cwd,
|
|
604
711
|
targetTree: checkpoint.snapshot.tree,
|
|
605
712
|
currentTree: safety?.snapshot?.tree,
|
|
713
|
+
excludePaths: checkpointSelection,
|
|
606
714
|
deleteExtra: this.config.restoreDeletesExtra,
|
|
607
715
|
signal: this.lifetime?.signal,
|
|
608
716
|
})
|
package/src/snapshots.js
CHANGED
|
@@ -45,6 +45,28 @@ function isSafeRelative(relative) {
|
|
|
45
45
|
return !relative.split(/[\\/]/).some((segment) => segment === '..' || segment === '')
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
/** Keep only work-tree-relative paths that are safe as literal git pathspecs. */
|
|
49
|
+
function sanitizeExcludePaths(list) {
|
|
50
|
+
if (!Array.isArray(list)) return []
|
|
51
|
+
const out = []
|
|
52
|
+
const seen = new Set()
|
|
53
|
+
for (const raw of list) {
|
|
54
|
+
if (typeof raw !== 'string') continue
|
|
55
|
+
const value = raw.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '')
|
|
56
|
+
if (!isSafeRelative(value) || value.startsWith(':') || seen.has(value)) continue
|
|
57
|
+
seen.add(value)
|
|
58
|
+
out.push(value)
|
|
59
|
+
}
|
|
60
|
+
return out.filter((candidate) => !out.some((other) => other !== candidate && candidate.startsWith(`${other}/`))).sort()
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Literal pathspecs restricting a git operation to the selected paths. */
|
|
64
|
+
function selectionPathspecs(excludePaths) {
|
|
65
|
+
const excludes = sanitizeExcludePaths(excludePaths)
|
|
66
|
+
if (excludes.length === 0) return null
|
|
67
|
+
return ['.', ...excludes.map((value) => `:(exclude,literal)${value}`)]
|
|
68
|
+
}
|
|
69
|
+
|
|
48
70
|
/** Hard cap a list of paths. */
|
|
49
71
|
function capPaths(paths) {
|
|
50
72
|
return paths.length <= PATH_LIST_LIMIT ? paths : paths.slice(0, PATH_LIST_LIMIT)
|
|
@@ -189,13 +211,16 @@ export class SnapshotStore {
|
|
|
189
211
|
* consume time and disk.
|
|
190
212
|
* @returns {Promise<{ok: boolean, files?: number, reason?: string}>}
|
|
191
213
|
*/
|
|
192
|
-
async probeWorkspace(repo, signal) {
|
|
193
|
-
const
|
|
214
|
+
async probeWorkspace(repo, signal, excludePaths = []) {
|
|
215
|
+
const excludes = sanitizeExcludePaths(excludePaths)
|
|
216
|
+
const cacheKey = `${repo.id}:${excludes.join('|')}`
|
|
217
|
+
const cached = this.probes.get(cacheKey)
|
|
194
218
|
if (cached) return cached
|
|
195
219
|
const env = { GIT_INDEX_FILE: path.join(repo.gitDir, 'probe.index') }
|
|
196
220
|
let verdict
|
|
197
221
|
try {
|
|
198
|
-
const
|
|
222
|
+
const pathspecs = selectionPathspecs(excludes)
|
|
223
|
+
const dryRun = await this.git(repo, ['--work-tree', repo.cwd, 'add', '-A', '--ignore-errors', '--dry-run', '--', ...(pathspecs ?? ['.'])], {
|
|
199
224
|
env,
|
|
200
225
|
signal,
|
|
201
226
|
timeoutMs: this.probeTimeoutMs,
|
|
@@ -214,8 +239,8 @@ export class SnapshotStore {
|
|
|
214
239
|
} finally {
|
|
215
240
|
await fs.rm(path.join(repo.gitDir, 'probe.index'), { force: true }).catch(() => {})
|
|
216
241
|
}
|
|
217
|
-
this.probes.set(
|
|
218
|
-
if (!verdict.ok) {
|
|
242
|
+
this.probes.set(cacheKey, verdict)
|
|
243
|
+
if (!verdict.ok && excludes.length === 0) {
|
|
219
244
|
this.blocked.set(repo.cwd, verdict)
|
|
220
245
|
this.logger?.warn?.(
|
|
221
246
|
`timeback: refusing to snapshot ${repo.cwd}: ${verdict.reason}` +
|
|
@@ -248,20 +273,31 @@ export class SnapshotStore {
|
|
|
248
273
|
* @param signal - cancellation.
|
|
249
274
|
* @returns {Promise<string>} tree object id.
|
|
250
275
|
*/
|
|
251
|
-
async treeOfHead(repo, signal) {
|
|
276
|
+
async treeOfHead(repo, signal, excludePaths = []) {
|
|
252
277
|
await this.clearStaleLock(repo.gitDir)
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
//
|
|
256
|
-
|
|
257
|
-
if (
|
|
258
|
-
|
|
278
|
+
const pathspecs = selectionPathspecs(excludePaths)
|
|
279
|
+
// A selection needs a fresh index, otherwise files outside the selection
|
|
280
|
+
// would survive from the previous full capture.
|
|
281
|
+
const indexPath = pathspecs ? path.join(repo.gitDir, 'index.filtered') : path.join(repo.gitDir, 'index')
|
|
282
|
+
if (pathspecs) await fs.rm(indexPath, { force: true })
|
|
283
|
+
const env = { GIT_INDEX_FILE: indexPath }
|
|
284
|
+
try {
|
|
285
|
+
const args = ['--work-tree', repo.cwd, 'add', '-A', '--ignore-errors']
|
|
286
|
+
if (pathspecs) args.push('--', ...pathspecs)
|
|
287
|
+
const add = await this.git(repo, args, { env, signal })
|
|
288
|
+
// Exit code 1 means individual unreadable entries were skipped; the tree
|
|
289
|
+
// built from everything else is still usable.
|
|
290
|
+
if (add.exitCode !== 0 && add.exitCode !== 1) {
|
|
291
|
+
throw new SnapshotError(`快照失败(git add):${add.stderr.trim()}`, 'snapshot/add-failed')
|
|
292
|
+
}
|
|
293
|
+
const write = await this.git(repo, ['write-tree'], { env, signal })
|
|
294
|
+
if (write.exitCode !== 0) throw new SnapshotError(`快照失败(write-tree):${write.stderr.trim()}`, 'snapshot/tree-failed')
|
|
295
|
+
const tree = write.stdout.trim()
|
|
296
|
+
if (!/^[0-9a-f]{40,64}$/.test(tree)) throw new SnapshotError('快照失败:git 返回了无效的 tree id', 'snapshot/tree-invalid')
|
|
297
|
+
return tree
|
|
298
|
+
} finally {
|
|
299
|
+
if (pathspecs) await fs.rm(indexPath, { force: true }).catch(() => {})
|
|
259
300
|
}
|
|
260
|
-
const write = await this.git(repo, ['write-tree'], { env, signal })
|
|
261
|
-
if (write.exitCode !== 0) throw new SnapshotError(`快照失败(write-tree):${write.stderr.trim()}`, 'snapshot/tree-failed')
|
|
262
|
-
const tree = write.stdout.trim()
|
|
263
|
-
if (!/^[0-9a-f]{40,64}$/.test(tree)) throw new SnapshotError('快照失败:git 返回了无效的 tree id', 'snapshot/tree-invalid')
|
|
264
|
-
return tree
|
|
265
301
|
}
|
|
266
302
|
|
|
267
303
|
/**
|
|
@@ -273,7 +309,8 @@ export class SnapshotStore {
|
|
|
273
309
|
return this.exclusive(async () => {
|
|
274
310
|
await this.available()
|
|
275
311
|
const repo = await this.ensureRepo(options.cwd, options.signal)
|
|
276
|
-
const
|
|
312
|
+
const excludePaths = sanitizeExcludePaths(options.excludePaths)
|
|
313
|
+
const blocked = excludePaths.length === 0 ? this.blocked.get(repo.cwd) : undefined
|
|
277
314
|
if (blocked) {
|
|
278
315
|
throw new SnapshotError(
|
|
279
316
|
`工作区过大,未创建文件快照(${blocked.reason})。可在插件配置里提高 maxFiles 或添加 exclude 规则。`,
|
|
@@ -281,7 +318,7 @@ export class SnapshotStore {
|
|
|
281
318
|
{ files: blocked.files ?? null, maxFiles: this.maxFiles },
|
|
282
319
|
)
|
|
283
320
|
}
|
|
284
|
-
const probe = await this.probeWorkspace(repo, options.signal)
|
|
321
|
+
const probe = await this.probeWorkspace(repo, options.signal, excludePaths)
|
|
285
322
|
if (!probe.ok) {
|
|
286
323
|
throw new SnapshotError(
|
|
287
324
|
`工作区过大,未创建文件快照(${probe.reason})。可在插件配置里提高 maxFiles 或添加 exclude 规则。`,
|
|
@@ -289,7 +326,7 @@ export class SnapshotStore {
|
|
|
289
326
|
{ files: probe.files ?? null, maxFiles: this.maxFiles },
|
|
290
327
|
)
|
|
291
328
|
}
|
|
292
|
-
const tree = await this.treeOfHead(repo, options.signal)
|
|
329
|
+
const tree = await this.treeOfHead(repo, options.signal, excludePaths)
|
|
293
330
|
const ref = `refs/timeback/${refComponent(options.sessionId)}/${refComponent(options.checkpointId)}`
|
|
294
331
|
const updated = await this.git(repo, ['update-ref', ref, tree], { signal: options.signal })
|
|
295
332
|
if (updated.exitCode !== 0) {
|
|
@@ -383,7 +420,8 @@ export class SnapshotStore {
|
|
|
383
420
|
if (type.exitCode !== 0 || type.stdout.trim() !== 'tree') {
|
|
384
421
|
throw new SnapshotError('目标文件快照不存在或已损坏', 'snapshot/target-missing')
|
|
385
422
|
}
|
|
386
|
-
const
|
|
423
|
+
const excludePaths = sanitizeExcludePaths(options.excludePaths)
|
|
424
|
+
const currentTree = options.currentTree ?? (await this.treeOfHead(repo, options.signal, excludePaths))
|
|
387
425
|
if (currentTree === options.targetTree) {
|
|
388
426
|
return { noop: true, restored: 0, deleted: 0, skipped: 0, gitlinks: 0, failed: [], restoredPaths: [], deletedPaths: [] }
|
|
389
427
|
}
|