@statewalker/vcs-commands 0.4.0 → 0.5.0

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.
Files changed (99) hide show
  1. package/dist/commands/add-command.d.ts.map +1 -1
  2. package/dist/commands/checkout-command.d.ts +7 -24
  3. package/dist/commands/checkout-command.d.ts.map +1 -1
  4. package/dist/commands/clean-command.d.ts +34 -4
  5. package/dist/commands/clean-command.d.ts.map +1 -1
  6. package/dist/commands/clone-command.d.ts +62 -7
  7. package/dist/commands/clone-command.d.ts.map +1 -1
  8. package/dist/commands/core-config.d.ts +16 -0
  9. package/dist/commands/core-config.d.ts.map +1 -0
  10. package/dist/commands/fetch-command.d.ts +96 -14
  11. package/dist/commands/fetch-command.d.ts.map +1 -1
  12. package/dist/commands/index.d.ts +1 -0
  13. package/dist/commands/index.d.ts.map +1 -1
  14. package/dist/commands/index.js +2 -2
  15. package/dist/commands/init-command.d.ts.map +1 -1
  16. package/dist/commands/remote-command.d.ts +115 -6
  17. package/dist/commands/remote-command.d.ts.map +1 -1
  18. package/dist/commands/reset-command.d.ts.map +1 -1
  19. package/dist/commands/stash-apply-command.d.ts +35 -13
  20. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  21. package/dist/commands/stash-create-command.d.ts +59 -25
  22. package/dist/commands/stash-create-command.d.ts.map +1 -1
  23. package/dist/commands/stash-drop-command.d.ts +8 -2
  24. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  25. package/dist/commands/stash-list-command.d.ts +2 -4
  26. package/dist/commands/stash-list-command.d.ts.map +1 -1
  27. package/dist/commands/stash-working-tree.d.ts +72 -0
  28. package/dist/commands/stash-working-tree.d.ts.map +1 -0
  29. package/dist/commands/status-command.d.ts +29 -22
  30. package/dist/commands/status-command.d.ts.map +1 -1
  31. package/dist/commands/tree-restore.d.ts +52 -5
  32. package/dist/commands/tree-restore.d.ts.map +1 -1
  33. package/dist/commands/worktree-overwrite-checks.d.ts +64 -0
  34. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -0
  35. package/dist/{commands-BpeXZTC3.js → commands-CsLNyvZ1.js} +2940 -631
  36. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  37. package/dist/core-commands/index.d.ts +0 -3
  38. package/dist/core-commands/index.d.ts.map +1 -1
  39. package/dist/errors/checkout-errors.d.ts +13 -0
  40. package/dist/errors/checkout-errors.d.ts.map +1 -1
  41. package/dist/errors/index.js +18 -1
  42. package/dist/git-command.d.ts +10 -1
  43. package/dist/git-command.d.ts.map +1 -1
  44. package/dist/git.d.ts +21 -3
  45. package/dist/git.d.ts.map +1 -1
  46. package/dist/index.js +4 -4
  47. package/dist/remote-config/index.d.ts +1 -0
  48. package/dist/remote-config/index.d.ts.map +1 -1
  49. package/dist/remote-config/remote-config-store.d.ts +18 -0
  50. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  51. package/dist/remote-config/remote-refs.d.ts +37 -0
  52. package/dist/remote-config/remote-refs.d.ts.map +1 -0
  53. package/dist/results/clone-result.d.ts +6 -0
  54. package/dist/results/clone-result.d.ts.map +1 -1
  55. package/dist/results/fetch-result.d.ts +9 -1
  56. package/dist/results/fetch-result.d.ts.map +1 -1
  57. package/dist/results/index.js +2 -2
  58. package/dist/results/status-result.d.ts +91 -20
  59. package/dist/results/status-result.d.ts.map +1 -1
  60. package/dist/{status-result-BapZoQaR.js → status-result-BpyUK1Sg.js} +113 -5
  61. package/dist/transport-command.d.ts +12 -0
  62. package/dist/transport-command.d.ts.map +1 -1
  63. package/package.json +11 -10
  64. package/src/commands/add-command.ts +9 -7
  65. package/src/commands/checkout-command.ts +200 -118
  66. package/src/commands/clean-command.ts +187 -88
  67. package/src/commands/clone-command.ts +244 -40
  68. package/src/commands/core-config.ts +41 -0
  69. package/src/commands/fetch-command.ts +476 -57
  70. package/src/commands/index.ts +1 -0
  71. package/src/commands/init-command.ts +32 -7
  72. package/src/commands/remote-command.ts +429 -19
  73. package/src/commands/reset-command.ts +18 -5
  74. package/src/commands/stash-apply-command.ts +632 -97
  75. package/src/commands/stash-create-command.ts +142 -62
  76. package/src/commands/stash-drop-command.ts +53 -5
  77. package/src/commands/stash-list-command.ts +10 -4
  78. package/src/commands/stash-working-tree.ts +243 -0
  79. package/src/commands/status-command.ts +197 -91
  80. package/src/commands/tree-restore.ts +142 -13
  81. package/src/commands/worktree-overwrite-checks.ts +215 -0
  82. package/src/core-commands/add.command.impl.ts +2 -4
  83. package/src/core-commands/index.ts +0 -8
  84. package/src/errors/checkout-errors.ts +20 -0
  85. package/src/git-command.ts +42 -1
  86. package/src/git.ts +30 -2
  87. package/src/remote-config/index.ts +1 -0
  88. package/src/remote-config/remote-config-store.ts +84 -8
  89. package/src/remote-config/remote-refs.ts +103 -0
  90. package/src/results/clone-result.ts +6 -0
  91. package/src/results/fetch-result.ts +9 -1
  92. package/src/results/status-result.ts +212 -29
  93. package/src/transport-command.ts +18 -0
  94. package/dist/core-commands/checkout.command.d.ts +0 -103
  95. package/dist/core-commands/checkout.command.d.ts.map +0 -1
  96. package/dist/core-commands/checkout.command.impl.d.ts +0 -110
  97. package/dist/core-commands/checkout.command.impl.d.ts.map +0 -1
  98. package/src/core-commands/checkout.command.impl.ts +0 -564
  99. package/src/core-commands/checkout.command.ts +0 -125
