@statewalker/vcs-commands 0.1.1 → 0.3.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.
Files changed (85) hide show
  1. package/dist/commands/commit-command.d.ts.map +1 -1
  2. package/dist/commands/init-command.d.ts.map +1 -1
  3. package/dist/commands/push-command.d.ts.map +1 -1
  4. package/dist/core-commands/checkout.command.impl.d.ts +1 -1
  5. package/dist/core-commands/checkout.command.impl.d.ts.map +1 -1
  6. package/dist/git-command.d.ts.map +1 -1
  7. package/package.json +19 -14
  8. package/src/commands/add-command.ts +494 -0
  9. package/src/commands/blame-command.ts +1241 -0
  10. package/src/commands/branch-command.ts +487 -0
  11. package/src/commands/checkout-command.ts +681 -0
  12. package/src/commands/cherry-pick-command.ts +544 -0
  13. package/src/commands/clean-command.ts +218 -0
  14. package/src/commands/clone-command.ts +532 -0
  15. package/src/commands/commit-command.ts +529 -0
  16. package/src/commands/describe-command.ts +454 -0
  17. package/src/commands/diff-command.ts +257 -0
  18. package/src/commands/fetch-command.ts +615 -0
  19. package/src/commands/gc-command.ts +155 -0
  20. package/src/commands/index.ts +31 -0
  21. package/src/commands/init-command.ts +365 -0
  22. package/src/commands/log-command.ts +549 -0
  23. package/src/commands/ls-remote-command.ts +237 -0
  24. package/src/commands/merge-command.ts +750 -0
  25. package/src/commands/pack-refs-command.ts +101 -0
  26. package/src/commands/pull-command.ts +258 -0
  27. package/src/commands/push-command.ts +682 -0
  28. package/src/commands/rebase-command.ts +665 -0
  29. package/src/commands/reflog-command.ts +68 -0
  30. package/src/commands/remote-command.ts +385 -0
  31. package/src/commands/reset-command.ts +292 -0
  32. package/src/commands/revert-command.ts +552 -0
  33. package/src/commands/rm-command.ts +178 -0
  34. package/src/commands/stash-apply-command.ts +402 -0
  35. package/src/commands/stash-create-command.ts +339 -0
  36. package/src/commands/stash-drop-command.ts +115 -0
  37. package/src/commands/stash-list-command.ts +116 -0
  38. package/src/commands/status-command.ts +173 -0
  39. package/src/commands/tag-command.ts +378 -0
  40. package/src/commands/tree-restore.ts +126 -0
  41. package/src/core-commands/add.command.impl.ts +274 -0
  42. package/src/core-commands/add.command.ts +81 -0
  43. package/src/core-commands/checkout.command.impl.ts +586 -0
  44. package/src/core-commands/checkout.command.ts +125 -0
  45. package/src/core-commands/index.ts +13 -0
  46. package/src/errors/add-errors.ts +20 -0
  47. package/src/errors/checkout-errors.ts +42 -0
  48. package/src/errors/command-errors.ts +68 -0
  49. package/src/errors/commit-errors.ts +40 -0
  50. package/src/errors/git-api-error.ts +11 -0
  51. package/src/errors/index.ts +12 -0
  52. package/src/errors/merge-errors.ts +94 -0
  53. package/src/errors/rebase-errors.ts +34 -0
  54. package/src/errors/ref-errors.ts +100 -0
  55. package/src/errors/remote-errors.ts +27 -0
  56. package/src/errors/stash-errors.ts +42 -0
  57. package/src/errors/tag-errors.ts +16 -0
  58. package/src/errors/transport-errors.ts +68 -0
  59. package/src/git-command.ts +421 -0
  60. package/src/git.ts +910 -0
  61. package/src/index.ts +18 -0
  62. package/src/pack-import/index.ts +8 -0
  63. package/src/pack-import/pack-import.ts +24 -0
  64. package/src/remote-config/index.ts +12 -0
  65. package/src/remote-config/remote-config-store.ts +285 -0
  66. package/src/rename/index.ts +5 -0
  67. package/src/rename/similarity-index.ts +185 -0
  68. package/src/results/cherry-pick-result.ts +35 -0
  69. package/src/results/clone-result.ts +25 -0
  70. package/src/results/diff-entry.ts +162 -0
  71. package/src/results/diff-formatter.ts +416 -0
  72. package/src/results/fetch-result.ts +91 -0
  73. package/src/results/index.ts +13 -0
  74. package/src/results/init-result.ts +29 -0
  75. package/src/results/merge-result.ts +135 -0
  76. package/src/results/pull-result.ts +27 -0
  77. package/src/results/push-result.ts +86 -0
  78. package/src/results/rebase-result.ts +140 -0
  79. package/src/results/revert-result.ts +35 -0
  80. package/src/results/stash-result.ts +60 -0
  81. package/src/results/status-result.ts +65 -0
  82. package/src/transport-command.ts +125 -0
  83. package/src/tree-merge/index.ts +8 -0
  84. package/src/tree-merge/tree-merge.ts +249 -0
  85. package/src/types.ts +70 -0
