@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,53 +1,72 @@
1
- import type { ObjectId } from "@statewalker/vcs-core";
2
- import { FileMode } from "@statewalker/vcs-core";
3
- import { MergeStage } from "@statewalker/vcs-working-tree";
1
+ import { FileMode, type ObjectId } from "@statewalker/vcs-core";
2
+ import {
3
+ compareWithWorktree,
4
+ findUntrackedFiles,
5
+ getStageState,
6
+ type IndexStatUpdate,
7
+ modeFromWorktree,
8
+ refreshIndexStats,
9
+ type StageStateValue,
10
+ statUpdateOf,
11
+ trackedUnder,
12
+ type Worktree,
13
+ } from "@statewalker/vcs-working-tree";
4
14
 
5
15
  import { GitCommand } from "../git-command.js";
6
- import { type Status, StatusImpl } from "../results/status-result.js";
16
+ import {
17
+ type Status,
18
+ type StatusCode,
19
+ type StatusFileEntry,
20
+ StatusImpl,
21
+ type StatusSide,
22
+ } from "../results/status-result.js";
23
+ import { worktreeModeTrust } from "./core-config.js";
7
24
 
8
- /**
9
- * Entry with full path for internal use.
10
- */
11
- interface PathEntry {
12
- path: string;
13
- mode: number;
14
- id: ObjectId;
15
- }
25
+ /** The porcelain `XY` of an unmerged path, by which of stages 1-3 it has. */
26
+ const UNMERGED_CODES: Record<number, [StatusCode, StatusCode]> = {
27
+ 1: ["D", "D"],
28
+ 2: ["A", "U"],
29
+ 3: ["U", "D"],
30
+ 4: ["U", "A"],
31
+ 5: ["D", "U"],
32
+ 6: ["A", "A"],
33
+ 7: ["U", "U"],
34
+ };
35
+
36
+ const S_IFMT = 0o170000;
37
+ const typeOf = (mode: number) => mode & S_IFMT;
16
38
 
17
39
  /**
18
- * Shows the staging area status compared to HEAD.
40
+ * Shows the working tree status, as `git status`: the index against HEAD (staged changes),
41
+ * the worktree against the index (unstaged changes: modified, deleted, type changed),
42
+ * unmerged entries, untracked files and, on request, ignored ones.
19
43
  *
20
- * This is a simplified version for repositories without working trees,
21
- * focusing on staged changes and conflicts.
44
+ * Worktree files are compared with the index through the stat it recorded: a file whose
45
+ * size and modification time still match is not read, unless its entry is racily clean
46
+ * (modified at or after the index was written), which is re-hashed as git does. Links are
47
+ * compared as links (mode 120000), the executable bit only where `core.filemode` trusts it,
48
+ * and the ignore rules are read afresh for each status. Untracked files are listed one by
49
+ * one (`--untracked-files=all`). Renames are not detected.
22
50
  *
23
- * Equivalent to `git status` but only for staged changes.
51
+ * Without a worktree only the index is compared with HEAD.
24
52
  *
25
- * Based on JGit's StatusCommand (staged-only subset).
53
+ * Based on JGit's StatusCommand.
26
54
  *
27
55
  * @example
28
56
  * ```typescript
29
- * // Get repository status
30
57
  * 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();
58
+ * if (status.isClean()) console.log("nothing to commit, working tree clean");
59
+ * console.log("Staged:", status.added, status.changed, status.removed);
60
+ * console.log("Unstaged:", status.modified, status.missing);
61
+ * console.log("Untracked:", status.untracked);
62
+ * // the lines of `git status --porcelain`
63
+ * console.log(formatStatusPorcelain(status));
47
64
  * ```
48
65
  */