@@ -1,8 +1,10 @@
1
- import type { ObjectId, PersonIdent } from "@statewalker/vcs-core";
1
+ import { formatPersonIdent, type ObjectId, type PersonIdent } from "@statewalker/vcs-core";
2
+ import type { Staging } from "@statewalker/vcs-working-tree";
2
3
 
3
- import { NoHeadError, RefNotFoundError } from "../errors/index.js";
4
+ import { NoHeadError, RefNotFoundError, StoreNotAvailableError } from "../errors/index.js";
4
5
  import { GitCommand } from "../git-command.js";
5
6
  import { STASH_REF } from "./stash-list-command.js";
7
+ import { WorkingCopyStashProvider } from "./stash-working-tree.js";
6
8
 
7
9
  /**
8
10
  * Get timezone offset string in Git format (+HHMM or -HHMM).
@@ -33,11 +35,25 @@ const MSG_WORKING_DIR = "WIP on {0}: {1} {2}";
33
35
  */
34
36
  const MSG_UNTRACKED = "untracked files on {0}: {1} {2}";
35
37
 
38
+ /**
39
+ * What the reset after a stash covers, as `git stash push` options.
40
+ */
41
+ export interface StashResetOptions {
42
+ /** `-u`: the untracked files were stashed and are removed (`git clean -fd`) */
43
+ includeUntracked?: boolean;
44
+ /** `-a`: the ignored files too (`git clean -fdx`) */
45
+ includeIgnored?: boolean;
46
+ /** `--keep-index`: the index tree is checked out again after the reset */
47
+ keepIndex?: boolean;
48
+ /** The stashed index tree (for `keepIndex`) */
49
+ indexTree?: ObjectId;
50
+ }
51
+
36
52
  /**
37
53
  * Interface for providing working tree and index state.
38
54
  *
39
- * The stash create operation requires access to the working directory
40
- * and index, which requires a WorkingCopy with worktree access.
55
+ * A working copy with an index and a worktree has a built-in provider
56
+ * ({@link WorkingCopyStashProvider}); set one only to stash something else.
41
57
  */
42
58
  export interface StashWorkingTreeProvider {
43
59
  /**
@@ -51,19 +67,23 @@ export interface StashWorkingTreeProvider {
51
67
  getWorkingTree(): Promise<ObjectId>;
52
68
 
53
69
  /**
54
- * Get tree of untracked files (optional).
70
+ * Get tree of untracked files (optional); the ignored ones too with `includeIgnored`.
55
71
  */
56
- getUntrackedTree?(): Promise<ObjectId | undefined>;
72
+ getUntrackedTree?(options?: { includeIgnored?: boolean }): Promise<ObjectId | undefined>;
57
73
 
58
74
  /**
59
- * Check if there are local changes to stash.
75
+ * Check if there are local changes to stash (untracked files count with
76
+ * `includeUntracked`, as `git stash -u`).
60
77
  */
61
- hasLocalChanges(): Promise<boolean>;
78
+ hasLocalChanges(options?: {
79
+ includeUntracked?: boolean;
80
+ includeIgnored?: boolean;
81
+ }): Promise<boolean>;
62
82
 
63
83
  /**
64
- * Reset working directory to HEAD after stash.
84
+ * Reset the working directory and index to HEAD after the stash, as `git stash push`.
65
85
  */
66
- resetHard(): Promise<void>;
86
+ resetHard(options?: StashResetOptions): Promise<void>;
67
87
  }