@@ -0,0 +1,173 @@
1
+ import type { ObjectId } from "@statewalker/vcs-core";
2
+ import { FileMode } from "@statewalker/vcs-core";
3
+ import { MergeStage } from "@statewalker/vcs-working-tree";
4
+
5
+ import { GitCommand } from "../git-command.js";
6
+ import { type Status, StatusImpl } from "../results/status-result.js";
7
+
8
+ /**
9
+ * Entry with full path for internal use.
10
+ */
11
+ interface PathEntry {
12
+ path: string;
13
+ mode: number;
14
+ id: ObjectId;
15
+ }
16
+
17
+ /**
18
+ * Shows the staging area status compared to HEAD.
19
+ *
20
+ * This is a simplified version for repositories without working trees,
21
+ * focusing on staged changes and conflicts.
22
+ *
23
+ * Equivalent to `git status` but only for staged changes.
24
+ *
25
+ * Based on JGit's StatusCommand (staged-only subset).
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * // Get repository status
30
+ * const status = await git.status().call();
31
+ *
32
+ * // Check if clean
33
+ * if (status.isClean()) {
34
+ * console.log("Nothing to commit");
35
+ * }
36
+ *
37
+ * // Check for changes
38
+ * console.log("Added:", status.added);
39
+ * console.log("Changed:", status.changed);
40
+ * console.log("Removed:", status.removed);
41
+ * console.log("Conflicting:", status.conflicting);
42
+ *
43
+ * // Filter by path
44
+ * const subStatus = await git.status()
45
+ * .addPath("src/")
46
+ * .call();
47
+ * ```
48
+ */
49
+ export class StatusCommand extends GitCommand<Status> {
50
+ private paths: string[] = [];
51
+
52
+ /**
53
+ * Add a path filter.
54
+ *
55
+ * Only status for paths starting with this prefix will be returned.
56
+ *
57
+ * @param path Path prefix to filter by
58
+ */
59
+ addPath(path: string): this {
60
+ this.checkCallable();
61
+ this.paths.push(path);
62
+ return this;
63
+ }
64
+
65
+ async call(): Promise<Status> {
66
+ this.checkCallable();
67
+ this.setCallable(false);
68
+
69
+ // Get conflicting paths first
70
+ const conflicting = new Set<string>();
71
+ for (const path of await this.staging.getConflictedPaths()) {
72
+ if (this.matchesPath(path)) {
73
+ conflicting.add(path);
74
+ }
75
+ }
76
+
77
+ // Get HEAD tree entries
78
+ const headEntries = new Map<string, PathEntry>();
79
+ const headRef = await this.refsStore.resolve("HEAD");
80
+ if (headRef?.objectId) {
81
+ try {
82
+ const headCommit = await this.commits.load(headRef.objectId);
83
+ if (headCommit) {
84
+ await this.collectTreeEntries(headCommit.tree, "", headEntries);
85
+ }
86
+ } catch {
87
+ // No HEAD commit yet - headEntries stays empty
88
+ }
89
+ }
90
+
91
+ // Get staging entries (only stage 0 = merged)
92
+ const stagingEntries = new Map<string, PathEntry>();
93
+ for await (const entry of this.staging.entries()) {
94
+ if (entry.stage === MergeStage.MERGED) {
95
+ stagingEntries.set(entry.path, {
96
+ path: entry.path,
97
+ mode: entry.mode,
98
+ id: entry.objectId,
99
+ });
100
+ }
101
+ }
102
+
103
+ // Compare HEAD vs staging
104
+ const added = new Set<string>();
105
+ const changed = new Set<string>();
106
+ const removed = new Set<string>();
107
+
108
+ // Files in staging but not in HEAD = added
109
+ // Files in staging and HEAD with different IDs = changed
110
+ for (const [path, stagingEntry] of stagingEntries) {
111
+ if (!this.matchesPath(path)) continue;
112
+
113
+ const headEntry = headEntries.get(path);
114
+ if (!headEntry) {
115
+ added.add(path);
116
+ } else if (headEntry.id !== stagingEntry.id || headEntry.mode !== stagingEntry.mode) {
117
+ changed.add(path);
118
+ }
119
+ }
120
+
121
+ // Files in HEAD but not in staging = removed
122
+ for (const [path] of headEntries) {
123
+ if (!this.matchesPath(path)) continue;
124
+
125
+ if (!stagingEntries.has(path)) {
126
+ removed.add(path);
127
+ }
128
+ }
129
+
130
+ return new StatusImpl(added, changed, removed, conflicting);
131
+ }
132
+
133
+ /**
134
+ * Check if a path matches the configured path filters.
135
+ */
136
+ private matchesPath(path: string): boolean {
137
+ if (this.paths.length === 0) {
138
+ return true;
139
+ }
140
+
141
+ for (const filterPath of this.paths) {
142
+ if (
143
+ path === filterPath ||
144
+ path.startsWith(`${filterPath}/`) ||
145
+ filterPath.startsWith(`${path}/`)
146
+ ) {
147
+ return true;
148
+ }
149
+ }
150
+ return false;
151
+ }
152
+
153
+ /**
154
+ * Collect all blob entries from a tree recursively.
155
+ */
156
+ private async collectTreeEntries(
157
+ treeId: ObjectId,
158
+ prefix: string,
159
+ entries: Map<string, PathEntry>,
160
+ ): Promise<void> {
161
+ for await (const entry of this.trees.loadTree(treeId)) {
162
+ const path = prefix ? `${prefix}/${entry.name}` : entry.name;
163
+
164
+ if (entry.mode === FileMode.TREE) {
165
+ // Recurse into subtree
166
+ await this.collectTreeEntries(entry.id, path, entries);
167
+ } else {
168
+ // Blob entry
169
+ entries.set(path, { path, mode: entry.mode, id: entry.id });
170
+ }
171
+ }
172
+ }
173
+ }
@@ -0,0 +1,378 @@
1
+ import type { AnnotatedTag, ObjectId, PersonIdent, Ref } from "@statewalker/vcs-core";
2
+ import { ObjectType } from "@statewalker/vcs-core";
3
+
4
+ import {
5
+ InvalidTagNameError,
6
+ RefAlreadyExistsError,
7
+ RefNotFoundError,
8
+ StoreNotAvailableError,
9
+ } from "../errors/index.js";
10
+ import { GitCommand } from "../git-command.js";
11
+
12
+ /**
13
+ * Get current timezone offset as string (+HHMM or -HHMM).
14
+ */
15
+ function getTimezoneOffset(): string {
16
+ const offset = new Date().getTimezoneOffset();
17
+ const sign = offset <= 0 ? "+" : "-";
18
+ const absOffset = Math.abs(offset);
19
+ const hours = Math.floor(absOffset / 60)
20
+ .toString()
21
+ .padStart(2, "0");
22
+ const minutes = (absOffset % 60).toString().padStart(2, "0");
23
+ return `${sign}${hours}${minutes}`;
24
+ }
25
+
26
+ /**
27
+ * Validate a tag name according to Git rules.
28
+ *
29
+ * @param name Tag name to validate
30
+ * @returns true if valid
31
+ */
32
+ function isValidTagName(name: string): boolean {
33
+ // Cannot be empty
34
+ if (!name || name.length === 0) {
35
+ return false;
36
+ }
37
+
38
+ // Cannot start or end with /
39
+ if (name.startsWith("/") || name.endsWith("/")) {
40
+ return false;
41
+ }
42
+
43
+ // Cannot contain ..
44
+ if (name.includes("..")) {
45
+ return false;
46
+ }
47
+
48
+ // Cannot contain special characters (control chars, space, ~^:?*[\)
49
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Git ref validation requires checking for control characters
50
+ if (/[\x00-\x1f\x7f ~^:?*[\\]/.test(name)) {
51
+ return false;
52
+ }
53
+
54
+ // Cannot end with .lock
55
+ if (name.endsWith(".lock")) {
56
+ return false;
57
+ }
58
+
59
+ // Cannot start with -
60
+ if (name.startsWith("-")) {
61
+ return false;
62
+ }
63
+
64
+ // Cannot be @
65
+ if (name === "@") {
66
+ return false;
67
+ }
68
+
69
+ // Cannot contain @{
70
+ if (name.includes("@{")) {
71
+ return false;
72
+ }
73
+
74
+ return true;
75
+ }
76
+
77
+ /**
78
+ * Create a tag (lightweight or annotated).
79
+ *
80
+ * Equivalent to `git tag`.
81
+ *
82
+ * Based on JGit's TagCommand.
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * // Create lightweight tag at HEAD
87
+ * await git.tag().setName("v1.0.0").call();
88
+ *
89
+ * // Create lightweight tag at specific commit
90
+ * await git.tag()
91
+ * .setName("v1.0.0")
92
+ * .setObjectId(commitId)
93
+ * .call();
94
+ *
95
+ * // Create annotated tag
96
+ * await git.tag()
97
+ * .setName("v1.0.0")
98
+ * .setMessage("Release version 1.0.0")
99
+ * .setAnnotated(true)
100
+ * .call();
101
+ *
102
+ * // Force overwrite existing tag
103
+ * await git.tag()
104
+ * .setName("v1.0.0")
105
+ * .setForce(true)
106
+ * .call();
107
+ * ```
108
+ */
109
+ export class TagCommand extends GitCommand<Ref> {
110
+ private name?: string;
111
+ private message?: string;
112
+ private objectId?: ObjectId;
113
+ private tagger?: PersonIdent;
114
+ private annotated = false;
115
+ private force = false;
116
+ private signed = false;
117
+
118
+ /**
119
+ * Set the tag name.
120
+ *
121
+ * @param name Tag name (without refs/tags/ prefix)
122
+ */
123
+ setName(name: string): this {
124
+ this.checkCallable();
125
+ this.name = name;
126
+ return this;
127
+ }
128
+
129
+ /**
130
+ * Set the tag message.
131
+ *
132
+ * Setting a message implies an annotated tag.
133
+ *
134
+ * @param message Tag message
135
+ */
136
+ setMessage(message: string): this {
137
+ this.checkCallable();
138
+ this.message = message;
139
+ return this;
140
+ }
141
+
142
+ /**
143
+ * Set the object to tag.
144
+ *
145
+ * If not set, tags HEAD.
146
+ *
147
+ * @param objectId Object to tag
148
+ */
149
+ setObjectId(objectId: ObjectId): this {
150
+ this.checkCallable();
151
+ this.objectId = objectId;
152
+ return this;
153
+ }
154
+
155
+ /**
156
+ * Set whether this is an annotated tag.
157
+ *
158
+ * Annotated tags are stored as objects and can have messages.
159
+ *
160
+ * @param annotated Whether to create annotated tag
161
+ */
162
+ setAnnotated(annotated: boolean): this {
163
+ this.checkCallable();
164
+ this.annotated = annotated;
165
+ return this;
166
+ }
167
+
168
+ /**
169
+ * Set the tagger identity.
170
+ *
171
+ * @param name Tagger name
172
+ * @param email Tagger email
173
+ */
174
+ setTagger(name: string, email: string): this {
175
+ this.checkCallable();
176
+ this.tagger = {
177
+ name,
178
+ email,
179
+ timestamp: Math.floor(Date.now() / 1000),
180
+ tzOffset: getTimezoneOffset(),
181
+ };
182
+ return this;
183
+ }
184
+
185
+ /**
186
+ * Set the tagger identity from a PersonIdent.
187
+ *
188
+ * @param tagger Tagger identity
189
+ */
190
+ setTaggerIdent(tagger: PersonIdent): this {
191
+ this.checkCallable();
192
+ this.tagger = tagger;
193
+ return this;
194
+ }
195
+
196
+ /**
197
+ * Set whether to force overwrite existing tag.
198
+ *
199
+ * @param force Whether to force
200
+ */
201
+ setForce(force: boolean): this {
202
+ this.checkCallable();
203
+ this.force = force;
204
+ return this;
205
+ }
206
+
207
+ /**
208
+ * Set whether to create a signed tag.
209
+ *
210
+ * Note: Signing is not implemented yet.
211
+ *
212
+ * @param signed Whether to sign
213
+ */
214
+ setSigned(signed: boolean): this {
215
+ this.checkCallable();
216
+ this.signed = signed;
217
+ return this;
218
+ }
219
+
220
+ /**
221
+ * Execute the tag creation.
222
+ *
223
+ * @returns The created tag ref
224
+ * @throws InvalidTagNameError if tag name is invalid
225
+ * @throws RefAlreadyExistsError if tag exists and force is false
226
+ */
227
+ async call(): Promise<Ref> {
228
+ this.checkCallable();
229
+
230
+ if (!this.name) {
231
+ throw new InvalidTagNameError("", "Tag name is required");
232
+ }
233
+
234
+ if (!isValidTagName(this.name)) {
235
+ throw new InvalidTagNameError(this.name);
236
+ }
237
+
238
+ const refName = `refs/tags/${this.name}`;
239
+
240
+ // Check if already exists
241
+ if (!this.force && (await this.refsStore.has(refName))) {
242
+ throw new RefAlreadyExistsError(refName, `Tag '${this.name}' already exists`);
243
+ }
244
+
245
+ // Resolve target object
246
+ const targetId = this.objectId ?? (await this.resolveHead());
247
+
248
+ // Determine if we should create annotated tag
249
+ const createAnnotated = this.annotated || this.message || this.signed;
250
+
251
+ let tagObjectId: ObjectId;
252
+
253
+ if (createAnnotated) {
254
+ // Create annotated tag object
255
+ if (!this.tagsStore) {
256
+ throw new StoreNotAvailableError(
257
+ "TagStore",
258
+ "Tag store is not available for annotated tags",
259
+ );
260
+ }
261
+
262
+ const tagger = this.tagger ?? {
263
+ name: "Unknown",
264
+ email: "unknown@example.com",
265
+ timestamp: Math.floor(Date.now() / 1000),
266
+ tzOffset: getTimezoneOffset(),
267
+ };
268
+
269
+ const tag: AnnotatedTag = {
270
+ object: targetId,
271
+ objectType: ObjectType.COMMIT,
272
+ tag: this.name,
273
+ tagger,
274
+ message: this.message ?? "",
275
+ };
276
+
277
+ tagObjectId = await this.tagsStore.storeTag(tag);
278
+ } else {
279
+ // Lightweight tag - just point to the object
280
+ tagObjectId = targetId;
281
+ }
282
+
283
+ await this.refsStore.set(refName, tagObjectId);
284
+
285
+ this.setCallable(false);
286
+
287
+ const ref = await this.refsStore.get(refName);
288
+ return ref as Ref;
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Delete tags.
294
+ *
295
+ * Equivalent to `git tag -d`.
296
+ *
297
+ * @example
298
+ * ```typescript
299
+ * // Delete a tag
300
+ * const deleted = await git.tagDelete().setTags("v1.0.0").call();
301
+ * ```
302
+ */
303
+ export class DeleteTagCommand extends GitCommand<string[]> {
304
+ private tags: string[] = [];
305
+
306
+ /**
307
+ * Set the tags to delete.
308
+ *
309
+ * @param tags Tag names (without refs/tags/ prefix)
310
+ */
311
+ setTags(...tags: string[]): this {
312
+ this.checkCallable();
313
+ this.tags.push(...tags);
314
+ return this;
315
+ }
316
+
317
+ /**
318
+ * Execute the tag deletion.
319
+ *
320
+ * @returns List of deleted tag names (full ref names)
321
+ * @throws RefNotFoundError if tag doesn't exist
322
+ */
323
+ async call(): Promise<string[]> {
324
+ this.checkCallable();
325
+ this.setCallable(false);
326
+
327
+ const deleted: string[] = [];
328
+
329
+ for (const name of this.tags) {
330
+ const refName = name.startsWith("refs/") ? name : `refs/tags/${name}`;
331
+
332
+ if (!(await this.refsStore.has(refName))) {
333
+ throw new RefNotFoundError(refName, `Tag '${name}' not found`);
334
+ }
335
+
336
+ await this.refsStore.delete(refName);
337
+ deleted.push(refName);
338
+ }
339
+
340
+ return deleted;
341
+ }
342
+ }
343
+
344
+ /**
345
+ * List tags.
346
+ *
347
+ * Equivalent to `git tag -l`.
348
+ *
349
+ * @example
350
+ * ```typescript
351
+ * // List all tags
352
+ * const tags = await git.tagList().call();
353
+ * ```
354
+ */
355
+ export class ListTagCommand extends GitCommand<Ref[]> {
356
+ /**
357
+ * Execute the tag listing.
358
+ *
359
+ * @returns List of tag refs
360
+ */
361
+ async call(): Promise<Ref[]> {
362
+ this.checkCallable();
363
+ this.setCallable(false);
364
+
365
+ const tags: Ref[] = [];
366
+
367
+ for await (const ref of this.refsStore.list("refs/tags/")) {
368
+ if ("objectId" in ref) {
369
+ tags.push(ref);
370
+ }
371
+ }
372
+
373
+ // Sort by name
374
+ tags.sort((a, b) => a.name.localeCompare(b.name));
375
+
376
+ return tags;
377
+ }
378
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Writing a tree back into the working tree.
3
+ *
4
+ * Shared by the commands that make the working tree match a tree object -
5
+ * `reset --hard` and `stash apply`. Both need the same two-phase shape: plan
6
+ * and validate the whole restore first, then write. A tree that cannot be
7
+ * restored faithfully therefore fails with the working tree still intact,
8
+ * rather than half-way through rewriting it.
9
+ */
10
+
11
+ import type { Blobs, ObjectId } from "@statewalker/vcs-core";
12
+ import { FileMode } from "@statewalker/vcs-core";
13
+ import type { Worktree } from "@statewalker/vcs-working-tree";
14
+
15
+ import type { CommandTrees } from "../git-command.js";
16
+
17
+ /** One file a restore plans to write back into the working tree. */
18
+ export interface RestoreEntry {
19
+ path: string;
20
+ objectId: ObjectId;
21
+ mode: number;
22
+ }
23
+
24
+ /** A validated restore, ready to execute. */
25
+ export interface TreeRestorePlan {
26
+ /** The files to write. */
27
+ entries: RestoreEntry[];
28
+ /**
29
+ * Every path the tree accounts for - the files above plus the gitlinks
30
+ * that are deliberately not written. A tracked path missing from this set
31
+ * is one the target tree deletes.
32
+ */
33
+ paths: Set<string>;
34
+ }
35
+
36
+ /**
37
+ * Walk a tree and plan which files to restore, validating as it goes.
38
+ *
39
+ * Throws on anything that cannot be restored faithfully, so the caller can
40
+ * abort before mutating the working tree.
41
+ *
42
+ * @param trees Tree storage to walk
43
+ * @param blobs Blob storage, checked for the content of every planned file
44
+ * @param treeId Tree to restore
45
+ * @param operation Names the operation in failure messages, e.g. `reset --hard`
46
+ */
47
+ export async function planTreeRestore(
48
+ trees: CommandTrees,
49
+ blobs: Blobs,
50
+ treeId: ObjectId,
51
+ operation: string,
52
+ ): Promise<TreeRestorePlan> {
53
+ const plan: TreeRestorePlan = { entries: [], paths: new Set() };
54
+ await planInto(trees, blobs, treeId, "", operation, plan);
55
+ return plan;
56
+ }
57
+
58
+ async function planInto(
59
+ trees: CommandTrees,
60
+ blobs: Blobs,
61
+ treeId: ObjectId,
62
+ prefix: string,
63
+ operation: string,
64
+ plan: TreeRestorePlan,
65
+ ): Promise<void> {
66
+ for await (const entry of trees.loadTree(treeId)) {
67
+ const path = prefix ? `${prefix}/${entry.name}` : entry.name;
68
+
69
+ if (entry.mode === FileMode.TREE) {
70
+ await planInto(trees, blobs, entry.id, path, operation, plan);
71
+ continue;
72
+ }
73
+
74
+ if (entry.mode === FileMode.GITLINK) {
75
+ // Submodule: neither `git reset --hard` nor `git stash apply` touches
76
+ // its contents. Record it so it is not mistaken for a path to delete.
77
+ plan.paths.add(path);
78
+ continue;
79
+ }
80
+
81
+ if (entry.mode === FileMode.SYMLINK) {
82
+ // The Worktree interface has no way to create a symbolic link, and
83
+ // writing the target path as a regular file would silently produce a
84
+ // working tree that does not match the tree being restored.
85
+ throw new Error(
86
+ `${operation} cannot restore ${path}: the worktree cannot create symbolic links`,
87
+ );
88
+ }
89
+
90
+ if (!(await blobs.has(entry.id))) {
91
+ throw new Error(`${operation} cannot restore ${path}: blob ${entry.id} is missing`);
92
+ }
93
+
94
+ plan.entries.push({ path, objectId: entry.id, mode: entry.mode });
95
+ plan.paths.add(path);
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Execute a plan produced by {@link planTreeRestore}, writing every file.
101
+ *
102
+ * @param worktree Working tree to write into
103
+ * @param blobs Blob storage to read content from
104
+ * @param plan The validated plan
105
+ * @param operation Names the operation in failure messages
106
+ */
107
+ export async function writeTreeRestorePlan(
108
+ worktree: Worktree,
109
+ blobs: Blobs,
110
+ plan: TreeRestorePlan,
111
+ operation: string,
112
+ ): Promise<void> {
113
+ for (const { path, objectId, mode } of plan.entries) {
114
+ const content = await blobs.load(objectId);
115
+ if (!content) {
116
+ throw new Error(`${operation} cannot restore ${path}: blob ${objectId} is missing`);
117
+ }
118
+
119
+ const chunks: Uint8Array[] = [];
120
+ for await (const chunk of content) {
121
+ chunks.push(chunk);
122
+ }
123
+
124
+ await worktree.writeContent(path, chunks, { mode, createParents: true });
125
+ }
126
+ }