49
66
  export class StatusCommand extends GitCommand<Status> {
50
67
  private paths: string[] = [];
68
+ private showIgnored = false;
69
+ private showUntracked = true;
51
70
 
52
71
  /**
53
72
  * Add a path filter.
@@ -62,72 +81,164 @@ export class StatusCommand extends GitCommand<Status> {
62
81
  return this;
63
82
  }
64
83
 
84
+ /**
85
+ * Whether to report the ignored files the index does not track (`--ignored`). Off by
86
+ * default.
87
+ */
88
+ setIgnored(ignored: boolean): this {
89
+ this.checkCallable();
90
+ this.showIgnored = ignored;
91
+ return this;
92
+ }
93
+
94
+ /**
95
+ * Whether to report untracked files (`--untracked-files=all`, the default, or `=no`).
96
+ */
97
+ setUntracked(untracked: boolean): this {
98
+ this.checkCallable();
99
+ this.showUntracked = untracked;
100
+ return this;
101
+ }
102
+
65
103
  async call(): Promise<Status> {
66
104
  this.checkCallable();
67
105
  this.setCallable(false);
106
+ const worktree = this.worktreeAccess;
107
+ // one operation: fresh ignore rules and one lstat cache for the whole status
108
+ return worktree?.batch ? worktree.batch(() => this.compute(worktree)) : this.compute(worktree);
109
+ }
68
110
 
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>();
111
+ private async compute(worktree: Worktree | undefined): Promise<Status> {
112
+ const head = new Map<string, StatusSide>();
79
113
  const headRef = await this.refsStore.resolve("HEAD");
80
114
  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
- }
115
+ const headCommit = await this.commits.load(headRef.objectId).catch(() => undefined);
116
+ if (headCommit) await this.collectTreeEntries(headCommit.tree, "", head);
89
117
  }
90
118
 