68
88
 
69
89
  /**
@@ -73,22 +93,21 @@ export interface StashWorkingTreeProvider {
73
93
  *
74
94
  * Based on JGit's StashCreateCommand.
75
95
  *
76
- * Note: This command requires a working tree provider to access
77
- * uncommitted changes. Without a provider, it creates a stash
78
- * from the current HEAD state (no actual changes stashed).
96
+ * On a working copy with an index and a worktree it stashes as `git stash push` does:
97
+ * the index tree, the worktree tree (tracked files as they are on disk), with `-u` the
98
+ * untracked files, then resets the index and the worktree to HEAD (keeping untracked files
99
+ * unless they were stashed). A working copy without a worktree has nothing to stash:
100
+ * `call()` throws `StoreNotAvailableError` unless a provider is set.
79
101
  *
80
102
  * @example
81
103
  * ```typescript
82
- * // Create a stash with working tree provider
83
- * const stashCommit = await git.stashCreate()
84
- * .setWorkingTreeProvider(provider)
85
- * .setMessage("WIP: feature work")
86
- * .call();
104
+ * // git stash push -m "WIP: feature work"
105
+ * const stashCommit = await git.stashCreate().setMessage("WIP: feature work").call();
87
106
  *
88
- * // Create stash including untracked files
107
+ * // git stash push -u --keep-index
89
108
  * const stashCommit = await git.stashCreate()
90
- * .setWorkingTreeProvider(provider)
91
109
  * .setIncludeUntracked(true)
110
+ * .setKeepIndex(true)
92
111
  * .call();
93
112
  * ```
94
113
  */
@@ -97,6 +116,8 @@ export class StashCreateCommand extends GitCommand<ObjectId | undefined> {
97
116
  private workingDirectoryMessage = MSG_WORKING_DIR;
98
117
  private ref: string | null = STASH_REF;
99
118
  private includeUntracked = false;
119
+ private includeIgnored = false;
120
+ private keepIndex = false;
100
121
  private workingTreeProvider?: StashWorkingTreeProvider;
101
122
  private customMessage?: string;
102
123
  private author?: PersonIdent;
@@ -127,7 +148,7 @@ export class StashCreateCommand extends GitCommand<ObjectId | undefined> {
127
148
  }
128
149
 
129
150
  /**
130
- * Set a custom stash message.
151
+ * Set a custom stash message; the stash is then "On <branch>: <message>", as `git stash push -m`.
131
152
  *
132
153
  * @param message The custom message
133
154
  */
@@ -139,7 +160,8 @@ export class StashCreateCommand extends GitCommand<ObjectId | undefined> {
139
160
 
140
161
  /**
141
162
  * Set the reference to update with the stashed commit ID.
142
- * If null, no reference is updated.
163
+ * If null, no reference is updated and the index and worktree are left as they are
164
+ * (`git stash create`).
143
165
  *
144
166
  * @param ref The ref name (default: refs/stash)
145
167
  */
@@ -167,6 +189,27 @@ export class StashCreateCommand extends GitCommand<ObjectId | undefined> {
167
189
  return this.includeUntracked;
168
190
  }
169
191
 
192
+ /**
193
+ * Set whether to stash (and remove) the ignored files too, as `git stash --all`; implies
194
+ * untracked files.
195
+ */
196
+ setIncludeIgnored(includeIgnored: boolean): this {
197
+ this.checkCallable();
198
+ this.includeIgnored = includeIgnored;
199
+ if (includeIgnored) this.includeUntracked = true;
200
+ return this;
201
+ }
202
+
203
+ /**
204
+ * Set whether the staged changes stay in the index and the worktree after the stash, as
205
+ * `git stash push --keep-index`.
206
+ */
207
+ setKeepIndex(keepIndex: boolean): this {
208
+ this.checkCallable();
209
+ this.keepIndex = keepIndex;
210
+ return this;
211
+ }
212
+
170
213
  /**
171
214
  * Set the working tree provider for accessing uncommitted changes.
172
215
  *
@@ -197,7 +240,12 @@ export class StashCreateCommand extends GitCommand<ObjectId | undefined> {
197
240
  async call(): Promise<ObjectId | undefined> {
198
241
  this.checkCallable();
199
242
  this.setCallable(false);
243
+ // one operation: one reading of the ignore rules for the trees, the clean and the reset
244
+ const worktree = this.worktreeAccess;
245
+ return worktree?.batch ? worktree.batch(() => this.stash()) : this.stash();
246
+ }
200
247
 
248
+ private async stash(): Promise<ObjectId | undefined> {
201
249
  // Get current HEAD
202
250
  const headRef = await this.refsStore.resolve("HEAD");
203
251
  if (!headRef?.objectId) {
@@ -219,38 +267,38 @@ export class StashCreateCommand extends GitCommand<ObjectId | undefined> {
219
267
  };
220
268
 
221
269
  // Determine trees to stash
222
- let indexTree: ObjectId;
223
- let workingTree: ObjectId;
224
- let untrackedTree: ObjectId | undefined;
225
-
226
- if (this.workingTreeProvider) {
227
- // Check if there are changes to stash
228
- const hasChanges = await this.workingTreeProvider.hasLocalChanges();
229
- if (!hasChanges) {
230
- return undefined;
231
- }
232
-
233
- indexTree = await this.workingTreeProvider.getIndexTree();
234
- workingTree = await this.workingTreeProvider.getWorkingTree();
235
-
236
- if (this.includeUntracked && this.workingTreeProvider.getUntrackedTree) {
237
- untrackedTree = await this.workingTreeProvider.getUntrackedTree();
238
- }
239
- } else {
240
- // No working tree provider - use HEAD tree
241
- // This is a degenerate case where there's nothing to actually stash
242
- indexTree = headCommit.tree;
243
- workingTree = headCommit.tree;
270
+ const provider = this.workingTreeProvider ?? this.defaultProvider();
271
+ if (!provider) {
272
+ // without a working tree there is nothing to stash: stashing HEAD's tree instead
273
+ // would report success while the local changes stay unsaved
274
+ throw new StoreNotAvailableError("worktree", "stash requires a working tree");
275
+ }
276
+ const untrackedOptions = {
277
+ includeUntracked: this.includeUntracked,
278
+ includeIgnored: this.includeIgnored,
279
+ };
280
+ // Check if there are changes to stash ("No local changes to save")
281
+ if (!(await provider.hasLocalChanges(untrackedOptions))) {
282
+ return undefined;
244
283
  }
245
284
 
285
+ const indexTree = await provider.getIndexTree();
286
+ const workingTree = await provider.getWorkingTree();
287
+ const untrackedTree =
288
+ this.includeUntracked && provider.getUntrackedTree
289
+ ? await provider.getUntrackedTree({ includeIgnored: this.includeIgnored })
290
+ : undefined;
291
+
246
292
  // Build commit messages
247
293
  const abbrev = headRef.objectId.substring(0, 7);
248
294
  const shortMessage = headCommit.message.split("\n")[0];
249
295
 
250
296
  const indexMsg = this.formatMessage(this.indexMessage, branch, abbrev, shortMessage);
297
+ // git: `stash push -m <msg>` is "On <branch>: <msg>"
251
298
  const workingMsg =
252
- this.customMessage ??
253
- this.formatMessage(this.workingDirectoryMessage, branch, abbrev, shortMessage);
299
+ this.customMessage !== undefined
300
+ ? `On ${branch}: ${this.customMessage}`
301
+ : this.formatMessage(this.workingDirectoryMessage, branch, abbrev, shortMessage);
254
302
 
255
303
  // Create index commit (parent: HEAD)
256
304
  const indexCommit = await this.commits.store({
@@ -289,19 +337,39 @@ export class StashCreateCommand extends GitCommand<ObjectId | undefined> {
289
337
  message: workingMsg,
290
338
  });
291
339
 
292
- // Update stash ref
293
- if (this.ref) {
294
- await this.updateStashRef(this.ref, stashCommit, workingMsg);
295
- }
340
+ // `git stash create` (no ref): the stash commit only, nothing else changes
341
+ if (!this.ref) return stashCommit;
342
+ await this.updateStashRef(this.ref, stashCommit, workingMsg, author);
296
343
 
297
- // Reset working directory (if provider supports it)
298
- if (this.workingTreeProvider) {
299
- await this.workingTreeProvider.resetHard();
300
- }
344
+ // Reset the index and the working directory, as git stash push does
345
+ await provider.resetHard({ ...untrackedOptions, keepIndex: this.keepIndex, indexTree });
301
346
 
302
347
  return stashCommit;
303
348
  }
304
349
 
350
+ /** The built-in provider, for a working copy with an index and a worktree. */
351
+ private defaultProvider(): StashWorkingTreeProvider | undefined {
352
+ const worktree = this.worktreeAccess;
353
+ if (!worktree) return undefined;
354
+ let staging: Staging;
355
+ try {
356
+ staging = this.staging;
357
+ } catch {
358
+ return undefined;
359
+ }
360
+ return new WorkingCopyStashProvider({
361
+ workingCopy: this.workingCopy,
362
+ trees: this.trees,
363
+ blobs: this.blobs,
364
+ staging,
365
+ worktree,
366
+ headTree: async () => {
367
+ const head = await this.refsStore.resolve("HEAD");
368
+ return head?.objectId ? (await this.commits.load(head.objectId))?.tree : undefined;
369
+ },
370
+ });
371
+ }
372
+
305
373
  /**
306
374
  * Format a message template.
307
375
  */
@@ -323,17 +391,29 @@ export class StashCreateCommand extends GitCommand<ObjectId | undefined> {
323
391
  // Strip refs/heads/ prefix
324
392
  return branch.replace(/^refs\/heads\//, "");
325
393
  }
326
- return "HEAD";
394
+ return "(no branch)"; // detached HEAD, as git names it
327
395
  }
328
396
 
329
397
  /**
330
- * Update the stash ref.
331
- *
332
- * Note: Reflog support is not part of the core Refs interface.
333
- * Stash history is tracked via parent commit chain instead.
398
+ * Update the stash ref as `git stash` does (update_ref with REF_FORCE_CREATE_REFLOG):
399
+ * a one-ref batch, under `<ref>.lock` on git files, that creates the ref's reflog and
400
+ * appends a line with the stash commit's message, so the stash is `stash@{0}` and the
401
+ * earlier ones move down the reflog.
334
402
  */
335
- private async updateStashRef(ref: string, commitId: ObjectId, _message: string): Promise<void> {
336
- // Update ref
337
- await this.refsStore.set(ref, commitId);
403
+ private async updateStashRef(
404
+ ref: string,
405
+ commitId: ObjectId,
406
+ message: string,
407
+ who: PersonIdent,
408
+ ): Promise<void> {
409
+ const result = await this.refsStore.batch([{ name: ref, new: commitId }], {
410
+ ident: formatPersonIdent(who),
411
+ message,
412
+ createReflog: true,
413
+ });
414
+ if (!result.ok) {
415
+ const why = result.rejected.map((r) => `${r.name}: ${r.reason}`).join(", ");
416
+ throw new Error(`Cannot save the current status: ${why}`);
417
+ }
338
418
  }
339
419
  }
@@ -11,8 +11,9 @@ import { STASH_REF } from "./stash-list-command.js";
11
11
  *
12
12
  * Based on JGit's StashDropCommand.
13
13
  *
14
- * Note: Without reflog support in Refs, only the most recent stash (index 0)
15
- * can be dropped. Dropping by index > 0 requires reflog support.
14
+ * With a ref store that keeps reflogs (`getReflog`, `deleteReflogEntry`), any
15
+ * `stash@{n}` can be dropped, as git drops it; otherwise only the most recent
16
+ * stash (index 0).
16
17
  *
17
18
  * @example
18
19
  * ```typescript
@@ -92,12 +93,41 @@ export class StashDropCommand extends GitCommand<ObjectId | undefined> {
92
93
  return undefined;
93
94
  }
94
95
 
95
- // Drop all stashes - just delete the ref
96
+ // Drop all stashes: delete the ref and its reflog (`git stash clear`)
96
97
  if (this.dropAll) {
97
- await this.refsStore.delete(STASH_REF);
98
+ await this.deleteStashRef(stashRef.objectId);
98
99
  return undefined;
99
100
  }
100
101
 
102
+ // With reflog support, as `git stash drop stash@{n}`: `git reflog delete --rewrite
103
+ // --updateref refs/stash@{n}` (under the ref's and the log's locks on git files),
104
+ // then the ref goes once no entry is left.
105
+ const refs = this.refsStore;
106
+ const reflog = await refs.getReflog?.(STASH_REF);
107
+ if (reflog && refs.deleteReflogEntry) {
108
+ if (!(await reflog.getReverseEntry(this.stashRefEntry))) {
109
+ throw new InvalidStashIndexError(
110
+ this.stashRefEntry,
111
+ `stash@{${this.stashRefEntry}} does not exist`,
112
+ );
113
+ }
114
+ const left = await refs.deleteReflogEntry(STASH_REF, this.stashRefEntry, {
115
+ rewrite: true,
116
+ updateRef: true,
117
+ });
118
+ // As git: refs/stash goes only once refs/stash@{0} no longer exists, re-checked
119
+ // now, so a stash pushed since the drop is kept (and returned).
120
+ const top = await (await refs.getReflog?.(STASH_REF))?.getReverseEntry(0);
121
+ if (left > 0 || top) return top?.newId;
122
+ const current = await refs.get(STASH_REF);
123
+ if (current && "objectId" in current && current.objectId) {
124
+ // a push between our read and the delete wins: the drop itself has succeeded
125
+ await this.deleteStashRef(current.objectId, { ignoreMismatch: true });
126
+ }
127
+ const after = await (await refs.getReflog?.(STASH_REF))?.getReverseEntry(0);
128
+ return after?.newId;
129
+ }
130
+
101
131
  // Without reflog support, we can only drop the most recent stash (index 0)
102
132
  // For index > 0, we would need reflog support to access older stashes
103
133
  if (this.stashRefEntry > 0) {
@@ -109,7 +139,25 @@ export class StashDropCommand extends GitCommand<ObjectId | undefined> {
109
139
  }
110
140
 
111
141
  // Drop stash@{0} by deleting the ref
112
- await this.refsStore.delete(STASH_REF);
142
+ await this.deleteStashRef(stashRef.objectId);
113
143
  return undefined;
114
144
  }
145
+
146
+ /**
147
+ * Delete `refs/stash` and its reflog if it still holds `expected` (git's clear_stash).
148
+ * With `ignoreMismatch`, a ref another writer moved meanwhile is left alone.
149
+ */
150
+ private async deleteStashRef(
151
+ expected: ObjectId,
152
+ options: { ignoreMismatch?: boolean } = {},
153
+ ): Promise<void> {
154
+ const result = await this.refsStore.batch([
155
+ { name: STASH_REF, old: expected, new: null, noDeref: true },
156
+ ]);
157
+ const moved = result.rejected.every((r) => r.reason === "mismatch");
158
+ if (!result.ok && !(options.ignoreMismatch && moved)) {
159
+ const why = result.rejected.map((r) => `${r.name}: ${r.reason}`).join(", ");
160
+ throw new Error(`Cannot drop the stash: ${why}`);
161
+ }
162
+ }
115
163
  }
@@ -44,6 +44,7 @@ export class StashListCommand extends GitCommand<StashEntry[]> {
44
44
  const stashes: StashEntry[] = [];
45
45
  const reflog = await this.getStashReflog();
46
46
 
47
+ // The index is the reflog position (stash@{n}), even if an entry cannot be parsed.
47
48
  let index = 0;
48
49
  for (const entry of reflog) {
49
50
  const stashEntry = await this.parseStashEntry(entry.commitId, entry.message, index);
@@ -57,12 +58,17 @@ export class StashListCommand extends GitCommand<StashEntry[]> {
57
58
  }
58
59
 
59
60
  /**
60
- * Get stash entries.
61
- *
62
- * Note: Without reflog support in the core Refs interface,
63
- * this returns only the most recent stash (if any).
61
+ * Get stash entries: the reflog of `refs/stash`, newest first, as `git stash list`
62
+ * reads it. A store without reflogs gives only the current `refs/stash`.
64
63
  */
65
64
  private async getStashReflog(): Promise<Array<{ commitId: ObjectId; message: string }>> {
65
+ const reflog = await this.refsStore.getReflog?.(STASH_REF);
66
+ if (reflog) {
67
+ return (await reflog.getReverseEntries()).map((e) => ({
68
+ commitId: e.newId,
69
+ message: e.comment,
70
+ }));
71
+ }
66
72
  // Without reflog support, we can only return the current stash ref
67
73
  const stashRef = await this.refsStore.resolve(STASH_REF);
68
74
  if (stashRef?.objectId) {
@@ -0,0 +1,243 @@
1
+ /**
2
+ * The built-in working-tree side of `git stash push`, for a working copy with an index and
3
+ * a worktree: the stash trees (index, worktree, untracked) as git builds them, and the
4
+ * reset that follows (`git clean -fd` with `-u`, `git reset --hard`, and with
5
+ * `--keep-index` the index tree checked out again).
6
+ *
7
+ * The index is compared with the worktree once per stash ({@link scanIndex}); the check for
8
+ * changes, the worktree tree and the reset all use that one comparison, and the entries it
9
+ * could only prove clean by hashing get their fresh stat in the index the reset writes.
10
+ */
11
+
12
+ import { type Blobs, FileMode, type ObjectId } from "@statewalker/vcs-core";
13
+ import {
14
+ createIndexTree,
15
+ createUntrackedTree,
16
+ createWorktreeTree,
17
+ directoriesOf,
18
+ findUntrackedFiles,
19
+ flattenTree,
20
+ hasTrackedChanges,
21
+ type IndexScan,
22
+ refreshableEntries,
23
+ refreshIndexStats,
24
+ type Staging,
25
+ type StashTreesSource,
26
+ scanIndex,
27
+ trackedUnder,
28
+ type WorkingCopy,
29
+ type Worktree,
30
+ } from "@statewalker/vcs-working-tree";
31
+
32
+ import type { CommandTrees } from "../git-command.js";
33
+ import { coreBool, worktreeModeTrust } from "./core-config.js";
34
+ import type { StashResetOptions, StashWorkingTreeProvider } from "./stash-create-command.js";
35
+ import { planTreeRestore, writeTreeRestorePlan } from "./tree-restore.js";
36
+ import { pruneEmptyParents, removeDirectoryIfEmpty } from "./worktree-overwrite-checks.js";
37
+
38
+ /** Names this operation in restore failure messages. */
39
+ const STASH = "stash";
40
+
41
+ /** What {@link WorkingCopyStashProvider} works on. */
42
+ export interface WorkingCopyStashContext {
43
+ workingCopy: WorkingCopy;
44
+ trees: CommandTrees;
45
+ blobs: Blobs;
46
+ staging: Staging;
47
+ worktree: Worktree;
48
+ /** HEAD's tree (undefined before the first commit) */
49
+ headTree: () => Promise<ObjectId | undefined>;
50
+ }
51
+
52
+ /**
53
+ * The stash working-tree provider `git.stashCreate()` uses when none is set and the working
54
+ * copy has an index and a worktree. One instance serves one stash: it compares the index
55
+ * with the worktree once and reuses that comparison.
56
+ */
57
+ export class WorkingCopyStashProvider implements StashWorkingTreeProvider {
58
+ private scanned?: Promise<IndexScan>;
59
+
60
+ constructor(private readonly context: WorkingCopyStashContext) {}
61
+
62
+ private get source(): StashTreesSource {
63
+ const { trees, blobs, staging, worktree, workingCopy } = this.context;
64
+ return { trees, blobs, staging, worktree, trust: worktreeModeTrust(workingCopy, worktree) };
65
+ }
66
+
67
+ /** The index compared with the worktree, once. */
68
+ private scan(): Promise<IndexScan> {
69
+ this.scanned ??= scanIndex(this.source);
70
+ return this.scanned;
71
+ }
72
+
73
+ getIndexTree(): Promise<ObjectId> {
74
+ return createIndexTree(this.source);
75
+ }
76
+
77
+ async getWorkingTree(): Promise<ObjectId> {
78
+ return createWorktreeTree(this.source, await this.context.headTree(), await this.scan());
79
+ }
80
+
81
+ async getUntrackedTree(options?: { includeIgnored?: boolean }): Promise<ObjectId | undefined> {
82
+ return (await createUntrackedTree(this.source, options)).treeId;
83
+ }
84
+
85
+ async hasLocalChanges(options?: {
86
+ includeUntracked?: boolean;
87
+ includeIgnored?: boolean;
88
+ }): Promise<boolean> {
89
+ const scan = await this.scan();
90
+ if (await hasTrackedChanges(this.source, await this.context.headTree(), scan)) return true;
91
+ if (!options?.includeUntracked) return false;
92
+ for await (const file of findUntrackedFiles(this.context.worktree, (p) => scan.paths.has(p), {
93
+ hasTrackedUnder: trackedUnder(scan.paths),
94
+ includeIgnored: options.includeIgnored,
95
+ })) {
96
+ if (!file.path.endsWith("/")) return true;
97
+ }
98
+ return false;
99
+ }
100
+
101
+ /**
102
+ * As `git stash push` after saving: with `includeUntracked` the untracked files go
103
+ * (`git clean -fd`, `-x` too with `includeIgnored`), then the index and the worktree's
104
+ * tracked files are reset to HEAD (`git reset --hard`); with `keepIndex` the index tree is
105
+ * then checked out again (`git checkout --no-overlay <index tree> -- :/`). Only paths
106
+ * that differ are written; untracked files are kept unless removed by the clean.
107
+ */
108
+ async resetHard(options: StashResetOptions = {}): Promise<void> {
109
+ const scan = await this.scan();
110
+ if (options.includeUntracked) await this.clean(scan, options.includeIgnored === true);
111
+ const headTree = await this.context.headTree();
112
+ await this.resetToHead(scan, headTree);
113
+ if (options.keepIndex && options.indexTree) {
114
+ await this.checkoutTree(headTree, options.indexTree);
115
+ }
116
+ }
117
+
118
+ /**
119
+ * `git clean -fd` (`-x` with `ignored`): the untracked files, then the untracked
120
+ * directories left empty, deepest first. A directory is removed only when nothing at all
121
+ * is in it, so a nested repository (and, without `-x`, an ignored file) keeps its own.
122
+ */
123
+ private async clean(scan: IndexScan, ignored: boolean): Promise<void> {
124
+ const { worktree } = this.context;
125
+ const tracked = scan.paths;
126
+ const trackedDirs = directoriesOf(tracked);
127
+ const untracked: string[] = [];
128
+ const dirs: string[] = [];
129
+ for await (const entry of worktree.walk({
130
+ includeIgnored: ignored,
131
+ includeDirectories: true,
132
+ })) {
133
+ if (entry.isDirectory) {
134
+ if (entry.mode !== FileMode.GITLINK && !trackedDirs.has(entry.path)) dirs.push(entry.path);
135
+ continue;
136
+ }
137
+ if (!tracked.has(entry.path) && (ignored || !entry.isIgnored)) untracked.push(entry.path);
138
+ }
139
+ for (const path of untracked) await worktree.remove(path);
140
+ dirs.sort((a, b) => b.split("/").length - a.split("/").length || (a < b ? 1 : -1));
141
+ for (const dir of dirs) await removeDirectoryIfEmpty(worktree, dir);
142
+ for (const path of untracked) await pruneEmptyParents(worktree, path);
143
+ }
144
+
145
+ /**
146
+ * The index and the worktree's tracked files made to match HEAD, as `git reset --hard`:
147
+ * every path whose index entry or worktree file differs is written (or removed) and staged
148
+ * with its fresh stat; paths that already match are not touched, and those the scan only
149
+ * proved clean by hashing get their fresh stat.
150
+ */
151
+ private async resetToHead(scan: IndexScan, headTree: ObjectId | undefined): Promise<void> {
152
+ const target = await flattenTree(this.context.trees, headTree);
153
+ const stale = new Set<string>(scan.unmerged);
154
+ for (const { entry, compared } of scan.entries) {
155
+ const t = target.get(entry.path);
156
+ if (!t || t.id !== entry.objectId || t.mode !== entry.mode) stale.add(entry.path);
157
+ else if (entry.mode !== FileMode.GITLINK && compared?.kind) stale.add(entry.path);
158
+ }
159
+ for (const path of target.keys()) if (!scan.paths.has(path)) stale.add(path);
160
+ const refresh = refreshableEntries(scan).filter((u) => !stale.has(u.path));
161
+ await this.write(headTree, target, stale);
162
+ await refreshIndexStats(this.context.staging, refresh);
163
+ }
164
+
165
+ /** `git checkout --no-overlay <tree> -- :/` after the reset: index and worktree at `to`. */
166
+ private async checkoutTree(from: ObjectId | undefined, to: ObjectId): Promise<void> {
167
+ const { trees } = this.context;
168
+ const before = await flattenTree(trees, from);
169
+ const target = await flattenTree(trees, to);
170
+ const stale = new Set<string>();
171
+ for (const [path, t] of target) {
172
+ const b = before.get(path);
173
+ if (!b || b.id !== t.id || b.mode !== t.mode) stale.add(path);
174
+ }
175
+ for (const path of before.keys()) if (!target.has(path)) stale.add(path);
176
+ await this.write(to, target, stale);
177
+ }
178
+
179
+ /** Writes (or removes) the `stale` paths of the worktree and the index to `treeId`. */
180
+ private async write(
181
+ treeId: ObjectId | undefined,
182
+ target: Map<string, { id: ObjectId; mode: number }>,
183
+ stale: Set<string>,
184
+ ): Promise<void> {
185
+ if (stale.size === 0) return;
186
+ const { trees, blobs, staging, worktree, workingCopy } = this.context;
187
+ const trust = worktreeModeTrust(workingCopy, worktree);
188
+ const plan = treeId
189
+ ? await planTreeRestore(trees, blobs, treeId, STASH, {
190
+ symlinks: true,
191
+ ignoreCase: coreBool(workingCopy, "ignorecase", false),
192
+ windows: worktree.capabilities?.windowsPaths === true,
193
+ reservedNames: worktree.capabilities?.reservedNames,
194
+ writing: stale,
195
+ })
196
+ : undefined;
197
+ // deletions first, as git's unpack-trees: a removed file `d` makes way for `d/x`
198
+ const editor = staging.createEditor();
199
+ for (const path of [...stale].sort()) {
200
+ if (target.has(path)) continue;
201
+ editor.remove(path);
202
+ const current = await worktree.getEntry(path);
203
+ if (current && !current.isDirectory) {
204
+ await worktree.remove(path);
205
+ await pruneEmptyParents(worktree, path);
206
+ }
207
+ }
208
+ if (plan) {
209
+ const writing = plan.entries.filter((e) => stale.has(e.path));
210
+ await writeTreeRestorePlan(
211
+ worktree,
212
+ blobs,
213
+ { ...plan, entries: writing, gitlinks: [] },
214
+ STASH,
215
+ { symlinks: trust.symlinks, replaceInTheWay: true },
216
+ );
217
+ for (const path of stale) {
218
+ const t = target.get(path);
219
+ if (!t) continue;
220
+ editor.remove(path);
221
+ const current = t.mode === FileMode.GITLINK ? undefined : await worktree.getEntry(path);
222
+ editor.upsert({
223
+ path,
224
+ objectId: t.id,
225
+ mode: t.mode,
226
+ stage: 0,
227
+ size: current?.size ?? 0,
228
+ mtime: current?.mtime ?? 0,
229
+ // the exact stat where the worktree reports it (git's stat data)
230
+ ...(current?.ctime !== undefined ? { ctime: current.ctime } : {}),
231
+ ...(current?.mtimeNs !== undefined ? { mtimeNs: current.mtimeNs } : {}),
232
+ ...(current?.ctimeNs !== undefined ? { ctimeNs: current.ctimeNs } : {}),
233
+ ...(current?.dev !== undefined ? { dev: current.dev } : {}),
234
+ ...(current?.ino !== undefined ? { ino: current.ino } : {}),
235
+ ...(current?.uid !== undefined ? { uid: current.uid } : {}),
236
+ ...(current?.gid !== undefined ? { gid: current.gid } : {}),
237
+ });
238
+ }
239
+ }
240
+ await editor.finish();
241
+ await staging.write();
242
+ }
243
+ }