91
- // Get staging entries (only stage 0 = merged)
92
- const stagingEntries = new Map<string, PathEntry>();
119
+ const added = new Set<string>();
120
+ const changed = new Set<string>();
121
+ const removed = new Set<string>();
122
+ const conflicting = new Set<string>();
123
+ const conflictingStageState = new Map<string, StageStateValue>();
124
+ const modified = new Set<string>();
125
+ const missing = new Set<string>();
126
+ const untracked = new Set<string>();
127
+ const ignored = new Set<string>();
128
+ const files: StatusFileEntry[] = [];
129
+
130
+ const trust = worktree ? worktreeModeTrust(this.workingCopy, worktree) : undefined;
131
+ const indexTime = this.staging.getUpdateTime();
132
+ const tracked = new Set<string>();
133
+ const refresh: IndexStatUpdate[] = [];
134
+ const unmerged = new Map<string, [StatusSide?, StatusSide?, StatusSide?]>();
135
+
93
136
  for await (const entry of this.staging.entries()) {
94
- if (entry.stage === MergeStage.MERGED) {
95
- stagingEntries.set(entry.path, {
137
+ tracked.add(entry.path);
138
+ if (!this.matchesPath(entry.path)) continue;
139
+ if (entry.stage !== 0) {
140
+ const stages = unmerged.get(entry.path) ?? [undefined, undefined, undefined];
141
+ stages[entry.stage - 1] = { mode: entry.mode, id: entry.objectId };
142
+ unmerged.set(entry.path, stages);
143
+ continue;
144
+ }
145
+ const h = head.get(entry.path);
146
+ const staged = { mode: entry.mode, id: entry.objectId };
147
+ let x: StatusCode = " ";
148
+ if (!h) {
149
+ if (!entry.intentToAdd) {
150
+ x = "A";
151
+ added.add(entry.path);
152
+ }
153
+ } else if (h.id !== entry.objectId || h.mode !== entry.mode) {
154
+ x = typeOf(h.mode) === typeOf(entry.mode) ? "M" : "T";
155
+ changed.add(entry.path);
156
+ }
157
+ let y: StatusCode = " ";
158
+ let worktreeMode: number | undefined = entry.mode;
159
+ let commitChanged = false;
160
+ if (worktree && !entry.skipWorktree && !entry.assumeValid) {
161
+ const result = await compareWithWorktree(worktree, entry, { trust, indexTime });
162
+ worktreeMode = result.worktreeMode;
163
+ // proved clean only by hashing: its fresh stat goes into the index (git's refresh);
164
+ // changed behind a matching stat: smudged
165
+ const update = statUpdateOf(entry, result);
166
+ if (update) refresh.push(update);
167
+ if (entry.mode === FileMode.GITLINK && result.kind === "modified") commitChanged = true;
168
+ if (result.kind === "deleted") {
169
+ y = "D";
170
+ missing.add(entry.path);
171
+ } else if (result.kind) {
172
+ y = result.kind === "typechange" ? "T" : "M";
173
+ modified.add(entry.path);
174
+ } else if (entry.intentToAdd) {
175
+ y = "A";
176
+ added.add(entry.path);
177
+ }
178
+ }
179
+ if (x !== " " || y !== " ") {
180
+ // git's v2 line of an intent-to-add entry: no index side while the file is there
181
+ // (".A"), and the placeholder as the HEAD side once it is gone (".D")
182
+ const ita = entry.intentToAdd;
183
+ files.push({
96
184
  path: entry.path,
97
- mode: entry.mode,
98
- id: entry.objectId,
185
+ index: x,
186
+ worktree: y,
187
+ head: ita && y === "D" ? staged : h,
188
+ staged: ita && y === "A" ? undefined : staged,
189
+ worktreeMode,
190
+ ...(commitChanged ? { submoduleCommitChanged: true } : {}),
99
191
  });
100
192
  }
101
193
  }
102
194
 
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);
195
+ for (const [path, stages] of unmerged) {
196
+ conflicting.add(path);
197
+ const [base, ours, theirs] = stages;
198
+ conflictingStageState.set(path, getStageState(!!base, !!ours, !!theirs));
199
+ const mask = (base ? 1 : 0) | (ours ? 2 : 0) | (theirs ? 4 : 0);
200
+ const [x, y] = UNMERGED_CODES[mask];
201
+ let worktreeMode: number | undefined;
202
+ const current = worktree ? await worktree.getEntry(path) : undefined;
203
+ if (current && !current.isDirectory && trust) {
204
+ worktreeMode = modeFromWorktree(current.mode, (ours ?? theirs ?? base)?.mode, trust);
118
205
  }
206
+ files.push({ path, index: x, worktree: y, worktreeMode, stages: [base, ours, theirs] });
119
207
  }
120
208
 
121
- // Files in HEAD but not in staging = removed
122
- for (const [path] of headEntries) {
123
- if (!this.matchesPath(path)) continue;
209
+ for (const [path, h] of head) {
210
+ if (tracked.has(path) || !this.matchesPath(path)) continue;
211
+ removed.add(path);
212
+ files.push({ path, index: "D", worktree: " ", head: h });
213
+ }
124
214
 
125
- if (!stagingEntries.has(path)) {
126
- removed.add(path);
215
+ if (worktree && this.showUntracked) {
216
+ for await (const file of findUntrackedFiles(worktree, (p) => tracked.has(p), {
217
+ hasTrackedUnder: trackedUnder(tracked),
218
+ includeIgnored: this.showIgnored,
219
+ filter: (p) => this.matchesPath(p),
220
+ })) {
221
+ if (file.ignored) {
222
+ ignored.add(file.path);
223
+ files.push({ path: file.path, index: "!", worktree: "!" });
224
+ } else {
225
+ untracked.add(file.path);
226
+ files.push({ path: file.path, index: "?", worktree: "?" });
227
+ }
127
228
  }
128
229
  }
129
230
 
130
- return new StatusImpl(added, changed, removed, conflicting);
231
+ // as git status: the refreshed stats written back when the index is free and unchanged
232
+ await refreshIndexStats(this.staging, refresh);
233
+
234
+ return new StatusImpl(added, changed, removed, conflicting, {
235
+ modified,
236
+ missing,
237
+ untracked,
238
+ ignored,
239
+ conflictingStageState,
240
+ files,
241
+ });
131
242
  }
132
243
 
133
244
  /**
@@ -137,13 +248,11 @@ export class StatusCommand extends GitCommand<Status> {
137
248
  if (this.paths.length === 0) {
138
249
  return true;
139
250
  }
140
-
141
- for (const filterPath of this.paths) {
142
- if (
143
- path === filterPath ||
144
- path.startsWith(`${filterPath}/`) ||
145
- filterPath.startsWith(`${path}/`)
146
- ) {
251
+ const p = path.endsWith("/") ? path.slice(0, -1) : path;
252
+ for (const raw of this.paths) {
253
+ const filterPath = raw.replace(/\/+$/, "");
254
+ if (filterPath === "" || filterPath === ".") return true;
255
+ if (p === filterPath || p.startsWith(`${filterPath}/`) || filterPath.startsWith(`${p}/`)) {
147
256
  return true;
148
257
  }
149
258
  }
@@ -156,17 +265,14 @@ export class StatusCommand extends GitCommand<Status> {
156
265
  private async collectTreeEntries(
157
266
  treeId: ObjectId,
158
267
  prefix: string,
159
- entries: Map<string, PathEntry>,
268
+ entries: Map<string, StatusSide>,
160
269
  ): Promise<void> {
161
270
  for await (const entry of this.trees.loadTree(treeId)) {
162
271
  const path = prefix ? `${prefix}/${entry.name}` : entry.name;
163
-
164
272
  if (entry.mode === FileMode.TREE) {
165
- // Recurse into subtree
166
273
  await this.collectTreeEntries(entry.id, path, entries);
167
274
  } else {
168
- // Blob entry
169
- entries.set(path, { path, mode: entry.mode, id: entry.id });
275
+ entries.set(path, { mode: entry.mode, id: entry.id });
170
276
  }
171
277
  }
172
278
  }
@@ -2,14 +2,14 @@
2
2
  * Writing a tree back into the working tree.
3
3
  *
4
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
5
+ * `reset --hard`, `stash apply` and the checkout of `clone`. All need the
6
+ * same two-phase shape: plan and validate the whole restore first, then write. A tree that cannot be
7
7
  * restored faithfully therefore fails with the working tree still intact,
8
8
  * rather than half-way through rewriting it.
9
9
  */
10
10
 
11
11
  import type { Blobs, ObjectId } from "@statewalker/vcs-core";
12
- import { FileMode } from "@statewalker/vcs-core";
12
+ import { FileMode, isValidWorktreePath } from "@statewalker/vcs-core";
13
13
  import type { Worktree } from "@statewalker/vcs-working-tree";
14
14
 
15
15
  import type { CommandTrees } from "../git-command.js";
@@ -31,30 +31,110 @@ export interface TreeRestorePlan {
31
31
  * is one the target tree deletes.
32
32
  */
33
33
  paths: Set<string>;
34
+ /** The gitlinks (submodules) of the tree, which are not written. */
35
+ gitlinks: RestoreEntry[];
36
+ /**
37
+ * With `ignoreCase`: files whose paths differ only in case (`README`, `readme`). Both are
38
+ * written, the last one wins, as git checks them out with its "the following paths have
39
+ * collided" warning.
40
+ */
41
+ collided: string[];
42
+ }
43
+
44
+ /** Options of {@link planTreeRestore}. */
45
+ export interface TreeRestoreOptions {
46
+ /**
47
+ * Plan symlinks as entries to write (their blob is the link target), for a
48
+ * worktree that writes mode `0o120000` as a link or as a file holding the
49
+ * target, as git does. Without it a symlink fails the plan.
50
+ */
51
+ symlinks?: boolean;
52
+ /**
53
+ * Compare paths case-insensitively (`core.ignorecase`), as a case-folding filesystem
54
+ * would: a path beneath a file, link or submodule of another case (`A` a link, `a/x`)
55
+ * is refused, it would be written through the link; two files differing only in case
56
+ * are both planned (the last wins) and reported in `collided`, as git does.
57
+ */
58
+ ignoreCase?: boolean;
59
+ /** The worktree is on Windows (`capabilities.windowsPaths`): git's Windows path rules. */
60
+ windows?: boolean;
61
+ /** Top-level names the worktree's storage reserves (`capabilities.reservedNames`) */
62
+ reservedNames?: string[];
63
+ /**
64
+ * Only these paths will be written: the blobs of the others are not checked (every path
65
+ * is still validated). Absent: every blob is checked.
66
+ */
67
+ writing?: Set<string>;
34
68
  }
35
69
 
36
70
  /**
37
71
  * Walk a tree and plan which files to restore, validating as it goes.
38
72
  *
39
73
  * Throws on anything that cannot be restored faithfully, so the caller can
40
- * abort before mutating the working tree.
74
+ * abort before mutating the working tree: a path git's `verify_path` refuses
75
+ * (`.git` under any spelling, a symlinked `.gitmodules`), and two entries that
76
+ * collide - the same path twice, a file and a directory of one name, or a path
77
+ * beneath a planned file, symlink or submodule (which would write through the
78
+ * link), compared case-insensitively with `ignoreCase`.
41
79
  *
42
80
  * @param trees Tree storage to walk
43
81
  * @param blobs Blob storage, checked for the content of every planned file
44
82
  * @param treeId Tree to restore
45
83
  * @param operation Names the operation in failure messages, e.g. `reset --hard`
84
+ * @param options What else the worktree can restore
46
85
  */
47
86
  export async function planTreeRestore(
48
87
  trees: CommandTrees,
49
88
  blobs: Blobs,
50
89
  treeId: ObjectId,
51
90
  operation: string,
91
+ options: TreeRestoreOptions = {},
52
92
  ): Promise<TreeRestorePlan> {
53
- const plan: TreeRestorePlan = { entries: [], paths: new Set() };
54
- await planInto(trees, blobs, treeId, "", operation, plan);
93
+ const plan: TreeRestorePlan = { entries: [], paths: new Set(), gitlinks: [], collided: [] };
94
+ await planInto(trees, blobs, treeId, "", operation, plan, options, new Map());
55
95
  return plan;
56
96
  }
57
97
 
98
+ /** What a planned path holds, by its (case-folded) key, and its first spelling. */
99
+ type PlannedKinds = Map<string, { kind: "tree" | "leaf"; path: string }>;
100
+
101
+ /**
102
+ * Records `path` as a tree or a leaf, refusing a path that collides with a planned one in
103
+ * a way that would write through it; two leaves differing only in case are recorded in
104
+ * `collided` instead (case-folding filesystems keep the last one).
105
+ */
106
+ function claim(
107
+ planned: PlannedKinds,
108
+ plan: TreeRestorePlan,
109
+ path: string,
110
+ kind: "tree" | "leaf",
111
+ operation: string,
112
+ options: TreeRestoreOptions,
113
+ ): void {
114
+ const key = options.ignoreCase ? path.toLowerCase() : path;
115
+ const existing = planned.get(key);
116
+ if (existing) {
117
+ if (existing.path === path || existing.kind !== kind) {
118
+ throw new Error(`${operation} cannot restore ${path}: it collides with another entry`);
119
+ }
120
+ if (kind === "leaf") {
121
+ if (!plan.collided.includes(existing.path)) plan.collided.push(existing.path);
122
+ plan.collided.push(path);
123
+ }
124
+ return;
125
+ }
126
+ // every leading component must be a planned tree, never a file, link or submodule
127
+ const parts = key.split("/");
128
+ for (let i = 1; i < parts.length; i++) {
129
+ if (planned.get(parts.slice(0, i).join("/"))?.kind === "leaf") {
130
+ throw new Error(
131
+ `${operation} cannot restore ${path}: ${parts.slice(0, i).join("/")} is not a directory`,
132
+ );
133
+ }
134
+ }
135
+ planned.set(key, { kind, path });
136
+ }
137
+
58
138
  async function planInto(
59
139
  trees: CommandTrees,
60
140
  blobs: Blobs,
@@ -62,32 +142,47 @@ async function planInto(
62
142
  prefix: string,
63
143
  operation: string,
64
144
  plan: TreeRestorePlan,
145
+ options: TreeRestoreOptions,
146
+ planned: PlannedKinds,
65
147
  ): Promise<void> {
66
148
  for await (const entry of trees.loadTree(treeId)) {
67
149
  const path = prefix ? `${prefix}/${entry.name}` : entry.name;
150
+ if (
151
+ !isValidWorktreePath(path, entry.mode, { windows: options.windows === true }) ||
152
+ // a name the storage reserves at the worktree's root (a simulated-links table)
153
+ (prefix === "" &&
154
+ options.reservedNames?.some(
155
+ (name) => entry.name.normalize("NFC").toLowerCase() === name.toLowerCase(),
156
+ ))
157
+ ) {
158
+ throw new Error(`${operation} cannot restore ${JSON.stringify(path)}: invalid path`);
159
+ }
68
160
 
69
161
  if (entry.mode === FileMode.TREE) {
70
- await planInto(trees, blobs, entry.id, path, operation, plan);
162
+ claim(planned, plan, path, "tree", operation, options);
163
+ await planInto(trees, blobs, entry.id, path, operation, plan, options, planned);
71
164
  continue;
72
165
  }
166
+ claim(planned, plan, path, "leaf", operation, options);
73
167
 
74
168
  if (entry.mode === FileMode.GITLINK) {
75
169
  // Submodule: neither `git reset --hard` nor `git stash apply` touches
76
170
  // its contents. Record it so it is not mistaken for a path to delete.
77
171
  plan.paths.add(path);
172
+ plan.gitlinks.push({ path, objectId: entry.id, mode: entry.mode });
78
173
  continue;
79
174
  }
80
175
 
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.
176
+ if (entry.mode === FileMode.SYMLINK && !options.symlinks) {
177
+ // Unless the caller opts in (clone), a symlink is refused: writing the
178
+ // target path as a regular file would silently produce a working tree
179
+ // that does not match the tree being restored.
85
180
  throw new Error(
86
181
  `${operation} cannot restore ${path}: the worktree cannot create symbolic links`,
87
182
  );
88
183
  }
89
184
 
90
- if (!(await blobs.has(entry.id))) {
185
+ if ((!options.writing || options.writing.has(path)) && !(await blobs.has(entry.id))) {
91
186
  throw new Error(`${operation} cannot restore ${path}: blob ${entry.id} is missing`);
92
187
  }
93
188
 
@@ -109,6 +204,19 @@ export async function writeTreeRestorePlan(
109
204
  blobs: Blobs,
110
205
  plan: TreeRestorePlan,
111
206
  operation: string,
207
+ options: TreeWriteOptions = {},
208
+ ): Promise<void> {
209
+ // one batch: the worktree may cache directories verified not to be links meanwhile
210
+ const run = () => writePlan(worktree, blobs, plan, operation, options);
211
+ await (worktree.batch ? worktree.batch(run) : run());
212
+ }
213
+
214
+ async function writePlan(
215
+ worktree: Worktree,
216
+ blobs: Blobs,
217
+ plan: TreeRestorePlan,
218
+ operation: string,
219
+ options: TreeWriteOptions,
112
220
  ): Promise<void> {
113
221
  for (const { path, objectId, mode } of plan.entries) {
114
222
  const content = await blobs.load(objectId);
@@ -116,7 +224,28 @@ export async function writeTreeRestorePlan(
116
224
  throw new Error(`${operation} cannot restore ${path}: blob ${objectId} is missing`);
117
225
  }
118
226
 
227
+ // without symlinks (core.symlinks=false) a link is a file holding its target
228
+ const written =
229
+ mode === FileMode.SYMLINK && options.symlinks === false ? FileMode.REGULAR_FILE : mode;
119
230
  // the blob streams into the file; it is never held whole in memory
120
- await worktree.writeContent(path, content, { mode, createParents: true });
231
+ await worktree.writeContent(path, content, {
232
+ mode: written,
233
+ createParents: true,
234
+ ...(options.replaceInTheWay ? { replaceInTheWay: true } : {}),
235
+ });
236
+ }
237
+ // a submodule is an empty directory, as git checks out an unpopulated one
238
+ if (options.gitlinks) {
239
+ for (const { path } of plan.gitlinks) await worktree.mkdir(path);
121
240
  }
122
241
  }
242
+
243
+ /** Options of {@link writeTreeRestorePlan}. */
244
+ export interface TreeWriteOptions {
245
+ /** Write symlinks as links (default); false writes them as files holding the target. */
246
+ symlinks?: boolean;
247
+ /** A forced checkout: unlink a file or link standing where a directory must go. */
248
+ replaceInTheWay?: boolean;
249
+ /** Create an empty directory for each gitlink (submodule). */
250
+ gitlinks?: boolean;
251
+ }