@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,11 +1,400 @@
1
- import { CannotDeleteCurrentBranchError, CommitNotFoundError, EmptyCommitError, IncompatibleOptionsError, InvalidArgumentError, InvalidMainlineParentError, InvalidMergeHeadsError, InvalidRefNameError, InvalidRemoteError, InvalidStashIndexError, InvalidTagNameError, MissingArgumentError, MultipleParentsNotAllowedError, NoFilepatternError, NoHeadError, NoMergeBaseError, NoMessageError, NoRebaseInProgressError, NonFastForwardError, NotADirectoryError, NotFastForwardError, NotImplementedError, NotMergedError, PathNotFoundInTreeError, PathNotInIndexError, PushRejectedException, RefAlreadyExistsError, RefNotFoundError, RemoteAlreadyExistsError, RemoteNotFoundError, StashApplyFailedError, StoreNotAvailableError, UnmergedPathsError, UpstreamRequiredError } from "./errors/index.js";
2
- import { C as isMergeSuccessful, d as createAddEntry, m as createModifyEntry, p as createDeleteEntry, t as StatusImpl } from "./status-result-BapZoQaR.js";
3
- import { DEFAULT_BIG_FILE_THRESHOLD, EMPTY_BLOB_ID, FileMode, ObjectType, compareRefNames, createInMemoryFilesApi, createMemoryHistory, isSymbolicRef, isValidBranchName, isValidTagName, isValidWorktreePath, probeBlob } from "@statewalker/vcs-core";
4
- import { DeleteStagingEntry, MergeStage, UpdateStagingEntry, createMemoryCheckout, storeWorktreeFile } from "@statewalker/vcs-working-tree";
5
- import { DEFAULT_ALGORITHM, MergeContentStrategy, RawText, RawTextComparator, getAlgorithm, merge3Way } from "@statewalker/vcs-utils";
6
- import { createRepositoryFacade, createTransportRefStore, expandFromDestination, expandFromSource, fetch, lsRemote, mapRejectReason, matchDestination, matchSource, parseRefSpec, push } from "@statewalker/vcs-transport";
7
- import { FileStagingStore, createFileWorktree, createGitFilesHistoryFromFiles } from "@statewalker/vcs-store-files";
1
+ import { CannotDeleteCurrentBranchError, CloneCheckoutError, CommitNotFoundError, EmptyCommitError, IncompatibleOptionsError, InvalidArgumentError, InvalidMainlineParentError, InvalidMergeHeadsError, InvalidRefNameError, InvalidRemoteError, InvalidStashIndexError, InvalidTagNameError, MissingArgumentError, MultipleParentsNotAllowedError, NoFilepatternError, NoHeadError, NoMergeBaseError, NoMessageError, NoRebaseInProgressError, NonFastForwardError, NotADirectoryError, NotFastForwardError, NotImplementedError, NotMergedError, PathNotFoundInTreeError, PathNotInIndexError, PushRejectedException, RefAlreadyExistsError, RefNotFoundError, RemoteAlreadyExistsError, RemoteNotFoundError, StashApplyFailedError, StoreNotAvailableError, UnmergedPathsError, UpstreamRequiredError } from "./errors/index.js";
2
+ import { f as createAddEntry, h as createModifyEntry, m as createDeleteEntry, t as StatusImpl, w as isMergeSuccessful } from "./status-result-BpyUK1Sg.js";
3
+ import { DEFAULT_BIG_FILE_THRESHOLD, EMPTY_BLOB_ID, FileMode, ObjectType, compareRefNames, createInMemoryFilesApi, createMemoryHistory, formatPersonIdent, isSymbolicRef, isValidBranchName, isValidRefName, isValidTagName, isValidWorktreePath, probeBlob } from "@statewalker/vcs-core";
4
+ import { DeleteStagingEntry, MergeStage, UpdateStagingEntry, basicStatMatches, compareWithWorktree, createIndexTree, createMemoryCheckout, createUntrackedTree, createWorktreeTree, directoriesOf, entryStatOf, findUntrackedFiles, flattenTree, getStageState, hasTrackedChanges, modeFromWorktree, refreshIndexStats, refreshableEntries, scanIndex, statUpdateOf, storeWorktreeFile, trackedUnder } from "@statewalker/vcs-working-tree";
5
+ import { DEFAULT_ALGORITHM, MergeContentStrategy, RawText, RawTextComparator, getAlgorithm, merge3Way, mergeLines } from "@statewalker/vcs-utils";
6
+ import { createRepositoryFacade, createTransportRefStore, expandFromDestination, expandFromSource, fetch, formatFetchHead, lsRefs, lsRemote, mapRejectReason, matchDestination, matchSource, openHttpConnection, parseRefSpec, push } from "@statewalker/vcs-transport";
7
+ import { FileStagingStore, createFileWorktree, createGitFilesHistoryFromFiles, probeCaseFolding, resolveLinkedGitDir } from "@statewalker/vcs-store-files";
8
8
  import { MemoryStagingStore } from "@statewalker/vcs-store-mem";
9
+ //#region src/remote-config/remote-config-store.ts
10
+ /** The default fetch refspec `git remote add` writes for a remote. */
11
+ function defaultFetchRefspec(name) {
12
+ return `+refs/heads/*:refs/remotes/${name}/*`;
13
+ }
14
+ const GIT_CONFIG_METHODS = [
15
+ "get",
16
+ "getAll",
17
+ "set",
18
+ "add",
19
+ "unset",
20
+ "unsetSection",
21
+ "subsections"
22
+ ];
23
+ function isGitConfigLike(config) {
24
+ if (!config) return false;
25
+ return GIT_CONFIG_METHODS.every((method) => typeof config[method] === "function");
26
+ }
27
+ /**
28
+ * Split `<section>.<subsection>.<name>` into its subsection.
29
+ *
30
+ * Follows git's key grammar (and `GitWorkingCopyConfig`'s): the first part is
31
+ * the section, the last is the variable name and everything in between is the
32
+ * subsection, which keeps its case and may itself contain dots.
33
+ *
34
+ * @returns undefined when the key is not a subsection key of `section`
35
+ */
36
+ function subsectionOf(key, section) {
37
+ const parts = key.split(".");
38
+ if (parts.length < 3 || parts[0].toLowerCase() !== section.toLowerCase()) return void 0;
39
+ return parts.slice(1, -1).join(".");
40
+ }
41
+ /**
42
+ * {@link GitConfigLike} over a plain `{[key: string]: unknown}` bag.
43
+ *
44
+ * Keys are stored in canonical dotted form (`remote.origin.url`) — the same
45
+ * form `GitWorkingCopyConfig` mirrors as own properties — so the two
46
+ * representations read alike. A repeated key holds an array.
47
+ *
48
+ * There is no `save()`: this config lives and dies with the working copy
49
+ * instance, which is exactly what a working copy without a config file has.
50
+ */
51
+ var PlainObjectConfig = class {
52
+ bag;
53
+ constructor(bag) {
54
+ this.bag = bag;
55
+ }
56
+ get(key) {
57
+ const values = this.getAll(key);
58
+ return values.length > 0 ? values[values.length - 1] : void 0;
59
+ }
60
+ getAll(key) {
61
+ const value = this.bag[key];
62
+ if (value === void 0) return [];
63
+ return Array.isArray(value) ? [...value] : [value];
64
+ }
65
+ set(key, value) {
66
+ this.bag[key] = value;
67
+ }
68
+ add(key, value) {
69
+ const existing = this.getAll(key);
70
+ this.bag[key] = existing.length > 0 ? [...existing, value] : value;
71
+ }
72
+ unset(key) {
73
+ delete this.bag[key];
74
+ }
75
+ unsetSection(section) {
76
+ const parts = section.split(".");
77
+ if (parts.length < 2) return;
78
+ const subsection = parts.slice(1).join(".");
79
+ for (const key of Object.keys(this.bag)) if (subsectionOf(key, parts[0]) === subsection) delete this.bag[key];
80
+ }
81
+ renameSection(oldSection, newSection) {
82
+ const [section, ...oldParts] = oldSection.split(".");
83
+ const oldSub = oldParts.join(".");
84
+ const newSub = newSection.split(".").slice(1).join(".");
85
+ for (const key of Object.keys(this.bag)) {
86
+ if (subsectionOf(key, section) !== oldSub) continue;
87
+ const name = key.slice(key.lastIndexOf(".") + 1);
88
+ this.bag[`${section}.${newSub}.${name}`] = this.bag[key];
89
+ delete this.bag[key];
90
+ }
91
+ }
92
+ subsections(section) {
93
+ const found = /* @__PURE__ */ new Set();
94
+ for (const key of Object.keys(this.bag)) {
95
+ if (this.getAll(key).length === 0) continue;
96
+ const subsection = subsectionOf(key, section);
97
+ if (subsection !== void 0) found.add(subsection);
98
+ }
99
+ return [...found];
100
+ }
101
+ };
102
+ /**
103
+ * The `[remote "<name>"]` sections of a working copy's configuration.
104
+ *
105
+ * Reading a remote is a **union** of two sources, and stays that way: the
106
+ * config sections, plus every name that appears under `refs/remotes/`. A
107
+ * remote that was fetched into tracking refs without ever being configured is
108
+ * a real remote to `git remote`, and so it is here — it simply has no URL.
109
+ */
110
+ var RemoteConfigStore = class RemoteConfigStore {
111
+ config;
112
+ constructor(config) {
113
+ this.config = config;
114
+ }
115
+ /**
116
+ * Wrap a working copy's configuration.
117
+ *
118
+ * A config that implements the git-config methods is used directly, so
119
+ * changes reach its backing file; anything else is driven as a plain bag.
120
+ */
121
+ static from(workingCopy) {
122
+ const config = workingCopy.config;
123
+ if (isGitConfigLike(config)) return new RemoteConfigStore(config);
124
+ return new RemoteConfigStore(new PlainObjectConfig(config ?? {}));
125
+ }
126
+ /** Remote names that have a config section. */
127
+ configuredNames() {
128
+ return this.config.subsections("remote");
129
+ }
130
+ /** Whether the remote has a config section. */
131
+ isConfigured(name) {
132
+ return this.configuredNames().includes(name);
133
+ }
134
+ /**
135
+ * Read a remote, filling in the default fetch refspec when none is
136
+ * configured, exactly as `git remote` reports one.
137
+ */
138
+ read(name) {
139
+ const fetchRefspecs = this.strings(name, "fetch");
140
+ return {
141
+ name,
142
+ urls: this.strings(name, "url"),
143
+ pushUrls: this.strings(name, "pushurl"),
144
+ fetchRefspecs: fetchRefspecs.length > 0 ? fetchRefspecs : [defaultFetchRefspec(name)],
145
+ pushRefspecs: this.strings(name, "push")
146
+ };
147
+ }
148
+ /**
149
+ * The `remote.<name>.fetch` lines as configured, without the default {@link read} fills
150
+ * in: a remote without any fetches only its HEAD, as `git fetch <name>` does.
151
+ */
152
+ configuredFetchRefspecs(name) {
153
+ return this.strings(name, "fetch");
154
+ }
155
+ /** Write every field of a remote, replacing whatever was there. */
156
+ write(remote) {
157
+ this.setAll(remote.name, "url", remote.urls);
158
+ this.setAll(remote.name, "fetch", remote.fetchRefspecs);
159
+ this.setAll(remote.name, "pushurl", remote.pushUrls);
160
+ this.setAll(remote.name, "push", remote.pushRefspecs);
161
+ }
162
+ /** Drop the whole `[remote "<name>"]` section. */
163
+ remove(name) {
164
+ this.config.unsetSection(`remote.${name}`);
165
+ }
166
+ /**
167
+ * Rename the `[remote "<oldName>"]` section to `[remote "<newName>"]`, in place where the
168
+ * config can (git's rename_section), else by copying every `remote.<oldName>.*` variable.
169
+ */
170
+ rename(oldName, newName) {
171
+ if (this.config.renameSection) {
172
+ this.config.renameSection(`remote.${oldName}`, `remote.${newName}`);
173
+ return;
174
+ }
175
+ const variables = /* @__PURE__ */ new Set();
176
+ for (const key of Object.keys(this.config)) if (subsectionOf(key, "remote") === oldName) variables.add(key.slice(key.lastIndexOf(".") + 1));
177
+ for (const variable of variables) {
178
+ const values = this.strings(oldName, variable);
179
+ if (values.length > 0) this.setAll(newName, variable, values);
180
+ }
181
+ this.config.unsetSection(`remote.${oldName}`);
182
+ }
183
+ /** Subsection names of a section (`branch`: the branch names with configuration). */
184
+ subsections(section) {
185
+ return this.config.subsections(section);
186
+ }
187
+ /** Remove every value of a config variable. */
188
+ unset(key) {
189
+ this.config.unset(key);
190
+ }
191
+ /**
192
+ * Point a remote at a URL.
193
+ *
194
+ * @param push Write `pushurl` instead of `url`
195
+ * @param oldUrl Replace only this URL, as `git remote set-url <name> <new> <old>` does
196
+ * @throws InvalidArgumentError if `oldUrl` is not among the configured URLs
197
+ */
198
+ setUrl(name, url, options = {}) {
199
+ const variable = options.push ? "pushurl" : "url";
200
+ if (options.oldUrl === void 0) {
201
+ this.setAll(name, variable, [url]);
202
+ return;
203
+ }
204
+ const existing = this.strings(name, variable);
205
+ if (!existing.includes(options.oldUrl)) throw new InvalidArgumentError("oldUri", `No such URL found: ${options.oldUrl}`);
206
+ this.setAll(name, variable, existing.map((value) => value === options.oldUrl ? url : value));
207
+ }
208
+ /**
209
+ * The URL to talk to a remote over, or undefined when it has none.
210
+ *
211
+ * @param push Prefer `pushurl`, falling back to `url`, as git does
212
+ */
213
+ urlFor(name, options = {}) {
214
+ if (options.push) {
215
+ const pushUrl = this.strings(name, "pushurl")[0];
216
+ if (pushUrl !== void 0) return pushUrl;
217
+ }
218
+ return this.strings(name, "url")[0];
219
+ }
220
+ /** A config variable (`push.default`, `branch.main.merge`), the last value when repeated. */
221
+ value(key) {
222
+ const value = this.config.get(key);
223
+ return value === void 0 || value === null ? void 0 : String(value);
224
+ }
225
+ /** Every value of a config variable (`branch.main.merge` may repeat). */
226
+ values(key) {
227
+ return this.config.getAll(key).filter((value) => value !== void 0 && value !== null).map((value) => String(value));
228
+ }
229
+ /** Sets a config variable, replacing every value it had. */
230
+ setValue(key, value) {
231
+ this.config.set(key, value);
232
+ }
233
+ /** Sets every value of a config variable, in order (none: unset). */
234
+ setValues(key, values) {
235
+ if (values.length === 0) {
236
+ this.config.unset(key);
237
+ return;
238
+ }
239
+ this.config.set(key, values[0]);
240
+ for (const value of values.slice(1)) this.config.add(key, value);
241
+ }
242
+ /** Flush to the backing file, if the config has one. */
243
+ async save() {
244
+ await this.config.save?.();
245
+ }
246
+ strings(name, variable) {
247
+ return this.config.getAll(`remote.${name}.${variable}`).filter((value) => value !== void 0 && value !== null).map((value) => String(value));
248
+ }
249
+ setAll(name, variable, values) {
250
+ const key = `remote.${name}.${variable}`;
251
+ if (values.length === 0) {
252
+ this.config.unset(key);
253
+ return;
254
+ }
255
+ this.config.set(key, values[0]);
256
+ for (const value of values.slice(1)) this.config.add(key, value);
257
+ }
258
+ };
259
+ /**
260
+ * Every remote name known to the repository: config sections ∪ the names
261
+ * appearing under `refs/remotes/`.
262
+ */
263
+ async function listRemoteNames(store, refs) {
264
+ const names = new Set(store.configuredNames());
265
+ for await (const ref of refs.list("refs/remotes/")) {
266
+ const parts = ref.name.split("/");
267
+ if (parts.length >= 3) names.add(parts[2]);
268
+ }
269
+ return [...names];
270
+ }
271
+ //#endregion
272
+ //#region src/remote-config/remote-refs.ts
273
+ /**
274
+ * Multi-ref writes of the remote commands (`git remote remove`, `git remote rename`,
275
+ * `git fetch --prune`), as one ref batch where the store can apply it.
276
+ *
277
+ * Internal to the package.
278
+ */
279
+ /**
280
+ * Deletes `names` with their reflogs: the refs holding an object id in one atomic batch
281
+ * (logged `message` where the store logs deletes), symbolic refs themselves (not their
282
+ * targets) one by one, as git deletes with REF_NO_DEREF. A store that cannot batch several
283
+ * refs (`unsupported`) deletes them one by one.
284
+ *
285
+ * @throws Error naming the refs when the batch is refused (nothing deleted then)
286
+ */
287
+ async function deleteRefs(refs, names, message) {
288
+ const direct = [];
289
+ const symbolic = [];
290
+ for (const name of names) {
291
+ const ref = await refs.get(name);
292
+ if (!ref) continue;
293
+ (isSymbolicRef(ref) ? symbolic : direct).push(name);
294
+ }
295
+ if (direct.length > 0) {
296
+ const result = await refs.batch(direct.map((name) => ({
297
+ name,
298
+ new: null
299
+ })), { message });
300
+ if (!result.ok) {
301
+ if (!result.rejected.every((r) => r.reason === "unsupported")) throw refused(result);
302
+ for (const name of direct) await refs.remove(name);
303
+ }
304
+ }
305
+ for (const name of symbolic) await refs.remove(name);
306
+ }
307
+ /**
308
+ * Renames refs, as `git remote rename` moves `refs/remotes/<old>/*`: the refs holding an
309
+ * object id are deleted and created under their new names in one atomic batch, each new
310
+ * name with the reflog lines given (the old log, carried over); symbolic refs are then
311
+ * re-created under their new names pointing at `symbolicTarget(old target)`. A store whose
312
+ * batch refuses several refs (`unsupported`: vcs-core's interim `kvStoreRefs`, which keeps
313
+ * no reflogs) moves them one by one: each new name is created only if it does not exist
314
+ * (compare-and-swap) before the old one goes, so no ref is overwritten or lost.
315
+ *
316
+ * @throws Error naming the refs when the batch is refused (a name conflict: nothing moved),
317
+ * or naming the ref whose new name exists in the one-by-one move (the refs before it moved)
318
+ */
319
+ async function moveRefs(refs, moves, symbolicTarget) {
320
+ const direct = [];
321
+ const symbolic = [];
322
+ for (const move of moves) {
323
+ const ref = await refs.get(move.from);
324
+ if (!ref) continue;
325
+ if (isSymbolicRef(ref)) symbolic.push({
326
+ move,
327
+ target: ref.target
328
+ });
329
+ else if (ref.objectId) direct.push({
330
+ move,
331
+ id: ref.objectId
332
+ });
333
+ }
334
+ if (direct.length > 0) {
335
+ const commands = [...direct.map(({ move, id }) => ({
336
+ name: move.from,
337
+ old: id,
338
+ new: null
339
+ })), ...direct.map(({ move, id }) => ({
340
+ name: move.to,
341
+ old: null,
342
+ new: id,
343
+ ...move.reflog ? { reflog: move.reflog } : {}
344
+ }))];
345
+ const result = await refs.batch(commands);
346
+ if (!result.ok) {
347
+ if (!result.rejected.every((r) => r.reason === "unsupported")) throw refused(result);
348
+ for (const { move, id } of direct) {
349
+ if (!(await refs.compareAndSwap(move.to, void 0, id)).success) throw new Error(`Cannot update refs: ${move.to} exists`);
350
+ await refs.remove(move.from);
351
+ }
352
+ }
353
+ }
354
+ for (const { move, target } of symbolic) {
355
+ if (await refs.has(move.to)) throw new Error(`Cannot update refs: ${move.to} exists`);
356
+ await refs.setSymbolic(move.to, symbolicTarget(target));
357
+ await refs.remove(move.from);
358
+ }
359
+ }
360
+ function refused(result) {
361
+ const why = result.rejected.map((r) => `${r.name}: ${r.reason}`).join(", ");
362
+ return /* @__PURE__ */ new Error(`Cannot update refs: ${why}`);
363
+ }
364
+ //#endregion
365
+ //#region src/commands/core-config.ts
366
+ /** A git boolean (`true`/`yes`/`on`/`1`, `false`/`no`/`off`/`0`), else `fallback`. */
367
+ function coreBool(workingCopy, name, fallback) {
368
+ const value = RemoteConfigStore.from(workingCopy).value(`core.${name}`)?.trim().toLowerCase();
369
+ if (value === void 0) return fallback;
370
+ if ([
371
+ "false",
372
+ "no",
373
+ "off",
374
+ "0"
375
+ ].includes(value)) return false;
376
+ if ([
377
+ "true",
378
+ "yes",
379
+ "on",
380
+ "1",
381
+ ""
382
+ ].includes(value)) return true;
383
+ return fallback;
384
+ }
385
+ /**
386
+ * Whether the worktree's executable bits and symbolic links are real: the worktree can
387
+ * represent them and `core.filemode` / `core.symlinks` are not false.
388
+ */
389
+ function worktreeModeTrust(workingCopy, worktree) {
390
+ return {
391
+ fullStat: !(RemoteConfigStore.from(workingCopy).value("core.checkStat")?.trim().toLowerCase() === "minimal"),
392
+ executable: worktree.capabilities?.executable !== false && coreBool(workingCopy, "filemode", true),
393
+ symlinks: worktree.capabilities?.symlinks !== false && coreBool(workingCopy, "symlinks", true),
394
+ ctime: coreBool(workingCopy, "trustctime", true) && RemoteConfigStore.from(workingCopy).value("core.checkStat")?.trim().toLowerCase() !== "minimal"
395
+ };
396
+ }
397
+ //#endregion
9
398
  //#region src/git-command.ts
10
399
  /**
11
400
  * Create a CommandTrees adapter wrapping a Trees instance.
@@ -70,6 +459,7 @@ function wrapCommits(commits) {
70
459
  var GitCommand = class {
71
460
  _workingCopy;
72
461
  callable = true;
462
+ racyCheckInstalled = false;
73
463
  constructor(workingCopy) {
74
464
  this._workingCopy = workingCopy;
75
465
  }
@@ -116,6 +506,37 @@ var GitCommand = class {
116
506
  * Supports both new architecture (checkout.staging) and legacy/init (staging directly).
117
507
  */
118
508
  get staging() {
509
+ const staging = this.resolveStaging();
510
+ if (!this.racyCheckInstalled) {
511
+ this.racyCheckInstalled = true;
512
+ this.installRacyCheck(staging);
513
+ }
514
+ return staging;
515
+ }
516
+ /**
517
+ * Gives the staging git's racy-git smudging for its writes: an entry whose mtime second is
518
+ * not older than the index file and whose content changed behind a matching stat is
519
+ * written with size 0 (`ce_smudge_racily_clean_entry`), so a later same-size edit in that
520
+ * second is never taken as clean.
521
+ */
522
+ installRacyCheck(staging) {
523
+ const worktree = this._workingCopy.worktree;
524
+ if (!worktree || typeof staging.setRacyCheck !== "function") return;
525
+ const trust = worktreeModeTrust(this._workingCopy, worktree);
526
+ staging.setRacyCheck(async (entry, indexTime) => {
527
+ try {
528
+ const current = await worktree.getEntry(entry.path);
529
+ if (!current || current.isDirectory || !basicStatMatches(entry, current, trust)) return false;
530
+ return (await compareWithWorktree(worktree, entry, {
531
+ trust,
532
+ indexTime
533
+ })).smudge === true;
534
+ } catch {
535
+ return false;
536
+ }
537
+ });
538
+ }
539
+ resolveStaging() {
119
540
  if (this._workingCopy.checkout?.staging) return this._workingCopy.checkout.staging;
120
541
  const wcAny = this._workingCopy;
121
542
  if (wcAny.staging) return wcAny.staging;
@@ -277,7 +698,7 @@ var GitCommand = class {
277
698
  * - "**" matches across path separators
278
699
  * - Exact directory prefix matches (e.g., "src" matches "src/file.ts")
279
700
  */
280
- function matchesPattern(path, patterns) {
701
+ function matchesPattern$1(path, patterns) {
281
702
  for (const pattern of patterns) if (matchGlob(path, pattern)) return true;
282
703
  return false;
283
704
  }
@@ -470,7 +891,7 @@ var AddCommand = class extends GitCommand {
470
891
  const filesToProcess = [];
471
892
  for await (const entry of worktree.walk({ includeIgnored: true })) {
472
893
  if (entry.isDirectory) continue;
473
- if (!matchesPattern(entry.path, patterns)) continue;
894
+ if (!matchesPattern$1(entry.path, patterns)) continue;
474
895
  if (entry.isIgnored && !this.force) {
475
896
  skipped.push(entry.path);
476
897
  continue;
@@ -485,7 +906,7 @@ var AddCommand = class extends GitCommand {
485
906
  const indexedPaths = /* @__PURE__ */ new Set();
486
907
  for await (const entry of this.staging.entries()) if (entry.stage === 0) indexedPaths.add(entry.path);
487
908
  for (const indexPath of indexedPaths) {
488
- if (!matchesPattern(indexPath, patterns)) continue;
909
+ if (!matchesPattern$1(indexPath, patterns)) continue;
489
910
  if (!await worktree.getEntry(indexPath)) filesToProcess.push({
490
911
  path: indexPath,
491
912
  exists: false,
@@ -501,6 +922,7 @@ var AddCommand = class extends GitCommand {
501
922
  filesToProcess.push(...filtered);
502
923
  }
503
924
  const editor = this.staging.createEditor();
925
+ const trust = worktreeModeTrust(this.workingCopy, worktree);
504
926
  for (const file of filesToProcess) {
505
927
  if (!file.exists) {
506
928
  editor.add(new DeleteStagingEntry(file.path));
@@ -519,10 +941,9 @@ var AddCommand = class extends GitCommand {
519
941
  const worktreeEntry = await worktree.getEntry(file.path);
520
942
  if (!worktreeEntry) continue;
521
943
  const stored = await storeWorktreeFile(this.blobs, worktree, file.path, worktreeEntry);
522
- editor.add(new UpdateStagingEntry(file.path, stored.id, stored.entry.mode, {
523
- size: stored.entry.size,
524
- mtime: stored.entry.mtime
525
- }));
944
+ const indexMode = (await this.staging.getEntry(file.path))?.mode;
945
+ const mode = modeFromWorktree(stored.entry.mode, indexMode, trust);
946
+ editor.add(new UpdateStagingEntry(file.path, stored.id, mode, entryStatOf(stored.entry)));
526
947
  added.push(file.path);
527
948
  }
528
949
  await editor.finish();
@@ -1680,6 +2101,240 @@ var RenameBranchCommand = class extends GitCommand {
1680
2101
  }
1681
2102
  };
1682
2103
  //#endregion
2104
+ //#region src/commands/tree-restore.ts
2105
+ /**
2106
+ * Walk a tree and plan which files to restore, validating as it goes.
2107
+ *
2108
+ * Throws on anything that cannot be restored faithfully, so the caller can
2109
+ * abort before mutating the working tree: a path git's `verify_path` refuses
2110
+ * (`.git` under any spelling, a symlinked `.gitmodules`), and two entries that
2111
+ * collide - the same path twice, a file and a directory of one name, or a path
2112
+ * beneath a planned file, symlink or submodule (which would write through the
2113
+ * link), compared case-insensitively with `ignoreCase`.
2114
+ *
2115
+ * @param trees Tree storage to walk
2116
+ * @param blobs Blob storage, checked for the content of every planned file
2117
+ * @param treeId Tree to restore
2118
+ * @param operation Names the operation in failure messages, e.g. `reset --hard`
2119
+ * @param options What else the worktree can restore
2120
+ */
2121
+ async function planTreeRestore(trees, blobs, treeId, operation, options = {}) {
2122
+ const plan = {
2123
+ entries: [],
2124
+ paths: /* @__PURE__ */ new Set(),
2125
+ gitlinks: [],
2126
+ collided: []
2127
+ };
2128
+ await planInto(trees, blobs, treeId, "", operation, plan, options, /* @__PURE__ */ new Map());
2129
+ return plan;
2130
+ }
2131
+ /**
2132
+ * Records `path` as a tree or a leaf, refusing a path that collides with a planned one in
2133
+ * a way that would write through it; two leaves differing only in case are recorded in
2134
+ * `collided` instead (case-folding filesystems keep the last one).
2135
+ */
2136
+ function claim(planned, plan, path, kind, operation, options) {
2137
+ const key = options.ignoreCase ? path.toLowerCase() : path;
2138
+ const existing = planned.get(key);
2139
+ if (existing) {
2140
+ if (existing.path === path || existing.kind !== kind) throw new Error(`${operation} cannot restore ${path}: it collides with another entry`);
2141
+ if (kind === "leaf") {
2142
+ if (!plan.collided.includes(existing.path)) plan.collided.push(existing.path);
2143
+ plan.collided.push(path);
2144
+ }
2145
+ return;
2146
+ }
2147
+ const parts = key.split("/");
2148
+ for (let i = 1; i < parts.length; i++) if (planned.get(parts.slice(0, i).join("/"))?.kind === "leaf") throw new Error(`${operation} cannot restore ${path}: ${parts.slice(0, i).join("/")} is not a directory`);
2149
+ planned.set(key, {
2150
+ kind,
2151
+ path
2152
+ });
2153
+ }
2154
+ async function planInto(trees, blobs, treeId, prefix, operation, plan, options, planned) {
2155
+ for await (const entry of trees.loadTree(treeId)) {
2156
+ const path = prefix ? `${prefix}/${entry.name}` : entry.name;
2157
+ if (!isValidWorktreePath(path, entry.mode, { windows: options.windows === true }) || prefix === "" && options.reservedNames?.some((name) => entry.name.normalize("NFC").toLowerCase() === name.toLowerCase())) throw new Error(`${operation} cannot restore ${JSON.stringify(path)}: invalid path`);
2158
+ if (entry.mode === FileMode.TREE) {
2159
+ claim(planned, plan, path, "tree", operation, options);
2160
+ await planInto(trees, blobs, entry.id, path, operation, plan, options, planned);
2161
+ continue;
2162
+ }
2163
+ claim(planned, plan, path, "leaf", operation, options);
2164
+ if (entry.mode === FileMode.GITLINK) {
2165
+ plan.paths.add(path);
2166
+ plan.gitlinks.push({
2167
+ path,
2168
+ objectId: entry.id,
2169
+ mode: entry.mode
2170
+ });
2171
+ continue;
2172
+ }
2173
+ if (entry.mode === FileMode.SYMLINK && !options.symlinks) throw new Error(`${operation} cannot restore ${path}: the worktree cannot create symbolic links`);
2174
+ if ((!options.writing || options.writing.has(path)) && !await blobs.has(entry.id)) throw new Error(`${operation} cannot restore ${path}: blob ${entry.id} is missing`);
2175
+ plan.entries.push({
2176
+ path,
2177
+ objectId: entry.id,
2178
+ mode: entry.mode
2179
+ });
2180
+ plan.paths.add(path);
2181
+ }
2182
+ }
2183
+ /**
2184
+ * Execute a plan produced by {@link planTreeRestore}, writing every file.
2185
+ *
2186
+ * @param worktree Working tree to write into
2187
+ * @param blobs Blob storage to read content from
2188
+ * @param plan The validated plan
2189
+ * @param operation Names the operation in failure messages
2190
+ */
2191
+ async function writeTreeRestorePlan(worktree, blobs, plan, operation, options = {}) {
2192
+ const run = () => writePlan(worktree, blobs, plan, operation, options);
2193
+ await (worktree.batch ? worktree.batch(run) : run());
2194
+ }
2195
+ async function writePlan(worktree, blobs, plan, operation, options) {
2196
+ for (const { path, objectId, mode } of plan.entries) {
2197
+ const content = await blobs.load(objectId);
2198
+ if (!content) throw new Error(`${operation} cannot restore ${path}: blob ${objectId} is missing`);
2199
+ const written = mode === FileMode.SYMLINK && options.symlinks === false ? FileMode.REGULAR_FILE : mode;
2200
+ await worktree.writeContent(path, content, {
2201
+ mode: written,
2202
+ createParents: true,
2203
+ ...options.replaceInTheWay ? { replaceInTheWay: true } : {}
2204
+ });
2205
+ }
2206
+ if (options.gitlinks) for (const { path } of plan.gitlinks) await worktree.mkdir(path);
2207
+ }
2208
+ //#endregion
2209
+ //#region src/commands/worktree-overwrite-checks.ts
2210
+ /**
2211
+ * What a checkout or a stash apply must not overwrite, as git's unpack-trees checks it
2212
+ * before writing anything: local changes (`verify_uptodate`), untracked files on a path or
2213
+ * a leading component (`verify_absent`, `check_leading_path`), and untracked files in a
2214
+ * directory a file replaces (`verify_clean_subdirectory`).
2215
+ */
2216
+ /**
2217
+ * Whether the worktree file at `path` no longer holds the index entry (git's
2218
+ * `verify_uptodate`): changed content, type, or executable bit where the worktree shows it.
2219
+ * A missing file is no local change.
2220
+ */
2221
+ async function worktreeDiffers(worktree, path, entry, trust) {
2222
+ const current = await worktree.getEntry(path);
2223
+ if (!current) return false;
2224
+ if (current.isDirectory) return entry.mode !== FileMode.GITLINK;
2225
+ if (entry.mode === FileMode.GITLINK) return false;
2226
+ if (trust?.executable && entry.mode !== FileMode.SYMLINK && current.mode !== FileMode.SYMLINK && current.mode === FileMode.EXECUTABLE_FILE !== (entry.mode === FileMode.EXECUTABLE_FILE)) return true;
2227
+ if (entry.mtime && current.size === entry.size && current.mtime === entry.mtime && (entry.ctime === void 0 || current.ctime === void 0 || entry.ctime === current.ctime)) return false;
2228
+ if (current.mode === FileMode.SYMLINK !== (entry.mode === FileMode.SYMLINK)) {
2229
+ if (worktree.capabilities?.symlinks !== false) return true;
2230
+ }
2231
+ return await worktree.computeHash(path) !== entry.objectId;
2232
+ }
2233
+ /**
2234
+ * Finds what stands where `writes` (paths not in the index) are written, `removes` being
2235
+ * the tracked paths the operation deletes first. Ignored files are expendable, as in git.
2236
+ * With `ignoreCase`, a file that is one of `removes` in another case is no obstacle (a
2237
+ * case-only rename on a case-folding worktree).
2238
+ */
2239
+ async function findInTheWay(worktree, options) {
2240
+ const { writes, removes, index } = options;
2241
+ const untracked = /* @__PURE__ */ new Set();
2242
+ const lostDirs = [];
2243
+ const removingFolded = new Set([...removes].map((p) => p.toLowerCase()));
2244
+ const tracked = (p) => index.has(p) && !removes.has(p);
2245
+ const trackedDirs = /* @__PURE__ */ new Set();
2246
+ for (const p of index.keys()) {
2247
+ if (removes.has(p)) continue;
2248
+ for (let k = p.indexOf("/"); k > 0; k = p.indexOf("/", k + 1)) trackedDirs.add(p.slice(0, k));
2249
+ }
2250
+ for (const path of writes) {
2251
+ if (trackedDirs.has(path)) {
2252
+ lostDirs.push(path);
2253
+ continue;
2254
+ }
2255
+ if (index.has(path)) continue;
2256
+ const parts = path.split("/");
2257
+ let blocked = false;
2258
+ for (let k = 1; k < parts.length && !blocked; k++) {
2259
+ const prefix = parts.slice(0, k).join("/");
2260
+ const entry = await worktree.getEntry(prefix);
2261
+ if (!entry || entry.isDirectory || removes.has(prefix)) continue;
2262
+ if (!await worktree.isIgnored(prefix)) untracked.add(prefix);
2263
+ blocked = true;
2264
+ }
2265
+ if (blocked) continue;
2266
+ const entry = await worktree.getEntry(path);
2267
+ if (!entry) continue;
2268
+ if (entry.isDirectory) {
2269
+ for await (const inside of worktree.walk({ pathPrefix: path })) if (!tracked(inside.path) && !removes.has(inside.path)) {
2270
+ lostDirs.push(path);
2271
+ break;
2272
+ }
2273
+ continue;
2274
+ }
2275
+ if (options.ignoreCase && removingFolded.has(path.toLowerCase())) continue;
2276
+ if (!await worktree.isIgnored(path)) untracked.add(path);
2277
+ }
2278
+ return {
2279
+ untracked: [...untracked],
2280
+ lostDirs
2281
+ };
2282
+ }
2283
+ /**
2284
+ * Removes the directory at `dir` if it holds nothing at all, as git's `rmdir`: never a
2285
+ * directory with a file, link, subdirectory, nested repository (`.git`) or FIFO in it, and
2286
+ * never recursively. Returns whether it was removed.
2287
+ */
2288
+ async function removeDirectoryIfEmpty(worktree, dir) {
2289
+ if (worktree.removeEmptyDirectory) return worktree.removeEmptyDirectory(dir);
2290
+ if (!(await worktree.getEntry(dir))?.isDirectory) return false;
2291
+ const inside = worktree.walk({
2292
+ pathPrefix: dir,
2293
+ includeIgnored: true,
2294
+ includeDirectories: true
2295
+ });
2296
+ for await (const _ of inside) return false;
2297
+ if (await worktree.exists(`${dir}/.git`)) return false;
2298
+ return worktree.remove(dir);
2299
+ }
2300
+ /**
2301
+ * Removes the directories a removal left empty, bottom-up to the worktree root, as git's
2302
+ * `schedule_dir_for_removal`: each only if it is truly empty, stopping at the first that is
2303
+ * not (a nested repository, an ignored or untracked file, a FIFO keeps its directory).
2304
+ */
2305
+ async function pruneEmptyParents(worktree, path) {
2306
+ const parts = path.split("/");
2307
+ for (let k = parts.length - 1; k > 0; k--) if (!await removeDirectoryIfEmpty(worktree, parts.slice(0, k).join("/"))) return;
2308
+ }
2309
+ /** git's refusal messages (unpack-trees), for `checkout` or `merge` (stash apply). */
2310
+ function overwriteMessage(action, found) {
2311
+ const list = (paths) => paths.map((p) => `\t${p}`);
2312
+ const advice = action === "checkout" ? "Please commit your changes or stash them before you switch branches." : "Please commit your changes or stash them before you merge.";
2313
+ const move = action === "checkout" ? "Please move or remove them before you switch branches." : "Please move or remove them before you merge.";
2314
+ const parts = [];
2315
+ if (found.local?.length) parts.push([
2316
+ `error: Your local changes to the following files would be overwritten by ${action}:`,
2317
+ ...list(found.local),
2318
+ advice
2319
+ ].join("\n"));
2320
+ if (found.lostDirs?.length) parts.push([
2321
+ "error: Updating the following directories would lose untracked files in them:",
2322
+ ...list(found.lostDirs),
2323
+ ""
2324
+ ].join("\n"));
2325
+ if (found.untracked?.length) parts.push([
2326
+ `error: The following untracked working tree files would be overwritten by ${action}:`,
2327
+ ...list(found.untracked),
2328
+ move
2329
+ ].join("\n"));
2330
+ if (found.untrackedRemoved?.length) parts.push([
2331
+ `error: The following untracked working tree files would be removed by ${action}:`,
2332
+ ...list(found.untrackedRemoved),
2333
+ move
2334
+ ].join("\n"));
2335
+ return parts.length > 0 ? [...parts, "Aborting"].join("\n") : void 0;
2336
+ }
2337
+ //#endregion
1683
2338
  //#region src/commands/checkout-command.ts
1684
2339
  /**
1685
2340
  * CheckoutCommand - Switch branches or restore files.
@@ -1715,6 +2370,8 @@ var RenameBranchCommand = class extends GitCommand {
1715
2370
  * .call();
1716
2371
  * ```
1717
2372
  */
2373
+ /** Names a branch checkout in failure messages. */
2374
+ const CHECKOUT = "checkout";
1718
2375
  /**
1719
2376
  * Stage to check out for conflicting files.
1720
2377
  */
@@ -1743,6 +2400,7 @@ let CheckoutStatus = /* @__PURE__ */ function(CheckoutStatus) {
1743
2400
  CheckoutStatus["ERROR"] = "ERROR";
1744
2401
  return CheckoutStatus;
1745
2402
  }({});
2403
+ const sameSide = (a, b) => a === void 0 || b === void 0 ? a === b : a.objectId === b.objectId && a.mode === b.mode;
1746
2404
  /**
1747
2405
  * Command to checkout branches, commits, or paths.
1748
2406
  *
@@ -1899,8 +2557,9 @@ var CheckoutCommand = class extends GitCommand {
1899
2557
  async call() {
1900
2558
  this.checkCallable();
1901
2559
  this.setCallable(false);
1902
- if (this.allPaths || this.paths.length > 0) return this.checkoutPaths();
1903
- return this.checkoutBranch();
2560
+ const run = () => this.allPaths || this.paths.length > 0 ? this.checkoutPaths() : this.checkoutBranch();
2561
+ const worktree = this.worktreeAccess;
2562
+ return worktree?.batch ? worktree.batch(run) : run();
1904
2563
  }
1905
2564
  /**
1906
2565
  * Checkout paths from index or commit.
@@ -1929,30 +2588,10 @@ var CheckoutCommand = class extends GitCommand {
1929
2588
  ref: null
1930
2589
  };
1931
2590
  }
1932
- /**
1933
- * Detect conflicts between staged changes and checkout target.
1934
- *
1935
- * Returns list of paths that have uncommitted staged changes.
1936
- * Git prevents checkout when staged changes differ from HEAD,
1937
- * as they would be lost during checkout.
1938
- *
1939
- * @param _targetTreeId Target tree to checkout (unused for now, checks HEAD vs staging)
1940
- * @returns Array of conflicting paths
1941
- */
1942
- async detectCheckoutConflicts(_targetTreeId) {
1943
- const conflicts = [];
1944
- const headId = await this.resolveCommitId("HEAD");
1945
- if (!headId) return conflicts;
1946
- const headTreeId = await this.commits.getTree(headId);
1947
- if (!headTreeId) return conflicts;
1948
- const headEntries = /* @__PURE__ */ new Map();
1949
- await this.collectTreeEntries(headTreeId, "", headEntries);
1950
- for await (const entry of this.staging.entries()) {
1951
- if (entry.stage !== 0) continue;
1952
- const headEntry = headEntries.get(entry.path);
1953
- if (!headEntry || headEntry.objectId !== entry.objectId) conflicts.push(entry.path);
1954
- }
1955
- return conflicts;
2591
+ /** Whether an untracked (not ignored) file or link is at `path`. */
2592
+ async untrackedFileAt(worktree, path) {
2593
+ const entry = await worktree.getEntry(path);
2594
+ return !!entry && !entry.isDirectory && !await worktree.isIgnored(path);
1956
2595
  }
1957
2596
  /**
1958
2597
  * Checkout a branch or commit.
@@ -1968,65 +2607,154 @@ var CheckoutCommand = class extends GitCommand {
1968
2607
  const targetId = await this.resolveCommitId(this.name);
1969
2608
  if (!targetId && !this.orphan) throw new RefNotFoundError(this.name);
1970
2609
  const targetTreeId = targetId ? await this.commits.getTree(targetId) : void 0;
1971
- if (!this.force && !this.orphan) {
1972
- const conflicts = await this.detectCheckoutConflicts(targetTreeId);
1973
- if (conflicts.length > 0) return {
2610
+ const worktree = this.worktreeAccess;
2611
+ const headId = await this.resolveCommitId("HEAD");
2612
+ const headTreeId = headId ? await this.commits.getTree(headId) : void 0;
2613
+ const head = /* @__PURE__ */ new Map();
2614
+ const target = /* @__PURE__ */ new Map();
2615
+ if (headTreeId) await this.collectTreeEntries(headTreeId, "", head);
2616
+ if (targetTreeId) await this.collectTreeEntries(targetTreeId, "", target);
2617
+ const index = /* @__PURE__ */ new Map();
2618
+ const unmerged = /* @__PURE__ */ new Set();
2619
+ for await (const entry of this.staging.entries()) if (entry.stage === 0) index.set(entry.path, entry);
2620
+ else unmerged.add(entry.path);
2621
+ if (!this.force && !this.orphan && unmerged.size > 0) return {
2622
+ status: "CONFLICTS",
2623
+ updated: [],
2624
+ removed: [],
2625
+ conflicts: [...unmerged].sort(),
2626
+ ref: null,
2627
+ message: "error: you need to resolve your current index first"
2628
+ };
2629
+ const switched = [];
2630
+ const local = [];
2631
+ const untracked = [];
2632
+ const untrackedRemoved = [];
2633
+ const lostDirs = [];
2634
+ const trust = worktree ? worktreeModeTrust(this.workingCopy, worktree) : void 0;
2635
+ const ignoreCase = coreBool(this.workingCopy, "ignorecase", false);
2636
+ const paths = [.../* @__PURE__ */ new Set([...head.keys(), ...target.keys()])].sort();
2637
+ for (const path of this.orphan ? [] : paths) {
2638
+ const h = head.get(path);
2639
+ const t = target.get(path);
2640
+ if (!this.force && sameSide(h, t)) continue;
2641
+ const i = index.get(path);
2642
+ if (this.force) {
2643
+ if (!sameSide(i, t) || t) switched.push(path);
2644
+ continue;
2645
+ }
2646
+ if (sameSide(i, t)) {
2647
+ if (h && !i && !t && worktree && await this.untrackedFileAt(worktree, path)) untrackedRemoved.push(path);
2648
+ continue;
2649
+ }
2650
+ if (!sameSide(i, h)) {
2651
+ if (i !== void 0 || t !== void 0) local.push(path);
2652
+ continue;
2653
+ }
2654
+ if (i !== void 0 && worktree && await worktreeDiffers(worktree, path, i, trust)) {
2655
+ local.push(path);
2656
+ continue;
2657
+ }
2658
+ switched.push(path);
2659
+ }
2660
+ if (worktree && !this.force) {
2661
+ const found = await findInTheWay(worktree, {
2662
+ writes: switched.filter((p) => target.has(p)),
2663
+ removes: new Set(switched.filter((p) => !target.has(p))),
2664
+ index,
2665
+ ignoreCase
2666
+ });
2667
+ untracked.push(...found.untracked);
2668
+ lostDirs.push(...found.lostDirs);
2669
+ }
2670
+ if (local.length + untracked.length + untrackedRemoved.length + lostDirs.length > 0) {
2671
+ const message = overwriteMessage("checkout", {
2672
+ local,
2673
+ lostDirs,
2674
+ untracked,
2675
+ untrackedRemoved
2676
+ });
2677
+ return {
1974
2678
  status: "CONFLICTS",
1975
2679
  updated: [],
1976
2680
  removed: [],
1977
- conflicts,
1978
- ref: null
2681
+ conflicts: [
2682
+ ...local,
2683
+ ...lostDirs,
2684
+ ...untracked,
2685
+ ...untrackedRemoved
2686
+ ],
2687
+ ref: null,
2688
+ message
2689
+ };
2690
+ }
2691
+ const updated = [];
2692
+ const removed = [];
2693
+ const switching = new Set(switched);
2694
+ if (targetTreeId && worktree) {
2695
+ const plan = await planTreeRestore(this.trees, this.blobs, targetTreeId, CHECKOUT, {
2696
+ symlinks: true,
2697
+ ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
2698
+ windows: worktree.capabilities?.windowsPaths === true,
2699
+ reservedNames: worktree.capabilities?.reservedNames
2700
+ });
2701
+ for (const path of switched) {
2702
+ if (target.has(path)) continue;
2703
+ await worktree.remove(path);
2704
+ await pruneEmptyParents(worktree, path);
2705
+ removed.push(path);
2706
+ }
2707
+ if (this.force) {
2708
+ for (const path of index.keys()) if (!target.has(path) && !switching.has(path)) {
2709
+ await worktree.remove(path);
2710
+ removed.push(path);
2711
+ }
2712
+ }
2713
+ const only = {
2714
+ ...plan,
2715
+ entries: plan.entries.filter((e) => switching.has(e.path)),
2716
+ gitlinks: plan.gitlinks.filter((e) => switching.has(e.path))
1979
2717
  };
2718
+ await writeTreeRestorePlan(worktree, this.blobs, only, CHECKOUT, {
2719
+ symlinks: worktreeModeTrust(this.workingCopy, worktree).symlinks,
2720
+ gitlinks: true,
2721
+ replaceInTheWay: true
2722
+ });
2723
+ updated.push(...only.entries.map((e) => e.path));
1980
2724
  }
1981
2725
  const isLocalBranch = await this.refsStore.has(`refs/heads/${this.name}`);
1982
2726
  if (this.orphan) await this.refsStore.setSymbolic("HEAD", `refs/heads/${this.name}`);
1983
2727
  else if (isLocalBranch) await this.refsStore.setSymbolic("HEAD", `refs/heads/${this.name}`);
1984
2728
  else if (targetId) await this.refsStore.set("HEAD", targetId);
1985
- const updated = [];
1986
- const removed = [];
1987
- if (targetTreeId) {
2729
+ if (targetTreeId && this.force) {
1988
2730
  await this.staging.readTree(this.trees, targetTreeId);
1989
2731
  await this.staging.write();
1990
- if (this.hasFileWriteSupport()) await this.writeTreeToWorkdir(targetTreeId, "");
2732
+ } else if (switched.length > 0) {
2733
+ const editor = this.staging.createEditor();
2734
+ for (const path of switched) {
2735
+ const t = target.get(path);
2736
+ if (!t) {
2737
+ editor.remove(path);
2738
+ continue;
2739
+ }
2740
+ const stats = worktree ? await worktree.getEntry(path) : void 0;
2741
+ editor.upsert({
2742
+ path,
2743
+ objectId: t.objectId,
2744
+ mode: t.mode,
2745
+ ...entryStatOf(stats ?? {})
2746
+ });
2747
+ }
2748
+ await editor.finish();
2749
+ await this.staging.write();
1991
2750
  }
1992
2751
  return {
1993
2752
  status: "OK",
1994
2753
  updated,
1995
2754
  removed,
1996
- conflicts: [],
1997
- ref: await this.refsStore.resolve("HEAD") ?? null
1998
- };
1999
- }
2000
- /**
2001
- * Check if the store supports file writes (not a bare repository).
2002
- *
2003
- * A repository is considered "bare" if it doesn't have a worktree interface.
2004
- */
2005
- hasFileWriteSupport() {
2006
- return !!this.worktreeAccess;
2007
- }
2008
- /**
2009
- * Write all files from a tree to the working directory.
2010
- *
2011
- * @param treeId The tree ID to checkout
2012
- * @param basePath The base path prefix for entries in this tree
2013
- */
2014
- async writeTreeToWorkdir(treeId, basePath) {
2015
- const worktree = this.worktreeAccess;
2016
- if (!worktree) throw new Error("Worktree not available for file writes");
2017
- for await (const entry of this.trees.loadTree(treeId)) {
2018
- const relativePath = basePath ? `${basePath}/${entry.name}` : entry.name;
2019
- if (entry.mode === FileMode.TREE) await this.writeTreeToWorkdir(entry.id, relativePath);
2020
- else {
2021
- const lastSlash = relativePath.lastIndexOf("/");
2022
- if (lastSlash > 0) {
2023
- const parentDir = relativePath.substring(0, lastSlash);
2024
- await worktree.mkdir(parentDir);
2025
- }
2026
- const blobContent = await this.blobs.load(entry.id);
2027
- await worktree.writeContent(relativePath, blobContent ?? []);
2028
- }
2029
- }
2755
+ conflicts: [],
2756
+ ref: await this.refsStore.resolve("HEAD") ?? null
2757
+ };
2030
2758
  }
2031
2759
  /**
2032
2760
  * Checkout a path from the staging index.
@@ -2532,6 +3260,7 @@ var CleanCommand = class extends GitCommand {
2532
3260
  dryRun = true;
2533
3261
  directories = false;
2534
3262
  ignore = true;
3263
+ forceNested = false;
2535
3264
  /**
2536
3265
  * Limit clean to specific paths.
2537
3266
  *
@@ -2556,7 +3285,8 @@ var CleanCommand = class extends GitCommand {
2556
3285
  return this;
2557
3286
  }
2558
3287
  /**
2559
- * Set whether to also clean directories.
3288
+ * Set whether to also clean untracked directories (`git clean -d`): their untracked
3289
+ * files are removed and each directory once it is empty.
2560
3290
  *
2561
3291
  * @param directories Whether to clean directories
2562
3292
  */
@@ -2579,69 +3309,178 @@ var CleanCommand = class extends GitCommand {
2579
3309
  return this;
2580
3310
  }
2581
3311
  /**
2582
- * Execute the clean command.
3312
+ * Set whether nested repositories (untracked directories with their own `.git`) are
3313
+ * removed too, as `git clean -ff`. Off by default: they are skipped, as `git clean -f`
3314
+ * skips them, and listed in `skipped`.
3315
+ *
3316
+ * @param force Whether to remove nested repositories
3317
+ */
3318
+ setForceNestedRepositories(force) {
3319
+ this.checkCallable();
3320
+ this.forceNested = force;
3321
+ return this;
3322
+ }
3323
+ /**
3324
+ * Execute the clean command, as `git clean -f` (`-d` with `setCleanDirectories(true)`,
3325
+ * `-x` with `setIgnore(false)`, `-ff` with `setForceNestedRepositories(true)`, `-n` with
3326
+ * dry run):
3327
+ * - only files the index does not track are removed, one at a time;
3328
+ * - an untracked directory (one holding no tracked or staged path) is entered only with
3329
+ * `-d` or a path filter; with `-d` it is removed once empty, deepest first and never
3330
+ * recursively, so whatever stays in it (an ignored file without `-x`, a nested
3331
+ * repository without `-ff`) keeps it;
3332
+ * - `cleaned` lists what `git clean -n` prints after "Would remove": a wholly removed
3333
+ * untracked directory as `dir/`, else the files; `skipped` the nested repositories
3334
+ * ("Would skip repository").
2583
3335
  *
2584
3336
  * @returns CleanResult with set of cleaned files
2585
3337
  */
2586
3338
  async call() {
2587
3339
  this.checkCallable();
2588
3340
  this.setCallable(false);
2589
- const cleaned = /* @__PURE__ */ new Set();
2590
- const toRemove = [];
2591
3341
  const worktree = this.worktreeAccess;
2592
3342
  if (!worktree) throw new Error("CleanCommand requires a WorkingCopy with worktree");
2593
- const stagedPaths = /* @__PURE__ */ new Set();
2594
- for await (const entry of this.staging.entries()) stagedPaths.add(entry.path);
2595
- const headPaths = /* @__PURE__ */ new Set();
2596
- try {
2597
- const head = await this.refsStore.resolve("HEAD");
2598
- if (head?.objectId) {
2599
- const commit = await this.commits.load(head.objectId);
2600
- if (commit) await this.collectTreePaths(commit.tree, "", headPaths);
3343
+ return worktree.batch ? worktree.batch(() => this.clean(worktree)) : this.clean(worktree);
3344
+ }
3345
+ /**
3346
+ * Whether `path` is or lies in one of the requested paths, as git's pathspec matches it: a
3347
+ * plain path matches itself and what is below it; one with `*`, `?` or `[...]` is a glob
3348
+ * over the whole path (`*` matching `/` too).
3349
+ */
3350
+ matchesPaths(path, isDirectory = false) {
3351
+ if (this.paths.size === 0) return true;
3352
+ for (const p of this.paths) {
3353
+ const spec = p.replace(/\/+$/, "");
3354
+ if (spec === "" || spec === ".") return true;
3355
+ if (/[*?[]/.test(spec)) {
3356
+ const glob = globToRegExp(spec);
3357
+ if (glob.test(path) || isDirectory && glob.test(`${path}/`)) return true;
3358
+ continue;
2601
3359
  }
2602
- } catch {}
2603
- const options = {
2604
- includeIgnored: !this.ignore,
2605
- includeDirectories: this.directories
3360
+ if (path === spec || path.startsWith(`${spec}/`)) return true;
3361
+ }
3362
+ return false;
3363
+ }
3364
+ /** Whether a requested path names `path` itself. */
3365
+ namesPath(path) {
3366
+ for (const p of this.paths) {
3367
+ const spec = p.replace(/\/+$/, "");
3368
+ if (spec === path || /[*?[]/.test(spec) && globToRegExp(spec).test(path)) return true;
3369
+ }
3370
+ return false;
3371
+ }
3372
+ async clean(worktree) {
3373
+ const tracked = /* @__PURE__ */ new Set();
3374
+ for await (const entry of this.staging.entries()) tracked.add(entry.path);
3375
+ const trackedDirs = directoriesOf(tracked);
3376
+ const removeIgnored = !this.ignore;
3377
+ const enterUntracked = this.directories || this.paths.size > 0;
3378
+ const ancestors = (path) => {
3379
+ const parts = path.split("/");
3380
+ const out = [];
3381
+ for (let k = 1; k < parts.length; k++) out.push(parts.slice(0, k).join("/"));
3382
+ return out;
2606
3383
  };
2607
- for await (const entry of worktree.walk(options)) {
2608
- const entryTyped = entry;
2609
- if (this.paths.size > 0) {
2610
- let matches = false;
2611
- for (const p of this.paths) if (entryTyped.path === p || entryTyped.path.startsWith(`${p}/`)) {
2612
- matches = true;
2613
- break;
3384
+ const holdsKept = async (dir) => {
3385
+ if (removeIgnored) return false;
3386
+ for await (const inside of worktree.walk({
3387
+ pathPrefix: dir,
3388
+ includeIgnored: true
3389
+ })) if (inside.isIgnored) return true;
3390
+ return false;
3391
+ };
3392
+ const removeFiles = [];
3393
+ const removeRepos = [];
3394
+ const untrackedDirs = [];
3395
+ const notEntered = /* @__PURE__ */ new Set();
3396
+ const skipped = /* @__PURE__ */ new Set();
3397
+ const kept = /* @__PURE__ */ new Set();
3398
+ const keep = (path, isDirectory = false) => {
3399
+ for (const dir of ancestors(path)) kept.add(dir);
3400
+ if (isDirectory) kept.add(path);
3401
+ };
3402
+ for await (const entry of worktree.walk({
3403
+ includeIgnored: true,
3404
+ includeDirectories: true
3405
+ })) {
3406
+ const path = entry.path;
3407
+ if (ancestors(path).some((dir) => notEntered.has(dir))) continue;
3408
+ const keptAsIgnored = entry.isIgnored && !removeIgnored;
3409
+ if (entry.isDirectory) {
3410
+ if (trackedDirs.has(path)) continue;
3411
+ if (tracked.has(path) || !enterUntracked) {
3412
+ notEntered.add(path);
3413
+ continue;
3414
+ }
3415
+ if (entry.mode === FileMode.GITLINK) {
3416
+ notEntered.add(path);
3417
+ if (worktree.isRepository && !await worktree.isRepository(path)) {
3418
+ if (keptAsIgnored || !this.matchesPaths(path) || await holdsKept(path)) keep(path, true);
3419
+ else removeRepos.push(path);
3420
+ continue;
3421
+ }
3422
+ if (keptAsIgnored || !this.matchesPaths(path)) keep(path, true);
3423
+ else if (!this.forceNested) {
3424
+ if (ancestors(path).some((dir) => !trackedDirs.has(dir)) && !this.namesPath(path)) skipped.add(path);
3425
+ keep(path, true);
3426
+ } else removeRepos.push(path);
3427
+ continue;
2614
3428
  }
2615
- if (!matches) continue;
3429
+ untrackedDirs.push(path);
3430
+ if (keptAsIgnored) keep(path, true);
3431
+ continue;
3432
+ }
3433
+ if (tracked.has(path)) continue;
3434
+ if (keptAsIgnored || !this.matchesPaths(path) || !isValidWorktreePath(path)) {
3435
+ keep(path);
3436
+ continue;
3437
+ }
3438
+ removeFiles.push(path);
3439
+ }
3440
+ const dirMode = this.directories || this.paths.size > 0;
3441
+ const removedDir = (dir) => dirMode && !trackedDirs.has(dir) && !kept.has(dir) && this.matchesPaths(dir, true);
3442
+ const reportFor = (path, suffix = "") => {
3443
+ for (const dir of ancestors(path)) if (removedDir(dir)) return `${dir}/`;
3444
+ return `${path}${suffix}`;
3445
+ };
3446
+ const cleaned = /* @__PURE__ */ new Set();
3447
+ for (const path of removeFiles) cleaned.add(reportFor(path));
3448
+ for (const path of removeRepos) cleaned.add(reportFor(path, "/"));
3449
+ for (const dir of untrackedDirs) if (removedDir(dir)) cleaned.add(reportFor(dir, "/"));
3450
+ if (!this.dryRun) {
3451
+ for (const path of removeFiles) await worktree.remove(path);
3452
+ for (const path of removeRepos) await worktree.remove(path, { recursive: true });
3453
+ if (dirMode) {
3454
+ const deepestFirst = [...untrackedDirs].sort((a, b) => b.split("/").length - a.split("/").length || (a < b ? 1 : -1));
3455
+ for (const dir of deepestFirst) if (this.matchesPaths(dir, true)) await removeDirectoryIfEmpty(worktree, dir);
2616
3456
  }
2617
- if (this.ignore && entryTyped.isIgnored) continue;
2618
- if (stagedPaths.has(entryTyped.path) || headPaths.has(entryTyped.path)) continue;
2619
- if (entryTyped.isDirectory && !this.directories) continue;
2620
- if (!isValidWorktreePath(entryTyped.path)) continue;
2621
- const displayPath = entryTyped.isDirectory ? `${entryTyped.path}/` : entryTyped.path;
2622
- cleaned.add(displayPath);
2623
- if (!this.dryRun) toRemove.push({
2624
- path: entryTyped.path,
2625
- isDirectory: entryTyped.isDirectory
2626
- });
2627
3457
  }
2628
- for (const { path, isDirectory } of toRemove) await worktree.remove(path, { recursive: isDirectory });
2629
3458
  return {
2630
3459
  cleaned,
3460
+ skipped,
2631
3461
  dryRun: this.dryRun
2632
3462
  };
2633
3463
  }
2634
- /**
2635
- * Collect all paths from a tree recursively.
2636
- */
2637
- async collectTreePaths(treeId, prefix, paths) {
2638
- for await (const entry of this.trees.loadTree(treeId)) {
2639
- const fullPath = prefix ? `${prefix}/${entry.name}` : entry.name;
2640
- if ((entry.mode & 61440) === 16384) await this.collectTreePaths(entry.id, fullPath, paths);
2641
- else paths.add(fullPath);
2642
- }
2643
- }
2644
3464
  };
3465
+ /** A pathspec glob as a regular expression over the whole path (`*` matches `/` too). */
3466
+ function globToRegExp(glob) {
3467
+ let out = "";
3468
+ for (let i = 0; i < glob.length; i++) {
3469
+ const c = glob[i];
3470
+ if (c === "*") out += ".*";
3471
+ else if (c === "?") out += "[^/]";
3472
+ else if (c === "[") {
3473
+ const end = glob.indexOf("]", i + 1);
3474
+ if (end < 0) out += "\\[";
3475
+ else {
3476
+ const body = glob.slice(i + 1, end).replace(/^!/, "^").replace(/\\/g, "\\\\");
3477
+ out += `[${body}]`;
3478
+ i = end;
3479
+ }
3480
+ } else out += c.replace(/[.+^${}()|\\/]/g, "\\$&");
3481
+ }
3482
+ return new RegExp(`^${out}$`);
3483
+ }
2645
3484
  //#endregion
2646
3485
  //#region src/transport-command.ts
2647
3486
  /**
@@ -2659,6 +3498,8 @@ var TransportCommand = class extends GitCommand {
2659
3498
  timeout;
2660
3499
  /** Custom HTTP headers */
2661
3500
  headers;
3501
+ /** Gzip large fetch request bodies (undefined: the transport's default, true) */
3502
+ gzipRequests;
2662
3503
  /** Progress callback */
2663
3504
  progressCallback;
2664
3505
  /** Progress message callback */
@@ -2698,6 +3539,18 @@ var TransportCommand = class extends GitCommand {
2698
3539
  return this;
2699
3540
  }
2700
3541
  /**
3542
+ * Send large upload-pack request bodies (a fetch's have-batches over 1024 bytes) gzipped,
3543
+ * with `Content-Encoding: gzip`, as git does (default true). Pass false for a browser behind
3544
+ * a CORS proxy that does not allow that header (it is not CORS-safelisted).
3545
+ *
3546
+ * @param gzip Whether to gzip large request bodies
3547
+ */
3548
+ setGzipRequests(gzip) {
3549
+ this.checkCallable();
3550
+ this.gzipRequests = gzip;
3551
+ return this;
3552
+ }
3553
+ /**
2701
3554
  * Set custom HTTP headers.
2702
3555
  *
2703
3556
  * @param headers Custom headers
@@ -2727,227 +3580,20 @@ var TransportCommand = class extends GitCommand {
2727
3580
  this.progressMessageCallback = callback;
2728
3581
  return this;
2729
3582
  }
2730
- /**
2731
- * Get transport options for passing to transport operations.
2732
- */
2733
- getTransportOptions() {
2734
- return {
2735
- auth: this.credentials,
2736
- headers: this.headers,
2737
- timeout: this.timeout,
2738
- onProgress: this.progressCallback,
2739
- onProgressMessage: this.progressMessageCallback
2740
- };
2741
- }
2742
- };
2743
- //#endregion
2744
- //#region src/remote-config/remote-config-store.ts
2745
- /** The default fetch refspec `git remote add` writes for a remote. */
2746
- function defaultFetchRefspec(name) {
2747
- return `+refs/heads/*:refs/remotes/${name}/*`;
2748
- }
2749
- const GIT_CONFIG_METHODS = [
2750
- "get",
2751
- "getAll",
2752
- "set",
2753
- "add",
2754
- "unset",
2755
- "unsetSection",
2756
- "subsections"
2757
- ];
2758
- function isGitConfigLike(config) {
2759
- if (!config) return false;
2760
- return GIT_CONFIG_METHODS.every((method) => typeof config[method] === "function");
2761
- }
2762
- /**
2763
- * Split `remote.<subsection>.<name>` into its subsection.
2764
- *
2765
- * Follows git's key grammar (and `GitWorkingCopyConfig`'s): the first part is
2766
- * the section, the last is the variable name and everything in between is the
2767
- * subsection, which keeps its case and may itself contain dots.
2768
- *
2769
- * @returns undefined when the key is not a `remote` subsection key
2770
- */
2771
- function remoteSubsectionOf(key) {
2772
- const parts = key.split(".");
2773
- if (parts.length < 3 || parts[0].toLowerCase() !== "remote") return void 0;
2774
- return parts.slice(1, -1).join(".");
2775
- }
2776
- /**
2777
- * {@link GitConfigLike} over a plain `{[key: string]: unknown}` bag.
2778
- *
2779
- * Keys are stored in canonical dotted form (`remote.origin.url`) — the same
2780
- * form `GitWorkingCopyConfig` mirrors as own properties — so the two
2781
- * representations read alike. A repeated key holds an array.
2782
- *
2783
- * There is no `save()`: this config lives and dies with the working copy
2784
- * instance, which is exactly what a working copy without a config file has.
2785
- */
2786
- var PlainObjectConfig = class {
2787
- bag;
2788
- constructor(bag) {
2789
- this.bag = bag;
2790
- }
2791
- get(key) {
2792
- const values = this.getAll(key);
2793
- return values.length > 0 ? values[values.length - 1] : void 0;
2794
- }
2795
- getAll(key) {
2796
- const value = this.bag[key];
2797
- if (value === void 0) return [];
2798
- return Array.isArray(value) ? [...value] : [value];
2799
- }
2800
- set(key, value) {
2801
- this.bag[key] = value;
2802
- }
2803
- add(key, value) {
2804
- const existing = this.getAll(key);
2805
- this.bag[key] = existing.length > 0 ? [...existing, value] : value;
2806
- }
2807
- unset(key) {
2808
- delete this.bag[key];
2809
- }
2810
- unsetSection(section) {
2811
- const parts = section.split(".");
2812
- if (parts.length < 2 || parts[0].toLowerCase() !== "remote") return;
2813
- const subsection = parts.slice(1).join(".");
2814
- for (const key of Object.keys(this.bag)) if (remoteSubsectionOf(key) === subsection) delete this.bag[key];
2815
- }
2816
- subsections(section) {
2817
- if (section.toLowerCase() !== "remote") return [];
2818
- const found = /* @__PURE__ */ new Set();
2819
- for (const key of Object.keys(this.bag)) {
2820
- if (this.getAll(key).length === 0) continue;
2821
- const subsection = remoteSubsectionOf(key);
2822
- if (subsection !== void 0) found.add(subsection);
2823
- }
2824
- return [...found];
2825
- }
2826
- };
2827
- /**
2828
- * The `[remote "<name>"]` sections of a working copy's configuration.
2829
- *
2830
- * Reading a remote is a **union** of two sources, and stays that way: the
2831
- * config sections, plus every name that appears under `refs/remotes/`. A
2832
- * remote that was fetched into tracking refs without ever being configured is
2833
- * a real remote to `git remote`, and so it is here — it simply has no URL.
2834
- */
2835
- var RemoteConfigStore = class RemoteConfigStore {
2836
- config;
2837
- constructor(config) {
2838
- this.config = config;
2839
- }
2840
- /**
2841
- * Wrap a working copy's configuration.
2842
- *
2843
- * A config that implements the git-config methods is used directly, so
2844
- * changes reach its backing file; anything else is driven as a plain bag.
2845
- */
2846
- static from(workingCopy) {
2847
- const config = workingCopy.config;
2848
- if (isGitConfigLike(config)) return new RemoteConfigStore(config);
2849
- return new RemoteConfigStore(new PlainObjectConfig(config ?? {}));
2850
- }
2851
- /** Remote names that have a config section. */
2852
- configuredNames() {
2853
- return this.config.subsections("remote");
2854
- }
2855
- /** Whether the remote has a config section. */
2856
- isConfigured(name) {
2857
- return this.configuredNames().includes(name);
2858
- }
2859
- /**
2860
- * Read a remote, filling in the default fetch refspec when none is
2861
- * configured, exactly as `git remote` reports one.
2862
- */
2863
- read(name) {
2864
- const fetchRefspecs = this.strings(name, "fetch");
2865
- return {
2866
- name,
2867
- urls: this.strings(name, "url"),
2868
- pushUrls: this.strings(name, "pushurl"),
2869
- fetchRefspecs: fetchRefspecs.length > 0 ? fetchRefspecs : [defaultFetchRefspec(name)],
2870
- pushRefspecs: this.strings(name, "push")
2871
- };
2872
- }
2873
- /** Write every field of a remote, replacing whatever was there. */
2874
- write(remote) {
2875
- this.setAll(remote.name, "url", remote.urls);
2876
- this.setAll(remote.name, "fetch", remote.fetchRefspecs);
2877
- this.setAll(remote.name, "pushurl", remote.pushUrls);
2878
- this.setAll(remote.name, "push", remote.pushRefspecs);
2879
- }
2880
- /** Drop the whole `[remote "<name>"]` section. */
2881
- remove(name) {
2882
- this.config.unsetSection(`remote.${name}`);
2883
- }
2884
- /**
2885
- * Point a remote at a URL.
2886
- *
2887
- * @param push Write `pushurl` instead of `url`
2888
- * @param oldUrl Replace only this URL, as `git remote set-url <name> <new> <old>` does
2889
- * @throws InvalidArgumentError if `oldUrl` is not among the configured URLs
2890
- */
2891
- setUrl(name, url, options = {}) {
2892
- const variable = options.push ? "pushurl" : "url";
2893
- if (options.oldUrl === void 0) {
2894
- this.setAll(name, variable, [url]);
2895
- return;
2896
- }
2897
- const existing = this.strings(name, variable);
2898
- if (!existing.includes(options.oldUrl)) throw new InvalidArgumentError("oldUri", `No such URL found: ${options.oldUrl}`);
2899
- this.setAll(name, variable, existing.map((value) => value === options.oldUrl ? url : value));
2900
- }
2901
- /**
2902
- * The URL to talk to a remote over, or undefined when it has none.
2903
- *
2904
- * @param push Prefer `pushurl`, falling back to `url`, as git does
2905
- */
2906
- urlFor(name, options = {}) {
2907
- if (options.push) {
2908
- const pushUrl = this.strings(name, "pushurl")[0];
2909
- if (pushUrl !== void 0) return pushUrl;
2910
- }
2911
- return this.strings(name, "url")[0];
2912
- }
2913
- /** A config variable (`push.default`, `branch.main.merge`), the last value when repeated. */
2914
- value(key) {
2915
- const value = this.config.get(key);
2916
- return value === void 0 || value === null ? void 0 : String(value);
2917
- }
2918
- /** Sets a config variable, replacing every value it had. */
2919
- setValue(key, value) {
2920
- this.config.set(key, value);
2921
- }
2922
- /** Flush to the backing file, if the config has one. */
2923
- async save() {
2924
- await this.config.save?.();
2925
- }
2926
- strings(name, variable) {
2927
- return this.config.getAll(`remote.${name}.${variable}`).filter((value) => value !== void 0 && value !== null).map((value) => String(value));
2928
- }
2929
- setAll(name, variable, values) {
2930
- const key = `remote.${name}.${variable}`;
2931
- if (values.length === 0) {
2932
- this.config.unset(key);
2933
- return;
2934
- }
2935
- this.config.set(key, values[0]);
2936
- for (const value of values.slice(1)) this.config.add(key, value);
2937
- }
2938
- };
2939
- /**
2940
- * Every remote name known to the repository: config sections ∪ the names
2941
- * appearing under `refs/remotes/`.
2942
- */
2943
- async function listRemoteNames(store, refs) {
2944
- const names = new Set(store.configuredNames());
2945
- for await (const ref of refs.list("refs/remotes/")) {
2946
- const parts = ref.name.split("/");
2947
- if (parts.length >= 3) names.add(parts[2]);
3583
+ /**
3584
+ * Get transport options for passing to transport operations.
3585
+ */
3586
+ getTransportOptions() {
3587
+ return {
3588
+ auth: this.credentials,
3589
+ headers: this.headers,
3590
+ timeout: this.timeout,
3591
+ gzipRequests: this.gzipRequests,
3592
+ onProgress: this.progressCallback,
3593
+ onProgressMessage: this.progressMessageCallback
3594
+ };
2948
3595
  }
2949
- return [...names];
2950
- }
3596
+ };
2951
3597
  //#endregion
2952
3598
  //#region src/commands/fetch-command.ts
2953
3599
  /**
@@ -3000,8 +3646,13 @@ let TagOption = /* @__PURE__ */ function(TagOption) {
3000
3646
  var FetchCommand = class extends TransportCommand {
3001
3647
  remote = "origin";
3002
3648
  refSpecs = [];
3003
- removeDeletedRefs = false;
3649
+ removeDeletedRefs;
3650
+ pruneTags;
3651
+ refmap;
3004
3652
  tagOption = "auto-follow";
3653
+ tagOptionSet = false;
3654
+ writeFetchHead = true;
3655
+ appendFetchHead = false;
3005
3656
  thin = true;
3006
3657
  depth;
3007
3658
  dryRun = false;
@@ -3055,7 +3706,11 @@ var FetchCommand = class extends TransportCommand {
3055
3706
  /**
3056
3707
  * Set whether to remove refs that no longer exist on the remote.
3057
3708
  *
3058
- * Equivalent to `git fetch --prune`.
3709
+ * Equivalent to `git fetch --prune` (true) and `--no-prune` (false). Unset, the
3710
+ * remote's `remote.<name>.prune`, else `fetch.prune`, decides, as in git; neither set,
3711
+ * nothing is pruned. The remote-tracking refs the refspecs map from a ref the remote no
3712
+ * longer has are deleted before anything is fetched (so `foo` can become `foo/bar`); the
3713
+ * command-line refspecs are used when given, else the configured ones.
3059
3714
  *
3060
3715
  * @param remove Whether to prune deleted refs
3061
3716
  */
@@ -3065,16 +3720,80 @@ var FetchCommand = class extends TransportCommand {
3065
3720
  return this;
3066
3721
  }
3067
3722
  /**
3068
- * Whether to remove deleted refs.
3723
+ * Whether to remove deleted refs, as set with {@link setRemoveDeletedRefs} (false when
3724
+ * unset: the configuration is read when the fetch runs).
3069
3725
  */
3070
3726
  isRemoveDeletedRefs() {
3071
- return this.removeDeletedRefs;
3727
+ return this.removeDeletedRefs ?? false;
3728
+ }
3729
+ /**
3730
+ * Set whether local tags the remote no longer has are pruned too (`git fetch
3731
+ * --prune-tags` / `--no-prune-tags`). Unset, `remote.<name>.pruneTags`, else
3732
+ * `fetch.pruneTags`, decides.
3733
+ *
3734
+ * As in git, this adds `refs/tags/*:refs/tags/*` to the refspecs (so every remote tag is
3735
+ * fetched), and only when no refspec is given: to the remote's configured refspecs, or for
3736
+ * a URL to the refspecs of the fetch. Tags are pruned only when pruning is on.
3737
+ */
3738
+ setPruneTags(pruneTags) {
3739
+ this.checkCallable();
3740
+ this.pruneTags = pruneTags;
3741
+ return this;
3742
+ }
3743
+ /**
3744
+ * Set the refspecs that map the refs named on the command line to remote-tracking refs
3745
+ * (`git fetch --refmap=<refspec>`), in place of the remote's `remote.<name>.fetch`.
3746
+ *
3747
+ * With explicit refspecs ({@link setRefSpecs}), git also updates the remote-tracking
3748
+ * ref each fetched ref maps to through the configured refspecs (`git fetch origin main`
3749
+ * moves `refs/remotes/origin/main`); a refmap replaces those, and an empty one
3750
+ * (`setRefmap()`, git's `--refmap=`) turns the update off. Without explicit refspecs a
3751
+ * refmap is an error, as in git.
3752
+ */
3753
+ setRefmap(...refspecs) {
3754
+ this.checkCallable();
3755
+ this.refmap = refspecs;
3756
+ return this;
3072
3757
  }
3758
+ /**
3759
+ * Set how tags are fetched (`--tags`, `--no-tags`, or auto-follow).
3760
+ *
3761
+ * Unset, a configured remote's `remote.<name>.tagOpt` (`--tags`, `--no-tags`) decides, as
3762
+ * in git; otherwise tags are auto-followed.
3763
+ */
3073
3764
  setTagOpt(option) {
3074
3765
  this.checkCallable();
3075
3766
  this.tagOption = option;
3767
+ this.tagOptionSet = true;
3768
+ return this;
3769
+ }
3770
+ /**
3771
+ * Set whether the fetch writes `FETCH_HEAD` (default true; `--no-write-fetch-head`).
3772
+ *
3773
+ * Written through the checkout's `writeFetchHead`; a checkout without it keeps none.
3774
+ */
3775
+ setWriteFetchHead(write) {
3776
+ this.checkCallable();
3777
+ this.writeFetchHead = write;
3778
+ return this;
3779
+ }
3780
+ /** Whether the fetch writes `FETCH_HEAD`. */
3781
+ isWriteFetchHead() {
3782
+ return this.writeFetchHead;
3783
+ }
3784
+ /**
3785
+ * Set whether the fetched refs are added after what `FETCH_HEAD` holds instead of
3786
+ * replacing it (`git fetch --append`).
3787
+ */
3788
+ setAppend(append) {
3789
+ this.checkCallable();
3790
+ this.appendFetchHead = append;
3076
3791
  return this;
3077
3792
  }
3793
+ /** Whether `FETCH_HEAD` is appended to. */
3794
+ isAppend() {
3795
+ return this.appendFetchHead;
3796
+ }
3078
3797
  /**
3079
3798
  * Set thin-pack preference.
3080
3799
  *
@@ -3250,20 +3969,50 @@ var FetchCommand = class extends TransportCommand {
3250
3969
  this.setCallable(false);
3251
3970
  const remoteUrl = await this.resolveRemoteUrl(this.remote);
3252
3971
  if (!remoteUrl) throw new InvalidRemoteError(this.remote);
3253
- const fromConfig = this.refSpecs.length === 0;
3254
- const configured = this.effectiveRefSpecs();
3255
- const refspecs = configured.length > 0 ? configured : ["HEAD"];
3972
+ const store = RemoteConfigStore.from(this.workingCopy);
3973
+ const viaConfig = store.isConfigured(this.remote);
3974
+ const prune = this.removeDeletedRefs ?? configBool(store.value(`remote.${this.remote}.prune`)) ?? configBool(store.value("fetch.prune")) ?? false;
3975
+ const pruneTags = this.pruneTags ?? configBool(store.value(`remote.${this.remote}.pruneTags`)) ?? configBool(store.value("fetch.pruneTags")) ?? false;
3976
+ const configured = viaConfig ? store.configuredFetchRefspecs(this.remote) : [];
3977
+ const explicitSpecs = [...this.refSpecs];
3978
+ if (pruneTags && this.refSpecs.length === 0) {
3979
+ if (viaConfig) configured.push(TAG_REFSPEC);
3980
+ else explicitSpecs.push(TAG_REFSPEC);
3981
+ }
3982
+ const fromConfig = explicitSpecs.length === 0;
3983
+ if (fromConfig && this.refmap !== void 0) throw new InvalidArgumentError("refmap", this.refmap, "--refmap option is only meaningful with command-line refspec(s)");
3984
+ const upstream = fromConfig ? await this.upstreamConfig() : void 0;
3985
+ const upstreamHere = upstream?.remote === this.remote;
3986
+ const useConfig = fromConfig && (configured.length > 0 || upstreamHere);
3987
+ const given = !fromConfig ? explicitSpecs : useConfig ? configured : ["HEAD"];
3988
+ const mergeRefs = useConfig && upstream && upstreamHere ? upstream.merge : [];
3989
+ const refspecs = [...given, ...mergeRefs];
3256
3990
  const history = this._workingCopy.history;
3991
+ const opportunistic = fromConfig ? [] : (this.refmap ?? configured).filter((spec) => spec !== "");
3992
+ const followHead = fromConfig && configured.length > 0 ? this.followRemoteHead(store) : null;
3993
+ const messages = [];
3994
+ const errors = [];
3995
+ const trackingUpdates = [];
3996
+ const checkout = this._workingCopy.checkout;
3997
+ const writesFetchHead = !this.dryRun && this.writeFetchHead && !!checkout?.writeFetchHead;
3998
+ if (writesFetchHead && !this.appendFetchHead) await checkout.writeFetchHead?.("");
3257
3999
  const result = await fetch({
3258
4000
  url: remoteUrl,
3259
4001
  auth: this.credentials,
3260
4002
  headers: this.headers,
3261
4003
  timeout: this.timeout,
4004
+ gzipRequests: this.gzipRequests,
3262
4005
  repository: createRepositoryFacade({ history }),
3263
4006
  refStore: createTransportRefStore(history.refs),
3264
4007
  refspecs,
3265
- missingRefsOk: fromConfig && configured.length > 0,
3266
- tags: toTagMode(this.tagOption),
4008
+ opportunisticRefspecs: opportunistic.length > 0 ? opportunistic : void 0,
4009
+ beforeFetch: prune ? async (remoteRefs) => {
4010
+ const names = new Set(remoteRefs.filter((r) => r.oid).map((r) => r.name));
4011
+ const pruneSpecs = (fromConfig ? configured : explicitSpecs).map((s) => parseRefSpec(s));
4012
+ trackingUpdates.push(...await this.pruneDeletedRefs(names, pruneSpecs, messages, errors));
4013
+ } : void 0,
4014
+ missingRefsOk: useConfig,
4015
+ tags: toTagMode(this.effectiveTagOption()),
3267
4016
  depth: this.depth,
3268
4017
  deepenSince: this.shallowSince,
3269
4018
  deepenNot: this.shallowExcludes.length > 0 ? this.shallowExcludes : void 0,
@@ -3275,11 +4024,20 @@ var FetchCommand = class extends TransportCommand {
3275
4024
  });
3276
4025
  const advertisedRefs = /* @__PURE__ */ new Map();
3277
4026
  for (const ref of result.remoteRefs) if (ref.oid) advertisedRefs.set(ref.name, ref.oid);
3278
- const trackingUpdates = result.refUpdates.map(toTrackingRefUpdate);
3279
- if (!this.dryRun && this.removeDeletedRefs) {
3280
- const parsed = refspecs.map((s) => parseRefSpec(s));
3281
- trackingUpdates.push(...await this.pruneDeletedRefs(new Set(advertisedRefs.keys()), parsed));
4027
+ trackingUpdates.push(...result.refUpdates.map(toTrackingRefUpdate));
4028
+ if (writesFetchHead && checkout?.writeFetchHead) {
4029
+ const entries = await this.fetchHeadEntries(result, {
4030
+ given: given.length,
4031
+ merge: mergeRefs,
4032
+ explicit: !useConfig,
4033
+ firstIsExact: given.length > 0 && !parseRefSpec(given[0]).wildcard,
4034
+ hasMerge: upstream !== void 0
4035
+ });
4036
+ await checkout.writeFetchHead(formatFetchHead(entries, remoteUrl), { append: true });
3282
4037
  }
4038
+ if (followHead) try {
4039
+ await this.setRemoteHead(result.remoteRefs, followHead, store, messages);
4040
+ } catch {}
3283
4041
  return {
3284
4042
  uri: remoteUrl,
3285
4043
  advertisedRefs,
@@ -3287,21 +4045,152 @@ var FetchCommand = class extends TransportCommand {
3287
4045
  defaultBranch: result.defaultBranch,
3288
4046
  bytesReceived: result.packBytes,
3289
4047
  isEmpty: result.isEmpty,
3290
- messages: []
4048
+ messages,
4049
+ ...errors.length > 0 ? { errors } : {}
3291
4050
  };
3292
4051
  }
3293
4052
  /**
3294
- * The refspecs this fetch runs with.
3295
- *
3296
- * Explicit refspecs win; otherwise a configured remote contributes its
3297
- * `remote.<name>.fetch` lines, which is what makes `fetch().setRemote("origin")`
3298
- * update tracking refs without being told how. A remote given as a bare URL
3299
- * has no config and so still needs its refspecs spelled out.
4053
+ * How `refs/remotes/<name>/HEAD` follows the remote HEAD (git 2.48+): the remote's
4054
+ * `remote.<name>.followRemoteHEAD`, else `fetch.followRemoteHEAD`, else `create`; an
4055
+ * unrecognized value is ignored, as git warns and ignores it. Null for `never`.
4056
+ */
4057
+ followRemoteHead(store) {
4058
+ const mode = parseFollowRemoteHead(store.value(`remote.${this.remote}.followRemoteHEAD`), true) ?? parseFollowRemoteHead(store.value("fetch.followRemoteHEAD"), false) ?? { mode: "create" };
4059
+ return mode.mode === "never" ? null : mode;
4060
+ }
4061
+ /**
4062
+ * git's set_head (fetch.c): the one branch the remote HEAD names (its symref, or else the
4063
+ * only branch at its commit) becomes `refs/remotes/<name>/HEAD`, if that tracking ref
4064
+ * exists here: created when missing (`create`, `warn`), or always set (`always`). In a
4065
+ * bare repository mirroring the remote (`remote.<name>.mirror`), HEAD itself is set to
4066
+ * the branch. `warn` reports a local HEAD that differs, in git's words, into `messages`.
4067
+ * As in git, failures are silent and a dry run is no exception.
4068
+ */
4069
+ async setRemoteHead(remoteRefs, follow, store, messages) {
4070
+ const head = remoteRefs.find((r) => r.name === "HEAD");
4071
+ if (!head) return;
4072
+ const branches = remoteRefs.filter((r) => r.oid && r.name.startsWith("refs/heads/"));
4073
+ const heads = head.symref ? branches.filter((r) => r.name === head.symref) : branches.filter((r) => r.oid === head.oid);
4074
+ if (heads.length !== 1) return;
4075
+ const headName = heads[0].name.slice(11);
4076
+ const remote = this.remote;
4077
+ const baremirror = configBool(store.value("core.bare")) === true && configBool(store.value(`remote.${remote}.mirror`)) === true;
4078
+ const createOnly = follow.mode === "always" ? false : !baremirror;
4079
+ const name = baremirror ? "HEAD" : `refs/remotes/${remote}/HEAD`;
4080
+ const target = baremirror ? `refs/heads/${headName}` : `refs/remotes/${remote}/${headName}`;
4081
+ if (!baremirror && !(await this.refsStore.resolve(target))?.objectId) return;
4082
+ const previous = await this.refsStore.get(name);
4083
+ if (!createOnly || !previous) await this.refsStore.setSymbolic(name, target);
4084
+ if (follow.mode !== "warn" || follow.noWarnBranch === headName || !previous) return;
4085
+ const prefix = `refs/remotes/${remote}/`;
4086
+ let warning;
4087
+ if (isSymbolicRef(previous)) {
4088
+ const was = previous.target.startsWith(prefix) ? previous.target.slice(prefix.length) : "";
4089
+ if (was && was !== headName) warning = `'HEAD' at '${remote}' is '${headName}', but we have '${was}' locally.`;
4090
+ } else warning = `'HEAD' at '${remote}' is '${headName}', but we have a detached HEAD pointing to '${previous.objectId}' locally.`;
4091
+ if (!warning) return;
4092
+ messages.push(warning);
4093
+ if (configBool(store.value("advice.fetchRemoteHEADWarn")) === false) return;
4094
+ const advice = [
4095
+ `Run 'git remote set-head ${remote} ${headName}' to follow the change, or modify`,
4096
+ `either of the 'remote.${remote}.followRemoteHEAD' or 'fetch.followRemoteHEAD'`,
4097
+ "configuration variables to handle the situation differently.",
4098
+ "",
4099
+ "Using this specific setting",
4100
+ "",
4101
+ ` git config set remote.${remote}.followRemoteHEAD warn-if-not-${headName}`,
4102
+ "",
4103
+ "will suppress the warning until the remote changes HEAD to something else.",
4104
+ "Disable this message with \"git config set advice.fetchRemoteHEADWarn false\""
4105
+ ];
4106
+ messages.push(...advice.map((line) => line ? `hint: ${line}` : "hint:"));
4107
+ }
4108
+ /** The tag option given, else the remote's `remote.<name>.tagOpt`, else auto-follow. */
4109
+ effectiveTagOption() {
4110
+ if (this.tagOptionSet) return this.tagOption;
4111
+ const tagOpt = RemoteConfigStore.from(this.workingCopy).value(`remote.${this.remote}.tagOpt`);
4112
+ if (tagOpt === "--no-tags") return "no-tags";
4113
+ if (tagOpt === "--tags") return "fetch-tags";
4114
+ return this.tagOption;
4115
+ }
4116
+ /**
4117
+ * The current branch's upstream: its `branch.<name>.remote` and `branch.<name>.merge`
4118
+ * refs, when both are set (git's branch_has_merge_config); undefined on a detached HEAD
4119
+ * or without upstream configuration.
3300
4120
  */
3301
- effectiveRefSpecs() {
3302
- if (this.refSpecs.length > 0) return this.refSpecs;
4121
+ async upstreamConfig() {
4122
+ const head = await this.refsStore.get("HEAD");
4123
+ if (!head || !isSymbolicRef(head) || !head.target.startsWith("refs/heads/")) return void 0;
4124
+ const branch = head.target.slice(11);
3303
4125
  const store = RemoteConfigStore.from(this.workingCopy);
3304
- return store.isConfigured(this.remote) ? store.read(this.remote).fetchRefspecs : [];
4126
+ const remote = store.value(`branch.${branch}.remote`);
4127
+ const merge = store.values(`branch.${branch}.merge`);
4128
+ return remote !== void 0 && merge.length > 0 ? {
4129
+ remote,
4130
+ merge
4131
+ } : void 0;
4132
+ }
4133
+ /**
4134
+ * The `FETCH_HEAD` lines of a fetch, marked as git's get_ref_map marks them: refs from
4135
+ * explicit refspecs (or the HEAD of an unconfigured remote) are to merge; with configured
4136
+ * refspecs, the refs the current branch's `branch.<name>.merge` names (fetched for this
4137
+ * alone when no refspec took them), or else the first ref when the first refspec names
4138
+ * one ref. Tags (`--tags`, auto-follow), the rest, and anything that does not peel to a
4139
+ * commit are `not-for-merge`.
4140
+ */
4141
+ async fetchHeadEntries(result, marks) {
4142
+ const mergeSpec = (index) => index !== void 0 && index >= marks.given && index < marks.given + marks.merge.length ? index - marks.given : void 0;
4143
+ const entries = [];
4144
+ for (const fetched of result.fetched) {
4145
+ if (mergeSpec(fetched.refspec) !== void 0) continue;
4146
+ const fromGiven = fetched.refspec !== void 0 && fetched.refspec < marks.given;
4147
+ entries.push({
4148
+ oid: fetched.oid,
4149
+ remoteRef: fetched.remoteRef,
4150
+ notForMerge: !(marks.explicit && fromGiven),
4151
+ refspec: fetched.refspec
4152
+ });
4153
+ }
4154
+ if (!marks.explicit) {
4155
+ if (!marks.hasMerge && marks.firstIsExact && entries[0]?.refspec === 0) entries[0].notForMerge = false;
4156
+ const matched = /* @__PURE__ */ new Set();
4157
+ for (const [k, ref] of marks.merge.entries()) {
4158
+ const match = entries.find((e) => e.refspec !== void 0 && e.refspec < marks.given && refNameMatches(ref, e.remoteRef));
4159
+ if (match) {
4160
+ match.notForMerge = false;
4161
+ matched.add(k);
4162
+ }
4163
+ }
4164
+ const extra = [];
4165
+ for (const fetched of result.fetched) {
4166
+ const k = mergeSpec(fetched.refspec);
4167
+ if (k === void 0 || matched.has(k)) continue;
4168
+ extra.push({
4169
+ oid: fetched.oid,
4170
+ remoteRef: fetched.remoteRef,
4171
+ notForMerge: false
4172
+ });
4173
+ }
4174
+ const tagsAt = entries.findIndex((e) => e.refspec === void 0 || e.refspec >= marks.given);
4175
+ entries.splice(tagsAt < 0 ? entries.length : tagsAt, 0, ...extra);
4176
+ }
4177
+ for (const entry of entries) if (!entry.notForMerge && !await this.peelsToCommit(entry.oid)) entry.notForMerge = true;
4178
+ return entries.map(({ oid, remoteRef, notForMerge }) => ({
4179
+ oid,
4180
+ remoteRef,
4181
+ notForMerge
4182
+ }));
4183
+ }
4184
+ /** Whether `id` is a commit, or a tag (chain) of one (git's lookup_commit_reference_gently). */
4185
+ async peelsToCommit(id) {
4186
+ const history = this._workingCopy.history;
4187
+ let current = id;
4188
+ for (let i = 0; current && i < 16; i++) {
4189
+ if (await history.commits.has(current)) return true;
4190
+ if (!await history.tags.has(current)) return false;
4191
+ current = await history.tags.getTarget(current);
4192
+ }
4193
+ return false;
3305
4194
  }
3306
4195
  /**
3307
4196
  * Resolve remote name to URL.
@@ -3315,42 +4204,69 @@ var FetchCommand = class extends TransportCommand {
3315
4204
  return RemoteConfigStore.from(this.workingCopy).urlFor(remote) ?? remote;
3316
4205
  }
3317
4206
  /**
3318
- * Prune local refs that a refspec maps from a remote ref that no longer exists (git's
3319
- * `--prune`): for each refspec with a destination, the local refs matching the
3320
- * destination whose source is not among the remote refs are deleted, unless a negative
3321
- * refspec excludes that source (git's query_matches_negative_refspec).
4207
+ * The stale remote-tracking refs (git's get_stale_heads): every local ref that the
4208
+ * refspecs map from remote refs (all of the matching refspecs: overlapping ones count
4209
+ * together), none of which the remote has, unless a negative refspec excludes it or it is
4210
+ * a symbolic ref. They are deleted (reflogs too) in one batch, logged `fetch: prune`, and
4211
+ * reported as deleted; a dry run reports them only. The symbolic refs left dangling are
4212
+ * named in `messages` as git does. A refused delete does not stop the fetch: as in git
4213
+ * (which then exits 1), the error goes into `errors` and nothing is reported deleted.
3322
4214
  */
3323
- async pruneDeletedRefs(remoteRefNames, specs) {
3324
- const updates = [];
3325
- const done = /* @__PURE__ */ new Set();
4215
+ async pruneDeletedRefs(remoteRefNames, specs, messages, errors) {
3326
4216
  const negative = specs.filter((s) => s.negative && s.source);
3327
- for (const spec of specs) {
3328
- if (spec.negative || !spec.source || !spec.destination) continue;
3329
- const prefix = spec.wildcard ? spec.destination.slice(0, spec.destination.indexOf("*")) : spec.destination;
3330
- for await (const ref of this.refsStore.list(prefix)) {
3331
- if (isSymbolicRef(ref) || done.has(ref.name)) continue;
3332
- let source;
3333
- if (spec.wildcard) {
3334
- if (!matchDestination(spec, ref.name)) continue;
3335
- source = expandFromDestination(spec, ref.name).source;
3336
- } else {
3337
- if (ref.name !== spec.destination) continue;
3338
- source = spec.source;
3339
- }
3340
- if (!source || remoteRefNames.has(source)) continue;
3341
- if (negative.some((n) => matchSource(n, source))) continue;
3342
- done.add(ref.name);
3343
- await this.refsStore.delete(ref.name);
3344
- updates.push({
3345
- localRef: ref.name,
3346
- remoteRef: source,
3347
- oldObjectId: ref.objectId,
3348
- newObjectId: "",
3349
- status: "deleted"
3350
- });
4217
+ const mapping = specs.filter((s) => !s.negative && s.source && s.destination);
4218
+ const stale = [];
4219
+ for await (const ref of this.refsStore.list("refs/")) {
4220
+ const sources = [];
4221
+ for (const spec of mapping) if (spec.wildcard) {
4222
+ if (!matchDestination(spec, ref.name)) continue;
4223
+ const source = expandFromDestination(spec, ref.name).source;
4224
+ if (source) sources.push(source);
4225
+ } else if (ref.name === spec.destination && spec.source) sources.push(spec.source);
4226
+ if (sources.length === 0 || isSymbolicRef(ref) || !ref.objectId) continue;
4227
+ if (sources.some((src) => negative.some((n) => matchSource(n, src)))) continue;
4228
+ if (sources.some((src) => remoteRefNames.has(src))) continue;
4229
+ stale.push({
4230
+ name: ref.name,
4231
+ objectId: ref.objectId,
4232
+ source: sources[0]
4233
+ });
4234
+ }
4235
+ if (stale.length === 0) return [];
4236
+ const dangling = await this.danglingSymrefs(new Set(stale.map((r) => r.name)));
4237
+ if (!this.dryRun) try {
4238
+ await deleteRefs(this.refsStore, stale.map((r) => r.name), "fetch: prune");
4239
+ } catch (error) {
4240
+ errors.push(error instanceof Error ? error.message : String(error));
4241
+ return [];
4242
+ }
4243
+ for (const { name, target } of dangling) messages.push(this.dryRun ? ` ${name} will become dangling after ${target} is deleted` : ` ${name} has become dangling after ${target} was deleted`);
4244
+ return stale.map((ref) => ({
4245
+ localRef: ref.name,
4246
+ remoteRef: ref.source,
4247
+ oldObjectId: ref.objectId,
4248
+ newObjectId: "",
4249
+ status: "deleted",
4250
+ summary: "[deleted]"
4251
+ }));
4252
+ }
4253
+ /** The symbolic refs whose chain ends at one of `names` (git's warn_if_dangling_symref). */
4254
+ async danglingSymrefs(names) {
4255
+ const found = [];
4256
+ for await (const ref of this.refsStore.list("refs/")) {
4257
+ if (!isSymbolicRef(ref)) continue;
4258
+ let target = ref.target;
4259
+ for (let i = 0; i < 5; i++) {
4260
+ const next = await this.refsStore.get(target);
4261
+ if (!next || !isSymbolicRef(next)) break;
4262
+ target = next.target;
3351
4263
  }
4264
+ if (names.has(target)) found.push({
4265
+ name: ref.name,
4266
+ target
4267
+ });
3352
4268
  }
3353
- return updates;
4269
+ return found.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
3354
4270
  }
3355
4271
  };
3356
4272
  /** The transport's tag mode for a {@link TagOption}. */
@@ -3374,8 +4290,41 @@ function toTrackingRefUpdate(update) {
3374
4290
  reason: update.reason
3375
4291
  };
3376
4292
  }
4293
+ /** git's TAG_REFSPEC, which `--prune-tags` adds. */
4294
+ const TAG_REFSPEC = "refs/tags/*:refs/tags/*";
4295
+ /**
4296
+ * A `followRemoteHEAD` value; undefined when unset or unrecognized. `warn-if-not-<branch>`
4297
+ * is read from `remote.<name>.followRemoteHEAD` only, as git's remote.c does.
4298
+ */
4299
+ function parseFollowRemoteHead(value, perRemote) {
4300
+ if (value === "never" || value === "create" || value === "warn" || value === "always") return { mode: value };
4301
+ if (perRemote && value?.startsWith("warn-if-not-")) return {
4302
+ mode: "warn",
4303
+ noWarnBranch: value.slice(12)
4304
+ };
4305
+ }
4306
+ /** A git boolean config value; undefined when unset or not a boolean. */
4307
+ function configBool(value) {
4308
+ if (value === void 0) return void 0;
4309
+ const v = value.trim().toLowerCase();
4310
+ if (v === "true" || v === "yes" || v === "on" || v === "1") return true;
4311
+ if (v === "false" || v === "no" || v === "off" || v === "0" || v === "") return false;
4312
+ }
4313
+ /** git's refname_match: `ref` (`main`, `heads/main`, `refs/heads/main`) names `fullName`. */
4314
+ function refNameMatches(ref, fullName) {
4315
+ return [
4316
+ ref,
4317
+ `refs/${ref}`,
4318
+ `refs/tags/${ref}`,
4319
+ `refs/heads/${ref}`,
4320
+ `refs/remotes/${ref}`,
4321
+ `refs/remotes/${ref}/HEAD`
4322
+ ].includes(fullName);
4323
+ }
3377
4324
  //#endregion
3378
4325
  //#region src/commands/clone-command.ts
4326
+ /** Names the clone's checkout in failure messages. */
4327
+ const CLONE = "clone";
3379
4328
  /**
3380
4329
  * Clone a remote repository.
3381
4330
  *
@@ -3387,6 +4336,25 @@ function toTrackingRefUpdate(update) {
3387
4336
  * rather than operating on an existing one. The store passed to the
3388
4337
  * constructor should be an empty/new store that will be populated.
3389
4338
  *
4339
+ * Like `git clone`, it configures the remote (`remote.<name>.url`, the
4340
+ * `remote.<name>.fetch` refspec of the clone, `remote.<name>.tagOpt` for
4341
+ * `--no-tags`, `remote.<name>.mirror`), the upstream of the checked-out branch
4342
+ * (`branch.<name>.remote` / `branch.<name>.merge`), and points
4343
+ * `refs/remotes/<name>/HEAD` at the remote's default branch.
4344
+ *
4345
+ * A non-bare clone checks out the commit HEAD names, as `git clone` does: the files
4346
+ * of its tree are written to the worktree (executable bits and symbolic links where
4347
+ * the worktree can represent them, see `Worktree.capabilities`; an empty directory
4348
+ * for each submodule) and the index records them with their stat data. When the
4349
+ * worktree cannot represent executables or symlinks, `core.filemode` or
4350
+ * `core.symlinks` is set to false, as `git init` does after probing the filesystem.
4351
+ * `setNoCheckout(true)` writes neither files nor index; a bare clone has neither.
4352
+ *
4353
+ * As in git, the checkout comes last, once the refs and the configuration are written:
4354
+ * when it fails (a tree path git's `verify_path` refuses, entries that collide, a file
4355
+ * in the way) the clone throws a `CloneCheckoutError` ("Clone succeeded, but checkout
4356
+ * failed") carrying the clone's result, and the repository stays usable.
4357
+ *
3390
4358
  * @example
3391
4359
  * ```typescript
3392
4360
  * // Basic clone
@@ -3422,6 +4390,7 @@ var CloneCommand = class extends TransportCommand {
3422
4390
  remoteName = "origin";
3423
4391
  cloneAllBranches = true;
3424
4392
  mirror = false;
4393
+ singleBranch;
3425
4394
  branchesToClone = [];
3426
4395
  tagOption = "auto-follow";
3427
4396
  shallowSince;
@@ -3443,10 +4412,11 @@ var CloneCommand = class extends TransportCommand {
3443
4412
  return this.uri;
3444
4413
  }
3445
4414
  /**
3446
- * Set the branch to clone.
4415
+ * Set the branch to check out (`git clone --branch`).
3447
4416
  *
3448
- * If set, only this branch will be fetched.
3449
- * Otherwise, all branches are fetched.
4417
+ * The branch, or else a tag of that name (checked out as a detached HEAD), instead
4418
+ * of the remote's default branch. All branches are still fetched unless
4419
+ * {@link setSingleBranch} (or a shallow clone) restricts the clone to this one.
3450
4420
  *
3451
4421
  * @param branch Branch name (e.g., "main" or "refs/heads/main")
3452
4422
  */
@@ -3489,7 +4459,8 @@ var CloneCommand = class extends TransportCommand {
3489
4459
  return this.bare;
3490
4460
  }
3491
4461
  /**
3492
- * Set whether to skip checkout.
4462
+ * Set whether to skip checkout (`git clone --no-checkout`): HEAD and the branch are
4463
+ * set up, but no file is written and the index is left empty.
3493
4464
  *
3494
4465
  * @param noCheckout Whether to skip checkout
3495
4466
  */
@@ -3523,6 +4494,24 @@ var CloneCommand = class extends TransportCommand {
3523
4494
  return this.remoteName;
3524
4495
  }
3525
4496
  /**
4497
+ * Clone only one branch (`git clone --single-branch`): the {@link setBranch} branch or
4498
+ * tag, else the remote's default branch. The remote's fetch refspec is configured for
4499
+ * that branch alone, and tags are auto-followed instead of all fetched.
4500
+ *
4501
+ * Unset, a shallow clone (`setDepth`, `setShallowSince`, `addShallowExclude`) is
4502
+ * single-branch, as in git, and so is a clone restricted by
4503
+ * {@link setBranchesToClone}; `setSingleBranch(false)` clones all branches anyway.
4504
+ */
4505
+ setSingleBranch(singleBranch) {
4506
+ this.checkCallable();
4507
+ this.singleBranch = singleBranch;
4508
+ return this;
4509
+ }
4510
+ /** Whether `--single-branch` was set (undefined: decided by the other options). */
4511
+ isSingleBranch() {
4512
+ return this.singleBranch;
4513
+ }
4514
+ /**
3526
4515
  * Set whether to clone all branches.
3527
4516
  *
3528
4517
  * Default is true. If set to false and no branch is specified,
@@ -3658,14 +4647,29 @@ var CloneCommand = class extends TransportCommand {
3658
4647
  this.checkCallable();
3659
4648
  this.setCallable(false);
3660
4649
  if (!this.uri) throw new InvalidRemoteError("", "URI must be specified for clone");
3661
- const branchToClone = toBranchName(this.determineBranchToClone());
4650
+ const branchesToClone = this.mirror || this.cloneAllBranches ? [] : this.branchesToClone;
4651
+ const branchToClone = toBranchName(this.branch ?? branchesToClone[0]);
3662
4652
  const history = this._workingCopy.history;
3663
4653
  const tracking = (branch) => this.bare ? `refs/heads/${branch}` : `refs/remotes/${this.remoteName}/${branch}`;
3664
- const singleBranch = !this.mirror && (branchToClone !== void 0 || this.depth !== void 0 || this.shallowSince !== void 0 || this.shallowExcludes.length > 0);
4654
+ const singleBranch = !this.mirror && (this.singleBranch ?? (branchesToClone.length > 0 || this.depth !== void 0 || this.shallowSince !== void 0 || this.shallowExcludes.length > 0));
3665
4655
  let detachedTag;
3666
4656
  let refspecs;
3667
4657
  if (this.mirror) refspecs = ["+refs/*:refs/*"];
3668
- else if (branchToClone !== void 0) {
4658
+ else if (branchToClone !== void 0 && !singleBranch) {
4659
+ const b = branchToClone;
4660
+ refspecs = {
4661
+ prefixes: ["refs/heads/", `refs/tags/${b}`],
4662
+ resolve: (remoteRefs) => {
4663
+ const all = [`+refs/heads/*:${tracking("*")}`];
4664
+ if (remoteRefs.some((r) => r.name === `refs/heads/${b}` && r.oid)) return all;
4665
+ if (this.tagOption !== "no-tags" && remoteRefs.some((r) => r.name === `refs/tags/${b}` && r.oid)) {
4666
+ detachedTag = `refs/tags/${b}`;
4667
+ return all;
4668
+ }
4669
+ throw new RefNotFoundError(`refs/heads/${b}`, `Remote branch ${b} not found in upstream ${this.remoteName}`);
4670
+ }
4671
+ };
4672
+ } else if (branchToClone !== void 0) {
3669
4673
  const b = branchToClone;
3670
4674
  refspecs = {
3671
4675
  prefixes: [`refs/heads/${b}`, `refs/tags/${b}`],
@@ -3693,6 +4697,7 @@ var CloneCommand = class extends TransportCommand {
3693
4697
  auth: this.credentials,
3694
4698
  headers: this.headers,
3695
4699
  timeout: this.timeout,
4700
+ gzipRequests: this.gzipRequests,
3696
4701
  repository: createRepositoryFacade({ history }),
3697
4702
  refStore: createTransportRefStore(history.refs),
3698
4703
  refspecs,
@@ -3707,6 +4712,9 @@ var CloneCommand = class extends TransportCommand {
3707
4712
  const advertisedDefaultBranch = result.defaultBranch;
3708
4713
  let defaultBranch = branchToClone ?? toBranchName(advertisedDefaultBranch);
3709
4714
  let headCommit;
4715
+ let checkedOutBranch;
4716
+ let checkoutId;
4717
+ if (!detachedTag && !this.bare && defaultBranch === void 0 && result.isEmpty) defaultBranch = await this.localHeadBranch() ?? "main";
3710
4718
  if (detachedTag) {
3711
4719
  defaultBranch = toBranchName(advertisedDefaultBranch);
3712
4720
  let id = (await this.refsStore.resolve(detachedTag))?.objectId;
@@ -3718,7 +4726,7 @@ var CloneCommand = class extends TransportCommand {
3718
4726
  if (id) {
3719
4727
  await this.refsStore.set("HEAD", id);
3720
4728
  headCommit = id;
3721
- if (!this.bare && !this.noCheckout) await this.checkoutHead(id);
4729
+ if (!this.bare && !this.noCheckout) checkoutId = id;
3722
4730
  }
3723
4731
  } else if (defaultBranch && !this.bare) {
3724
4732
  const localRef = `refs/heads/${defaultBranch}`;
@@ -3726,18 +4734,32 @@ var CloneCommand = class extends TransportCommand {
3726
4734
  if (tip?.objectId) {
3727
4735
  await this.refsStore.set(localRef, tip.objectId);
3728
4736
  headCommit = tip.objectId;
3729
- if (!this.noCheckout) await this.checkoutHead(tip.objectId);
4737
+ if (!this.noCheckout) checkoutId = tip.objectId;
3730
4738
  }
3731
4739
  await this.refsStore.setSymbolic("HEAD", localRef);
4740
+ if (tip?.objectId || result.isEmpty) checkedOutBranch = defaultBranch;
3732
4741
  } else if (this.bare || this.mirror) {
3733
4742
  if (defaultBranch) {
3734
4743
  await this.refsStore.setSymbolic("HEAD", `refs/heads/${defaultBranch}`);
3735
4744
  headCommit = (await this.refsStore.resolve("HEAD"))?.objectId;
3736
4745
  }
3737
4746
  }
4747
+ const remoteHead = advertisedDefaultBranch?.startsWith("refs/heads/") ? toBranchName(advertisedDefaultBranch) : void 0;
4748
+ if (!this.bare && remoteHead) {
4749
+ const target = `refs/remotes/${this.remoteName}/${remoteHead}`;
4750
+ if ((await this.refsStore.resolve(target))?.objectId) await this.refsStore.setSymbolic(`refs/remotes/${this.remoteName}/HEAD`, target);
4751
+ }
4752
+ await this.writeConfig({
4753
+ worktree: this.bare ? void 0 : this.worktreeAccess,
4754
+ singleBranch,
4755
+ branch: branchToClone,
4756
+ detachedTag,
4757
+ remoteHead,
4758
+ checkedOutBranch
4759
+ });
3738
4760
  const advertisedRefs = /* @__PURE__ */ new Map();
3739
4761
  for (const ref of result.remoteRefs) if (ref.oid) advertisedRefs.set(ref.name, ref.oid);
3740
- return {
4762
+ const cloneResult = {
3741
4763
  fetchResult: {
3742
4764
  uri: this.uri,
3743
4765
  advertisedRefs,
@@ -3752,25 +4774,110 @@ var CloneCommand = class extends TransportCommand {
3752
4774
  bare: this.bare,
3753
4775
  headCommit
3754
4776
  };
4777
+ if (checkoutId) try {
4778
+ const collided = await this.checkoutHead(checkoutId);
4779
+ if (collided.length > 0) cloneResult.collidedPaths = collided;
4780
+ } catch (error) {
4781
+ throw new CloneCheckoutError(cloneResult, error);
4782
+ }
4783
+ return cloneResult;
3755
4784
  }
3756
4785
  /**
3757
- * Determine which branch to clone based on options.
4786
+ * Writes the configuration `git clone` writes (clone.c): `remote.<name>.url`,
4787
+ * `remote.<name>.tagOpt` for `--no-tags` and `--mirror` (git 2.49+), the `remote.<name>.fetch` refspec of what was
4788
+ * cloned (none for a bare clone; `+refs/*:refs/*` and `remote.<name>.mirror` for a
4789
+ * mirror; one branch or tag for a single-branch clone), and the upstream of the
4790
+ * checked-out branch (`branch.<b>.remote`, `branch.<b>.merge`).
3758
4791
  */
3759
- determineBranchToClone() {
3760
- if (this.branch) return this.branch;
3761
- if (this.mirror || this.cloneAllBranches) return;
3762
- if (this.branchesToClone.length > 0) return this.branchesToClone[0];
4792
+ async writeConfig(clone) {
4793
+ const store = RemoteConfigStore.from(this.workingCopy);
4794
+ const capabilities = clone.worktree?.capabilities;
4795
+ if (capabilities?.executable === false) store.setValue("core.filemode", "false");
4796
+ if (capabilities?.symlinks === false) store.setValue("core.symlinks", "false");
4797
+ const folding = await clone.worktree?.probeCaseFolding?.();
4798
+ if (folding?.ignoreCase) store.setValue("core.ignorecase", "true");
4799
+ if (folding?.precomposeUnicode) store.setValue("core.precomposeunicode", "true");
4800
+ const remote = `remote.${this.remoteName}`;
4801
+ store.setValue(`${remote}.url`, this.uri);
4802
+ if (this.tagOption === "no-tags" || this.mirror) store.setValue(`${remote}.tagOpt`, "--no-tags");
4803
+ let fetchRefspec;
4804
+ if (this.mirror) fetchRefspec = "+refs/*:refs/*";
4805
+ else if (!this.bare) {
4806
+ const top = `refs/remotes/${this.remoteName}/`;
4807
+ if (!clone.singleBranch) fetchRefspec = `+refs/heads/*:${top}*`;
4808
+ else if (clone.detachedTag) fetchRefspec = `+${clone.detachedTag}:${clone.detachedTag}`;
4809
+ else if (clone.branch) fetchRefspec = `+refs/heads/${clone.branch}:${top}${clone.branch}`;
4810
+ else if (clone.remoteHead) fetchRefspec = `+refs/heads/${clone.remoteHead}:${top}${clone.remoteHead}`;
4811
+ }
4812
+ if (fetchRefspec) {
4813
+ store.setValue(`${remote}.fetch`, fetchRefspec);
4814
+ if (this.mirror) store.setValue(`${remote}.mirror`, "true");
4815
+ }
4816
+ if (!this.bare && clone.checkedOutBranch) {
4817
+ store.setValue(`branch.${clone.checkedOutBranch}.remote`, this.remoteName);
4818
+ store.setValue(`branch.${clone.checkedOutBranch}.merge`, `refs/heads/${clone.checkedOutBranch}`);
4819
+ }
4820
+ await store.save();
4821
+ }
4822
+ /** The branch the local HEAD names (`init.defaultBranch` of the new repository), if any. */
4823
+ async localHeadBranch() {
4824
+ const head = await this.refsStore.get("HEAD");
4825
+ return head && "target" in head && head.target.startsWith("refs/heads/") ? head.target.slice(11) : void 0;
3763
4826
  }
3764
4827
  /**
3765
- * Checkout HEAD commit to staging area.
4828
+ * Check out the cloned commit, as `git clone` does: the files of its tree into the
4829
+ * worktree, then the index with the stat data of the files written. Without a
4830
+ * worktree only the index is filled.
4831
+ *
4832
+ * The whole tree is planned (and every blob checked) before the first file is
4833
+ * written. Symlinks become links where the worktree makes them and `core.symlinks`
4834
+ * is not false, else plain files holding the target (the index keeps mode 120000);
4835
+ * a submodule becomes an empty directory, as in a clone without `--recurse-submodules`.
4836
+ *
4837
+ * The index records size, mtime and (where the worktree reports it) ctime, but no inode,
4838
+ * device, uid or gid, which FilesApi does not give: `git status` sees the files clean and
4839
+ * refreshes the index once, while commands that do not refresh (`git diff-files`,
4840
+ * `git diff-index --quiet`) report every file as changed until then, unless
4841
+ * `core.checkStat=minimal`.
3766
4842
  */
3767
4843
  async checkoutHead(commitId) {
3768
- try {
3769
- const commit = await this.commits.load(commitId);
3770
- if (!commit) return;
4844
+ const commit = await this.commits.load(commitId).catch(() => void 0);
4845
+ if (!commit) return [];
4846
+ const worktree = this.bare ? void 0 : this.worktreeAccess;
4847
+ if (!worktree) {
3771
4848
  await this.staging.readTree(this.trees, commit.tree);
3772
4849
  await this.staging.write();
3773
- } catch {}
4850
+ return [];
4851
+ }
4852
+ const plan = await planTreeRestore(this.trees, this.blobs, commit.tree, CLONE, {
4853
+ symlinks: true,
4854
+ ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
4855
+ windows: worktree.capabilities?.windowsPaths === true,
4856
+ reservedNames: worktree.capabilities?.reservedNames
4857
+ });
4858
+ const symlinks = this.symlinksEnabled(worktree);
4859
+ await writeTreeRestorePlan(worktree, this.blobs, plan, CLONE, {
4860
+ symlinks,
4861
+ gitlinks: true
4862
+ });
4863
+ await this.staging.readTree(this.trees, commit.tree);
4864
+ const editor = this.staging.createEditor();
4865
+ for (const { path, objectId, mode } of plan.entries) {
4866
+ const stats = await worktree.getEntry(path);
4867
+ if (stats) editor.upsert({
4868
+ path,
4869
+ objectId,
4870
+ mode,
4871
+ ...entryStatOf(stats)
4872
+ });
4873
+ }
4874
+ await editor.finish();
4875
+ await this.staging.write();
4876
+ return plan.collided;
4877
+ }
4878
+ /** Whether symlinks are written as links: the worktree can, and `core.symlinks` allows. */
4879
+ symlinksEnabled(worktree) {
4880
+ return worktreeModeTrust(this.workingCopy, worktree).symlinks;
3774
4881
  }
3775
4882
  };
3776
4883
  /**
@@ -5190,7 +6297,7 @@ var Git = class Git {
5190
6297
  return new CleanCommand(this._workingCopy);
5191
6298
  }
5192
6299
  /**
5193
- * Create a StatusCommand for showing staging area status.
6300
+ * Create a StatusCommand for showing the index and worktree status.
5194
6301
  *
5195
6302
  * @example
5196
6303
  * ```typescript
@@ -5346,6 +6453,30 @@ var Git = class Git {
5346
6453
  return new RemoteSetUrlCommand(this._workingCopy);
5347
6454
  }
5348
6455
  /**
6456
+ * Create a RemoteSetHeadCommand for setting or deleting `refs/remotes/<name>/HEAD`.
6457
+ *
6458
+ * @example
6459
+ * ```typescript
6460
+ * await git.remoteSetHead().setRemoteName("origin").setBranch("develop").call();
6461
+ * ```
6462
+ */
6463
+ remoteSetHead() {
6464
+ this.checkClosed();
6465
+ return new RemoteSetHeadCommand(this._workingCopy);
6466
+ }
6467
+ /**
6468
+ * Create a RemoteRenameCommand for renaming a remote (`git remote rename`).
6469
+ *
6470
+ * @example
6471
+ * ```typescript
6472
+ * await git.remoteRename().setOldName("origin").setNewName("upstream").call();
6473
+ * ```
6474
+ */
6475
+ remoteRename() {
6476
+ this.checkClosed();
6477
+ return new RemoteRenameCommand(this._workingCopy);
6478
+ }
6479
+ /**
5349
6480
  * Create a RebaseCommand for rebasing commits.
5350
6481
  *
5351
6482
  * @example
@@ -5370,8 +6501,8 @@ var Git = class Git {
5370
6501
  *
5371
6502
  * @example
5372
6503
  * ```typescript
6504
+ * // the working copy's index and worktree are stashed, then reset to HEAD
5373
6505
  * const stashCommit = await git.stashCreate()
5374
- * .setWorkingTreeProvider(provider)
5375
6506
  * .setMessage("WIP: feature work")
5376
6507
  * .call();
5377
6508
  * ```
@@ -5721,26 +6852,32 @@ var InitCommand = class {
5721
6852
  let staging;
5722
6853
  if (this.files) {
5723
6854
  const dir = gitDir.replace(/\/+$/, "") || ".";
5724
- const isFile = async (path) => (await files.stats(path))?.kind === "file";
6855
+ const repoFiles = await resolveLinkedGitDir(files, dir);
6856
+ const isFile = async (path) => (await repoFiles.stats(path))?.kind === "file";
5725
6857
  const hasHead = await isFile(`${dir}/HEAD`);
5726
6858
  const fresh = !hasHead && !await isFile(`${dir}/config`);
5727
6859
  const open = (create) => createGitFilesHistoryFromFiles({
5728
- files,
6860
+ files: repoFiles,
5729
6861
  gitDir,
5730
6862
  create,
5731
6863
  defaultBranch: this.initialBranch
5732
6864
  });
5733
6865
  if (fresh && this.bare && dir !== ".") {
5734
6866
  await open(true);
5735
- await markBare(files, `${dir}/config`);
6867
+ await markBare(repoFiles, `${dir}/config`);
5736
6868
  history = await open(false);
5737
6869
  } else history = await open(fresh);
5738
6870
  await history.initialize();
6871
+ if (fresh) {
6872
+ const folding = await probeCaseFolding(repoFiles, dir);
6873
+ if (folding.ignoreCase) await setCoreValue(repoFiles, `${dir}/config`, "ignorecase", "true");
6874
+ if (folding.precomposeUnicode) await setCoreValue(repoFiles, `${dir}/config`, "precomposeunicode", "true");
6875
+ }
5739
6876
  if (!hasHead && !fresh) await history.refs.setSymbolic("HEAD", `refs/heads/${this.initialBranch}`);
5740
6877
  if (this.stagingStore) staging = this.stagingStore;
5741
6878
  else if (this.bare) staging = new MemoryStagingStore();
5742
6879
  else {
5743
- const fileStaging = new FileStagingStore(files, `${dir}/index`);
6880
+ const fileStaging = new FileStagingStore(repoFiles, `${dir}/index`);
5744
6881
  await fileStaging.read();
5745
6882
  staging = fileStaging;
5746
6883
  }
@@ -5834,10 +6971,15 @@ var InitCommand = class {
5834
6971
  };
5835
6972
  /** Sets `core.bare = true` in a config file written by the git directory layout. */
5836
6973
  async function markBare(files, configPath) {
6974
+ await setCoreValue(files, configPath, "bare", "true");
6975
+ }
6976
+ /** Sets `core.<key>` in the fresh config `init` wrote (one `[core]` section). */
6977
+ async function setCoreValue(files, configPath, key, value) {
5837
6978
  const chunks = [];
5838
6979
  for await (const chunk of files.read(configPath)) chunks.push(chunk);
5839
6980
  const text = new TextDecoder().decode(concatChunks(chunks));
5840
- const updated = /^\s*bare\s*=/m.test(text) ? text.replace(/^(\s*bare\s*=\s*)\S+/m, "$1true") : text.replace(/^\[core\]\s*$/m, "[core]\n bare = true");
6981
+ const existing = new RegExp(`^(\\s*${key}\\s*=\\s*)\\S+`, "mi");
6982
+ const updated = existing.test(text) ? text.replace(existing, `$1${value}`) : text.replace(/^\[core\]\s*$/m, `[core]\n\t${key} = ${value}`);
5841
6983
  await files.write(configPath, [new TextEncoder().encode(updated)]);
5842
6984
  }
5843
6985
  function concatChunks(chunks) {
@@ -8358,6 +9500,14 @@ var RemoteAddCommand = class extends GitCommand {
8358
9500
  *
8359
9501
  * Based on JGit's RemoteRemoveCommand.
8360
9502
  *
9503
+ * As git's builtin/remote.c `rm`: the branches whose upstream is the remote lose
9504
+ * `branch.<b>.remote` and `branch.<b>.merge`, those pushing to it `branch.<b>.pushRemote`;
9505
+ * the remote-tracking refs its fetch refspecs map to (under `refs/remotes/`, and not mapped
9506
+ * by another remote too) are deleted with their reflogs, `refs/remotes/<name>/HEAD`
9507
+ * included; `remote.pushDefault` naming it is unset; the `[remote "<name>"]` section goes.
9508
+ * Local branches a refspec maps to are kept, and git's note naming them is in
9509
+ * {@link getMessages}. A remote without a config section is refused, as git refuses it.
9510
+ *
8361
9511
  * @example
8362
9512
  * ```typescript
8363
9513
  * await git.remoteRemove()
@@ -8367,6 +9517,7 @@ var RemoteAddCommand = class extends GitCommand {
8367
9517
  */
8368
9518
  var RemoteRemoveCommand = class extends GitCommand {
8369
9519
  remoteName;
9520
+ messages = [];
8370
9521
  /**
8371
9522
  * Set the remote name to remove.
8372
9523
  *
@@ -8384,32 +9535,205 @@ var RemoteRemoveCommand = class extends GitCommand {
8384
9535
  return this.remoteName;
8385
9536
  }
8386
9537
  /**
9538
+ * What git prints after the removal (on stderr): the note on local branches a refspec
9539
+ * maps to, which are not removed. Empty until {@link call} has run.
9540
+ */
9541
+ getMessages() {
9542
+ return [...this.messages];
9543
+ }
9544
+ /**
8387
9545
  * Execute the remote remove operation.
8388
9546
  *
8389
- * Drops both halves of a remote: its config section and its tracking refs.
8390
- * A remote that has only one of the two is still removable.
8391
- *
8392
- * @returns Removed remote config, or undefined if not found
9547
+ * @returns Removed remote config
9548
+ * @throws RemoteNotFoundError when the remote has no config section (git: "No such
9549
+ * remote: '<name>'"); nothing is changed then
8393
9550
  */
8394
9551
  async call() {
8395
9552
  this.checkCallable();
8396
9553
  this.setCallable(false);
8397
- if (!this.remoteName) throw new MissingArgumentError("remoteName", "Remote name must be specified");
9554
+ const name = this.remoteName;
9555
+ if (!name) throw new MissingArgumentError("remoteName", "Remote name must be specified");
8398
9556
  const store = RemoteConfigStore.from(this.workingCopy);
8399
- const configured = store.isConfigured(this.remoteName);
9557
+ if (!store.isConfigured(name)) throw new RemoteNotFoundError(name, `No such remote: '${name}'`);
9558
+ const removed = store.read(name);
9559
+ const own = store.configuredFetchRefspecs(name).map((spec) => parseRefSpec(spec));
9560
+ const others = store.configuredNames().filter((other) => other !== name).map((other) => store.configuredFetchRefspecs(other).map((spec) => parseRefSpec(spec)));
8400
9561
  const refsToDelete = [];
8401
- for await (const ref of this.refsStore.list(`refs/remotes/${this.remoteName}/`)) refsToDelete.push(ref.name);
8402
- if (!configured && refsToDelete.length === 0) return;
8403
- const removed = store.read(this.remoteName);
8404
- for (const refName of refsToDelete) await this.refsStore.delete(refName);
8405
- if (configured) {
8406
- store.remove(this.remoteName);
8407
- await store.save();
9562
+ const skipped = [];
9563
+ for await (const ref of this.refsStore.list("refs/")) {
9564
+ if (!tracks(own, ref.name)) continue;
9565
+ if (others.some((specs) => tracks(specs, ref.name))) continue;
9566
+ if (!ref.name.startsWith("refs/remotes/")) {
9567
+ if (ref.name.startsWith("refs/heads/")) skipped.push(ref.name.slice(11));
9568
+ continue;
9569
+ }
9570
+ refsToDelete.push(ref.name);
8408
9571
  }
9572
+ for (const branch of store.subsections("branch")) {
9573
+ if (store.value(`branch.${branch}.remote`) === name) {
9574
+ store.unset(`branch.${branch}.remote`);
9575
+ store.unset(`branch.${branch}.merge`);
9576
+ }
9577
+ if (store.value(`branch.${branch}.pushRemote`) === name) store.unset(`branch.${branch}.pushRemote`);
9578
+ }
9579
+ await deleteRefs(this.refsStore, refsToDelete, "remote: remove");
9580
+ if (skipped.length > 0) this.messages.push(skipped.length === 1 ? "Note: A branch outside the refs/remotes/ hierarchy was not removed;\nto delete it, use:" : "Note: Some branches outside the refs/remotes/ hierarchy were not removed;\nto delete them, use:", ...skipped.map((branch) => ` git branch -d ${branch}`));
9581
+ store.remove(name);
9582
+ if (store.value("remote.pushDefault") === name) store.unset("remote.pushDefault");
9583
+ await store.save();
8409
9584
  return removed;
8410
9585
  }
8411
9586
  };
8412
9587
  /**
9588
+ * Rename a remote.
9589
+ *
9590
+ * Equivalent to `git remote rename <old> <new>`.
9591
+ *
9592
+ * As git's builtin/remote.c `mv`: the `[remote "<old>"]` section is renamed in place; each
9593
+ * fetch refspec writing under `refs/remotes/<old>/` is rewritten to `refs/remotes/<new>/`,
9594
+ * the others kept with git's warning; `branch.<b>.remote` and `branch.<b>.pushRemote`
9595
+ * naming the remote are updated. When a refspec was rewritten, the refs under
9596
+ * `refs/remotes/<old>/` move to `refs/remotes/<new>/` in one batch, each with its reflog
9597
+ * and a `remote: renamed <old ref> to <new ref>` line, symbolic refs (`HEAD`) re-pointed
9598
+ * at the moved refs, and `remote.pushDefault` follows the new name.
9599
+ *
9600
+ * @example
9601
+ * ```typescript
9602
+ * const { remote, warnings } = await git.remoteRename().setOldName("origin").setNewName("upstream").call();
9603
+ * ```
9604
+ */
9605
+ var RemoteRenameCommand = class extends GitCommand {
9606
+ oldName;
9607
+ newName;
9608
+ /** Set the remote to rename. */
9609
+ setOldName(name) {
9610
+ this.checkCallable();
9611
+ this.oldName = name;
9612
+ return this;
9613
+ }
9614
+ /** Set the remote's new name. */
9615
+ setNewName(name) {
9616
+ this.checkCallable();
9617
+ this.newName = name;
9618
+ return this;
9619
+ }
9620
+ /**
9621
+ * @throws RemoteNotFoundError if the remote has no config section (git: "No such remote: '<old>'")
9622
+ * @throws RemoteAlreadyExistsError if the new name is taken (git: "remote <new> already exists.")
9623
+ * @throws InvalidArgumentError for an invalid new name (git: "'<new>' is not a valid remote name")
9624
+ */
9625
+ async call() {
9626
+ this.checkCallable();
9627
+ this.setCallable(false);
9628
+ const { oldName, newName } = this;
9629
+ if (!oldName) throw new MissingArgumentError("oldName", "Old remote name must be specified");
9630
+ if (!newName) throw new MissingArgumentError("newName", "New remote name must be specified");
9631
+ const store = RemoteConfigStore.from(this.workingCopy);
9632
+ if (!store.isConfigured(oldName)) throw new RemoteNotFoundError(oldName, `No such remote: '${oldName}'`);
9633
+ if (store.isConfigured(newName)) throw new RemoteAlreadyExistsError(newName, `remote ${newName} already exists.`);
9634
+ if (!isValidRemoteName(newName)) throw new InvalidArgumentError("newName", newName, `'${newName}' is not a valid remote name`);
9635
+ const fetch = store.configuredFetchRefspecs(oldName);
9636
+ const oldContext = `:refs/remotes/${oldName}/`;
9637
+ const refspecsNeedUpdate = fetch.some((spec) => spec.includes(oldContext));
9638
+ const oldTop = `refs/remotes/${oldName}/`;
9639
+ const renamed = (ref) => `refs/remotes/${newName}/${ref.slice(oldTop.length)}`;
9640
+ if (refspecsNeedUpdate) {
9641
+ const moves = [];
9642
+ for await (const ref of this.refsStore.list(oldTop)) {
9643
+ const to = renamed(ref.name);
9644
+ const reflog = [];
9645
+ const id = isSymbolicRef(ref) ? void 0 : ref.objectId;
9646
+ const log = id ? await this.refsStore.getReflog?.(ref.name) : void 0;
9647
+ if (log && id) {
9648
+ for (const entry of (await log.getReverseEntries()).reverse()) reflog.push({
9649
+ oldId: entry.oldId,
9650
+ newId: entry.newId,
9651
+ ident: formatIdent(entry.who),
9652
+ message: entry.comment
9653
+ });
9654
+ reflog.push({
9655
+ oldId: id,
9656
+ newId: id,
9657
+ message: `remote: renamed ${ref.name} to ${to}`
9658
+ });
9659
+ }
9660
+ moves.push({
9661
+ from: ref.name,
9662
+ to,
9663
+ reflog: reflog.length > 0 ? reflog : void 0
9664
+ });
9665
+ }
9666
+ await moveRefs(this.refsStore, moves, (target) => target.startsWith(oldTop) ? renamed(target) : target);
9667
+ }
9668
+ store.rename(oldName, newName);
9669
+ const warnings = [];
9670
+ if (fetch.length > 0) {
9671
+ const rewritten = fetch.map((spec) => {
9672
+ const at = spec.indexOf(oldContext);
9673
+ if (at < 0) {
9674
+ warnings.push(`Not updating non-default fetch refspec\n\t${spec}\n\tPlease update the configuration manually if necessary.`);
9675
+ return spec;
9676
+ }
9677
+ const nameAt = at + 14;
9678
+ return `${spec.slice(0, nameAt)}${newName}${spec.slice(nameAt + oldName.length)}`;
9679
+ });
9680
+ store.setValues(`remote.${newName}.fetch`, rewritten);
9681
+ }
9682
+ for (const branch of store.subsections("branch")) {
9683
+ if (store.value(`branch.${branch}.remote`) === oldName) store.setValue(`branch.${branch}.remote`, newName);
9684
+ if (store.value(`branch.${branch}.pushRemote`) === oldName) store.setValue(`branch.${branch}.pushRemote`, newName);
9685
+ }
9686
+ if (refspecsNeedUpdate && store.value("remote.pushDefault") === oldName) store.setValue("remote.pushDefault", newName);
9687
+ await store.save();
9688
+ return {
9689
+ remote: store.read(newName),
9690
+ warnings
9691
+ };
9692
+ }
9693
+ };
9694
+ /** git's report_set_head_auto (builtin/remote.c), from what `refs/remotes/<remote>/HEAD` held. */
9695
+ function reportSetHeadAuto(remote, head, previous) {
9696
+ const prefix = `refs/remotes/${remote}/`;
9697
+ const target = previous && "target" in previous ? previous.target : void 0;
9698
+ const prev = target?.startsWith(prefix) ? target.slice(prefix.length) : void 0;
9699
+ if (prev === head) return `'${remote}/HEAD' is unchanged and points to '${head}'`;
9700
+ if (prev !== void 0) return `'${remote}/HEAD' has changed from '${prev}' and now points to '${head}'`;
9701
+ if (!previous) return `'${remote}/HEAD' is now created and points to '${head}'`;
9702
+ if (target === void 0) return `'${remote}/HEAD' was detached at '${previous.objectId}' and now points to '${head}'`;
9703
+ return `'${remote}/HEAD' used to point to '${target}' (which is not a remote branch), but now points to '${head}'`;
9704
+ }
9705
+ /** git's remote_find_tracking: whether a fetch refspec writes `refName` (and no negative one excludes it). */
9706
+ function tracks(specs, refName) {
9707
+ const sources = [];
9708
+ for (const spec of specs) {
9709
+ if (spec.negative || !spec.source || !spec.destination) continue;
9710
+ if (spec.wildcard) {
9711
+ if (!matchDestination(spec, refName)) continue;
9712
+ const source = expandFromDestination(spec, refName).source;
9713
+ if (source) sources.push(source);
9714
+ } else if (spec.destination === refName) sources.push(spec.source);
9715
+ }
9716
+ const negative = specs.filter((spec) => spec.negative && spec.source);
9717
+ const excluded = sources.some((source) => negative.some((n) => n.wildcard ? matchesPattern(n.source, source) : n.source === source));
9718
+ return sources.length > 0 && !excluded;
9719
+ }
9720
+ /** A `*` pattern of a negative refspec matches `name`. */
9721
+ function matchesPattern(pattern, name) {
9722
+ const star = pattern.indexOf("*");
9723
+ if (star < 0) return pattern === name;
9724
+ const head = pattern.slice(0, star);
9725
+ const tail = pattern.slice(star + 1);
9726
+ return name.length >= head.length + tail.length && name.startsWith(head) && name.endsWith(tail);
9727
+ }
9728
+ /** git's valid_remote_name: `refs/remotes/<name>/test` is a valid ref name. */
9729
+ function isValidRemoteName(name) {
9730
+ return name.length > 0 && isValidRefName(`refs/remotes/${name}/test`);
9731
+ }
9732
+ /** A reflog identity, as git writes it: `Name <email> <seconds> <tz>`. */
9733
+ function formatIdent(who) {
9734
+ return `${who.name} <${who.email}> ${Math.floor(who.timestamp)} ${who.tzOffset}`;
9735
+ }
9736
+ /**
8413
9737
  * List remotes in the repository.
8414
9738
  *
8415
9739
  * Equivalent to `git remote -v`.
@@ -8555,66 +9879,128 @@ var RemoteSetUrlCommand = class extends GitCommand {
8555
9879
  return false;
8556
9880
  }
8557
9881
  };
8558
- //#endregion
8559
- //#region src/commands/tree-restore.ts
8560
9882
  /**
8561
- * Walk a tree and plan which files to restore, validating as it goes.
9883
+ * Point `refs/remotes/<name>/HEAD` at one of the remote's tracking branches, or delete it.
8562
9884
  *
8563
- * Throws on anything that cannot be restored faithfully, so the caller can
8564
- * abort before mutating the working tree.
9885
+ * Equivalent to `git remote set-head <name> <branch>`, `git remote set-head <name> -a`
9886
+ * and `git remote set-head <name> -d`. The symbolic ref names the remote's default branch,
9887
+ * so the remote name alone resolves to that branch (`git log origin`); `git clone` creates
9888
+ * it. With {@link setAuto} the remote is asked which branch its HEAD is (its HEAD symref,
9889
+ * or else the one branch at HEAD's commit). As git 2.48+, setting it on a remote whose
9890
+ * `remote.<name>.followRemoteHEAD` is `always` turns that into `warn`, so the next fetch
9891
+ * does not undo the choice.
8565
9892
  *
8566
- * @param trees Tree storage to walk
8567
- * @param blobs Blob storage, checked for the content of every planned file
8568
- * @param treeId Tree to restore
8569
- * @param operation Names the operation in failure messages, e.g. `reset --hard`
9893
+ * @example
9894
+ * ```typescript
9895
+ * await git.remoteSetHead().setRemoteName("origin").setBranch("develop").call();
9896
+ * await git.remoteSetHead().setRemoteName("origin").setAuto(true).call();
9897
+ * await git.remoteSetHead().setRemoteName("origin").setDelete(true).call();
9898
+ * ```
8570
9899
  */
8571
- async function planTreeRestore(trees, blobs, treeId, operation) {
8572
- const plan = {
8573
- entries: [],
8574
- paths: /* @__PURE__ */ new Set()
8575
- };
8576
- await planInto(trees, blobs, treeId, "", operation, plan);
8577
- return plan;
8578
- }
8579
- async function planInto(trees, blobs, treeId, prefix, operation, plan) {
8580
- for await (const entry of trees.loadTree(treeId)) {
8581
- const path = prefix ? `${prefix}/${entry.name}` : entry.name;
8582
- if (entry.mode === FileMode.TREE) {
8583
- await planInto(trees, blobs, entry.id, path, operation, plan);
8584
- continue;
8585
- }
8586
- if (entry.mode === FileMode.GITLINK) {
8587
- plan.paths.add(path);
8588
- continue;
9900
+ var RemoteSetHeadCommand = class extends TransportCommand {
9901
+ remoteName;
9902
+ branch;
9903
+ deleteHead = false;
9904
+ auto = false;
9905
+ messages = [];
9906
+ /** Set the remote whose HEAD is set. */
9907
+ setRemoteName(name) {
9908
+ this.checkCallable();
9909
+ this.remoteName = name;
9910
+ return this;
9911
+ }
9912
+ /** Set the branch (`develop`, or `refs/remotes/origin/develop`) HEAD names. */
9913
+ setBranch(branch) {
9914
+ this.checkCallable();
9915
+ this.branch = branch;
9916
+ return this;
9917
+ }
9918
+ /** Delete `refs/remotes/<name>/HEAD` instead (`-d`). */
9919
+ setDelete(deleteHead) {
9920
+ this.checkCallable();
9921
+ this.deleteHead = deleteHead;
9922
+ return this;
9923
+ }
9924
+ /**
9925
+ * What `git remote set-head -a` prints (git 2.48+): `'origin/HEAD' is now created and
9926
+ * points to 'main'`, `… is unchanged and points to …`, `… has changed from 'a' and now
9927
+ * points to 'b'`, and so on. Empty without {@link setAuto}, or before {@link call}.
9928
+ */
9929
+ getMessages() {
9930
+ return [...this.messages];
9931
+ }
9932
+ /** Ask the remote which branch its HEAD is, and point at that one (`-a`). */
9933
+ setAuto(auto) {
9934
+ this.checkCallable();
9935
+ this.auto = auto;
9936
+ return this;
9937
+ }
9938
+ /**
9939
+ * @returns The tracking ref HEAD now names, or undefined after a delete
9940
+ * @throws RefNotFoundError if the tracking branch does not exist (git: "Not a valid ref: <ref>")
9941
+ * @throws RefNotFoundError with `-a` when the remote HEAD names no branch (git: "Cannot
9942
+ * determine remote HEAD"), or several ("Multiple remote HEAD branches. Please choose
9943
+ * one explicitly with:" and a `git remote set-head` line for each)
9944
+ */
9945
+ async call() {
9946
+ this.checkCallable();
9947
+ this.setCallable(false);
9948
+ const remote = this.remoteName;
9949
+ if (!remote) throw new MissingArgumentError("remoteName", "Remote name must be specified");
9950
+ const top = `refs/remotes/${remote}/`;
9951
+ if (this.deleteHead) {
9952
+ await this.refsStore.delete(`${top}HEAD`);
9953
+ return;
8589
9954
  }
8590
- if (entry.mode === FileMode.SYMLINK) throw new Error(`${operation} cannot restore ${path}: the worktree cannot create symbolic links`);
8591
- if (!await blobs.has(entry.id)) throw new Error(`${operation} cannot restore ${path}: blob ${entry.id} is missing`);
8592
- plan.entries.push({
8593
- path,
8594
- objectId: entry.id,
8595
- mode: entry.mode
8596
- });
8597
- plan.paths.add(path);
9955
+ let branch = this.branch;
9956
+ if (this.auto) {
9957
+ const heads = await this.remoteHeads(remote);
9958
+ if (heads.length === 0) throw new RefNotFoundError(`${top}HEAD`, "Cannot determine remote HEAD");
9959
+ if (heads.length > 1) {
9960
+ const lines = heads.map((h) => ` git remote set-head ${remote} ${h}`);
9961
+ throw new RefNotFoundError(`${top}HEAD`, ["Multiple remote HEAD branches. Please choose one explicitly with:", ...lines].join("\n"));
9962
+ }
9963
+ branch = heads[0];
9964
+ }
9965
+ if (!branch) throw new MissingArgumentError("branch", "Branch must be specified, or auto or delete set");
9966
+ const target = branch.startsWith(top) ? branch : `${top}${branch}`;
9967
+ if (!(await this.refsStore.resolve(target))?.objectId) throw new RefNotFoundError(target, `Not a valid ref: ${target}`);
9968
+ const previous = await this.refsStore.get(`${top}HEAD`);
9969
+ await this.refsStore.setSymbolic(`${top}HEAD`, target);
9970
+ if (this.auto) this.messages.push(reportSetHeadAuto(remote, target.slice(top.length), previous));
9971
+ const store = RemoteConfigStore.from(this.workingCopy);
9972
+ if (store.value(`remote.${remote}.followRemoteHEAD`) === "always") {
9973
+ store.setValue(`remote.${remote}.followRemoteHEAD`, "warn");
9974
+ await store.save();
9975
+ }
9976
+ return target;
8598
9977
  }
8599
- }
8600
- /**
8601
- * Execute a plan produced by {@link planTreeRestore}, writing every file.
8602
- *
8603
- * @param worktree Working tree to write into
8604
- * @param blobs Blob storage to read content from
8605
- * @param plan The validated plan
8606
- * @param operation Names the operation in failure messages
8607
- */
8608
- async function writeTreeRestorePlan(worktree, blobs, plan, operation) {
8609
- for (const { path, objectId, mode } of plan.entries) {
8610
- const content = await blobs.load(objectId);
8611
- if (!content) throw new Error(`${operation} cannot restore ${path}: blob ${objectId} is missing`);
8612
- await worktree.writeContent(path, content, {
8613
- mode,
8614
- createParents: true
9978
+ /**
9979
+ * The remote's HEAD branches, as git's get_remote_ref_states (GET_HEAD_NAMES) finds them:
9980
+ * every ref listed, then the branch HEAD's symref names, or else every branch at HEAD's
9981
+ * commit (git's guess_remote_head with all matches).
9982
+ */
9983
+ async remoteHeads(remote) {
9984
+ const url = RemoteConfigStore.from(this.workingCopy).urlFor(remote);
9985
+ if (!url) throw new InvalidRemoteError(remote);
9986
+ const connection = await openHttpConnection({
9987
+ url,
9988
+ auth: this.credentials,
9989
+ headers: this.headers,
9990
+ timeout: this.timeout
8615
9991
  });
9992
+ let refs;
9993
+ try {
9994
+ refs = connection.version === 2 ? await lsRefs(connection, []) : connection.advertisedRefs ?? [];
9995
+ } finally {
9996
+ await connection.close();
9997
+ }
9998
+ const head = refs.find((r) => r.name === "HEAD");
9999
+ if (!head) return [];
10000
+ const branches = refs.filter((r) => r.oid && r.name.startsWith("refs/heads/"));
10001
+ return (head.symref ? branches.filter((r) => r.name === head.symref) : branches.filter((r) => r.oid === head.oid)).map((r) => r.name.slice(11));
8616
10002
  }
8617
- }
10003
+ };
8618
10004
  //#endregion
8619
10005
  //#region src/commands/reset-command.ts
8620
10006
  /** Names this operation in restore failure messages. */
@@ -8783,12 +10169,20 @@ var ResetCommand = class extends GitCommand {
8783
10169
  if (!worktree) return;
8784
10170
  const commit = await this.commits.load(targetId);
8785
10171
  if (!commit) throw new RefNotFoundError(targetId, "Target commit not found");
8786
- const plan = await planTreeRestore(this.trees, this.blobs, commit.tree, RESET_HARD);
8787
- await writeTreeRestorePlan(worktree, this.blobs, plan, RESET_HARD);
10172
+ const plan = await planTreeRestore(this.trees, this.blobs, commit.tree, RESET_HARD, {
10173
+ symlinks: true,
10174
+ ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
10175
+ windows: worktree.capabilities?.windowsPaths === true,
10176
+ reservedNames: worktree.capabilities?.reservedNames
10177
+ });
8788
10178
  for (const path of trackedBefore) {
8789
10179
  if (plan.paths.has(path)) continue;
8790
10180
  await worktree.remove(path);
8791
10181
  }
10182
+ await writeTreeRestorePlan(worktree, this.blobs, plan, RESET_HARD, {
10183
+ symlinks: worktreeModeTrust(this.workingCopy, worktree).symlinks,
10184
+ replaceInTheWay: true
10185
+ });
8792
10186
  }
8793
10187
  /**
8794
10188
  * Reset staging area to match a tree.
@@ -9327,12 +10721,15 @@ var StashListCommand = class extends GitCommand {
9327
10721
  return stashes;
9328
10722
  }
9329
10723
  /**
9330
- * Get stash entries.
9331
- *
9332
- * Note: Without reflog support in the core Refs interface,
9333
- * this returns only the most recent stash (if any).
10724
+ * Get stash entries: the reflog of `refs/stash`, newest first, as `git stash list`
10725
+ * reads it. A store without reflogs gives only the current `refs/stash`.
9334
10726
  */
9335
10727
  async getStashReflog() {
10728
+ const reflog = await this.refsStore.getReflog?.(STASH_REF);
10729
+ if (reflog) return (await reflog.getReverseEntries()).map((e) => ({
10730
+ commitId: e.newId,
10731
+ message: e.comment
10732
+ }));
9336
10733
  const stashRef = await this.refsStore.resolve(STASH_REF);
9337
10734
  if (stashRef?.objectId) {
9338
10735
  const commit = await this.commits.load(stashRef.objectId);
@@ -9367,8 +10764,27 @@ var StashListCommand = class extends GitCommand {
9367
10764
  };
9368
10765
  //#endregion
9369
10766
  //#region src/commands/stash-apply-command.ts
10767
+ function concatBytes(chunks) {
10768
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
10769
+ let offset = 0;
10770
+ for (const c of chunks) {
10771
+ out.set(c, offset);
10772
+ offset += c.length;
10773
+ }
10774
+ return out;
10775
+ }
10776
+ const sameEntry = (a, b) => a === void 0 || b === void 0 ? a === b : a.objectId === b.objectId && a.mode === b.mode;
9370
10777
  /** Names this operation in restore failure messages. */
9371
10778
  const STASH_APPLY = "stash apply";
10779
+ /** Removes the directory at `path` if nothing is in it (git's `rmdir` of a submodule). */
10780
+ async function removeIfEmptyDirectory(worktree, path) {
10781
+ const entry = await worktree.getEntry(path);
10782
+ if (!entry?.isDirectory) {
10783
+ if (entry) await worktree.remove(path);
10784
+ return;
10785
+ }
10786
+ await removeDirectoryIfEmpty(worktree, path);
10787
+ }
9372
10788
  /**
9373
10789
  * Command to apply a stashed commit.
9374
10790
  *
@@ -9376,18 +10792,16 @@ const STASH_APPLY = "stash apply";
9376
10792
  *
9377
10793
  * Based on JGit's StashApplyCommand.
9378
10794
  *
9379
- * The stashed changes are three-way merged against the current HEAD and the
9380
- * result is written back: the merged working tree always, the merged index
9381
- * when `restoreIndex` is set, and the stashed untracked files when
9382
- * `restoreUntracked` is set. A conflict aborts before anything is written.
10795
+ * As git's `stash apply`: the stash's change is merged into the current index (staged
10796
+ * content and newly staged files take part), line by line where both sides changed a
10797
+ * file; the result goes to the worktree, refused up front where it would overwrite local
10798
+ * changes or untracked files. A content conflict is written with conflict markers and
10799
+ * staged at stages 1-3 (status CONFLICTS). Without `setRestoreIndex(true)` (`--index`)
10800
+ * the index keeps its entries plus the files the stash adds; the stashed untracked files
10801
+ * are restored first, refused (nothing written) where a file stands in their way.
9383
10802
  *
9384
- * Known limits, shared with `reset --hard`:
9385
- * - a symlink in the merged tree is refused, because the `Worktree` interface
9386
- * has no primitive to create one - writing the target as a regular file
9387
- * would silently produce a working tree that does not match;
9388
- * - a gitlink's contents are not restored, as in git;
9389
- * - directories left empty by a deletion are not pruned;
9390
- * - the restore is not atomic across the working tree and the index.
10803
+ * Known limits: a gitlink's contents are not restored, as in git; the restore is not
10804
+ * atomic across the working tree and the index.
9391
10805
  *
9392
10806
  * @example
9393
10807
  * ```typescript
@@ -9407,7 +10821,7 @@ const STASH_APPLY = "stash apply";
9407
10821
  */
9408
10822
  var StashApplyCommand = class extends GitCommand {
9409
10823
  stashRef;
9410
- restoreIndex = true;
10824
+ restoreIndex = false;
9411
10825
  restoreUntracked = true;
9412
10826
  strategy = "recursive";
9413
10827
  contentStrategy;
@@ -9430,9 +10844,12 @@ var StashApplyCommand = class extends GitCommand {
9430
10844
  return this.stashRef;
9431
10845
  }
9432
10846
  /**
9433
- * Set whether to restore the index state.
10847
+ * Set whether to restore the index state (`git stash apply --index`): the stash's index
10848
+ * change is merged into the current index, and a conflict there refuses the apply
10849
+ * ("conflicts in index. Try without --index."). Off by default, as in git: the index then
10850
+ * keeps its entries, plus the files the stash adds.
9434
10851
  *
9435
- * @param restoreIndex true to restore index (default)
10852
+ * @param restoreIndex true to restore the index (default false)
9436
10853
  */
9437
10854
  setRestoreIndex(restoreIndex) {
9438
10855
  this.checkCallable();
@@ -9514,6 +10931,9 @@ var StashApplyCommand = class extends GitCommand {
9514
10931
  this.setCallable(false);
9515
10932
  const worktree = this.worktreeAccess;
9516
10933
  if (!worktree) throw new StoreNotAvailableError("worktree", "stash apply requires a working tree");
10934
+ return worktree.batch ? worktree.batch(() => this.apply(worktree)) : this.apply(worktree);
10935
+ }
10936
+ async apply(worktree) {
9517
10937
  const headRef = await this.refsStore.resolve("HEAD");
9518
10938
  if (!headRef?.objectId) throw new NoHeadError("HEAD is required to apply stash");
9519
10939
  const stashId = await this.resolveStashRef();
@@ -9526,42 +10946,478 @@ var StashApplyCommand = class extends GitCommand {
9526
10946
  const headCommit = await this.commits.load(headRef.objectId);
9527
10947
  const stashHeadCommitObj = await this.commits.load(stashHeadCommit);
9528
10948
  if (!headCommit || !stashHeadCommitObj) throw new RefNotFoundError(headRef.objectId, "Head or stash commit not found");
9529
- const stashHeadTree = stashHeadCommitObj.tree;
9530
- const stashWorkingTree = stashCommit.tree;
9531
- const mergeResult = await mergeTreesThreeWay(this.trees, stashHeadTree, stashWorkingTree, headCommit.tree);
9532
- if (mergeResult.conflicts && mergeResult.conflicts.length > 0) return {
9533
- status: "conflicts",
9534
- stashCommit: stashId,
9535
- conflicts: mergeResult.conflicts
9536
- };
9537
- let mergedIndexTree;
10949
+ const unmerged = [];
10950
+ const index = /* @__PURE__ */ new Map();
10951
+ for await (const entry of this.staging.entries()) if (entry.stage === 0) index.set(entry.path, entry);
10952
+ else unmerged.push(entry.path);
10953
+ if (unmerged.length > 0) throw new StashApplyFailedError(stashId, [...new Set(unmerged)], "error: you need to resolve your current index first");
10954
+ const ignoreCase = coreBool(this.workingCopy, "ignorecase", false);
10955
+ const base = await this.flatTree(stashHeadCommitObj.tree);
10956
+ const stashWorking = await this.flatTree(stashCommit.tree);
10957
+ const ours = new Map(index);
10958
+ let restoredIndex;
9538
10959
  if (this.restoreIndex) {
9539
- const stashIndexTree = (await this.commits.load(stashIndexCommit))?.tree ?? stashHeadTree;
9540
- const indexMergeResult = await mergeTreesThreeWay(this.trees, stashHeadTree, stashIndexTree, headCommit.tree);
9541
- if (indexMergeResult.conflicts && indexMergeResult.conflicts.length > 0) return {
10960
+ const stashIndexCommitObj = await this.commits.load(stashIndexCommit);
10961
+ const stashIndex = stashIndexCommitObj ? await this.flatTree(stashIndexCommitObj.tree) : base;
10962
+ const indexMerge = await this.mergeFlat(base, ours, stashIndex, ignoreCase);
10963
+ if (indexMerge.conflicts.size > 0) throw new StashApplyFailedError(stashId, [...indexMerge.conflicts.keys()], "error: conflicts in index. Try without --index.");
10964
+ restoredIndex = indexMerge.result;
10965
+ }
10966
+ const merge = await this.mergeFlat(base, ours, stashWorking, ignoreCase);
10967
+ const trust = worktreeModeTrust(this.workingCopy, worktree);
10968
+ const resultTree = await this.storeFlat(merge.result);
10969
+ const worktreePlan = await planTreeRestore(this.trees, this.blobs, resultTree, STASH_APPLY, {
10970
+ symlinks: true,
10971
+ ignoreCase,
10972
+ windows: worktree.capabilities?.windowsPaths === true,
10973
+ reservedNames: worktree.capabilities?.reservedNames
10974
+ });
10975
+ const conflicts = merge.conflicts;
10976
+ const changed = [.../* @__PURE__ */ new Set([
10977
+ ...ours.keys(),
10978
+ ...merge.result.keys(),
10979
+ ...conflicts.keys()
10980
+ ])].filter((p) => conflicts.has(p) || !sameEntry(ours.get(p), merge.result.get(p))).sort();
10981
+ const movedFrom = new Set([...conflicts.values()].flatMap((c) => c.moveFrom ? [c.moveFrom] : []));
10982
+ const removes = changed.filter((p) => !merge.result.has(p) && ours.has(p) && !conflicts.has(p));
10983
+ const conflictWrites = [...conflicts.values()].filter((c) => c.content || c.write);
10984
+ const writes = [...changed.filter((p) => merge.result.has(p) && !conflicts.has(p)), ...conflictWrites.map((c) => c.stagePath)];
10985
+ const local = [];
10986
+ for (const path of changed) {
10987
+ const conflict = conflicts.get(path);
10988
+ if (conflict && !conflict.content && !conflict.write && !conflict.moveFrom) continue;
10989
+ const i = index.get(path);
10990
+ if (i && await worktreeDiffers(worktree, path, i, trust)) local.push(path);
10991
+ }
10992
+ const found = await findInTheWay(worktree, {
10993
+ writes,
10994
+ removes: /* @__PURE__ */ new Set([...removes, ...movedFrom]),
10995
+ index,
10996
+ ignoreCase
10997
+ });
10998
+ const refused = overwriteMessage("merge", {
10999
+ local,
11000
+ ...found
11001
+ });
11002
+ if (refused) throw new StashApplyFailedError(stashId, [
11003
+ ...local,
11004
+ ...found.lostDirs,
11005
+ ...found.untracked
11006
+ ], refused);
11007
+ const untrackedPlan = await this.planUntrackedRestore(stashUntrackedCommit, worktreePlan, worktree);
11008
+ if (untrackedPlan) await writeTreeRestorePlan(worktree, this.blobs, untrackedPlan, STASH_APPLY, { symlinks: trust.symlinks });
11009
+ for (const conflict of conflicts.values()) {
11010
+ if (!conflict.moveFrom) continue;
11011
+ if (conflict.write?.mode === FileMode.GITLINK) {
11012
+ if (!await worktree.getEntry(conflict.stagePath)) await worktree.mkdir(conflict.stagePath);
11013
+ await removeIfEmptyDirectory(worktree, conflict.moveFrom);
11014
+ continue;
11015
+ }
11016
+ if (conflict.content) await worktree.writeContent(conflict.stagePath, conflict.content, {
11017
+ mode: conflict.mode,
11018
+ createParents: true,
11019
+ replaceInTheWay: true
11020
+ });
11021
+ else if (conflict.write) await this.writeBlob(worktree, conflict.stagePath, conflict.write, trust.symlinks);
11022
+ await worktree.remove(conflict.moveFrom);
11023
+ }
11024
+ for (const path of removes) {
11025
+ await worktree.remove(path);
11026
+ await pruneEmptyParents(worktree, path);
11027
+ }
11028
+ const writing = new Set(writes.filter((p) => merge.result.has(p)));
11029
+ await writeTreeRestorePlan(worktree, this.blobs, {
11030
+ ...worktreePlan,
11031
+ entries: worktreePlan.entries.filter((e) => writing.has(e.path)),
11032
+ gitlinks: []
11033
+ }, STASH_APPLY, {
11034
+ symlinks: trust.symlinks,
11035
+ replaceInTheWay: true
11036
+ });
11037
+ for (const conflict of conflicts.values()) {
11038
+ if (conflict.moveFrom) continue;
11039
+ if (conflict.content) await worktree.writeContent(conflict.stagePath, conflict.content, {
11040
+ mode: conflict.mode,
11041
+ createParents: true,
11042
+ replaceInTheWay: true
11043
+ });
11044
+ else if (conflict.write) await this.writeBlob(worktree, conflict.stagePath, conflict.write, trust.symlinks);
11045
+ }
11046
+ const editor = this.staging.createEditor();
11047
+ const stage = async (path, entry, stageNumber) => {
11048
+ let stats;
11049
+ if (stageNumber === 0) {
11050
+ const current = await worktree.getEntry(path);
11051
+ if (current && !current.isDirectory && await worktree.computeHash(path) === entry.objectId) stats = current;
11052
+ }
11053
+ editor.upsert({
11054
+ path,
11055
+ objectId: entry.objectId,
11056
+ mode: entry.mode,
11057
+ stage: stageNumber,
11058
+ ...entryStatOf(stats ?? {})
11059
+ });
11060
+ };
11061
+ if (conflicts.size > 0) {
11062
+ for (const path of changed) {
11063
+ const result = merge.result.get(path);
11064
+ const conflict = conflicts.get(path);
11065
+ if (conflict) {
11066
+ editor.remove(path);
11067
+ if (conflict.base) await stage(conflict.stagePath, conflict.base, 1);
11068
+ if (conflict.ours) await stage(conflict.stagePath, conflict.ours, 2);
11069
+ if (conflict.theirs) await stage(conflict.stagePath, conflict.theirs, 3);
11070
+ } else if (result) await stage(path, result, 0);
11071
+ else editor.remove(path);
11072
+ }
11073
+ await editor.finish();
11074
+ await this.staging.write();
11075
+ return {
9542
11076
  status: "conflicts",
9543
11077
  stashCommit: stashId,
9544
- conflicts: indexMergeResult.conflicts
11078
+ conflicts: [...conflicts.keys()].sort()
9545
11079
  };
9546
- mergedIndexTree = indexMergeResult.tree;
9547
11080
  }
9548
- const worktreePlan = await planTreeRestore(this.trees, this.blobs, mergeResult.tree, STASH_APPLY);
9549
- const trackedPaths = /* @__PURE__ */ new Set();
9550
- for await (const entry of this.staging.entries()) trackedPaths.add(entry.path);
9551
- const removals = [...trackedPaths].filter((path) => !worktreePlan.paths.has(path));
9552
- const untrackedPlan = await this.planUntrackedRestore(stashUntrackedCommit, worktreePlan, worktree);
9553
- await writeTreeRestorePlan(worktree, this.blobs, worktreePlan, STASH_APPLY);
9554
- for (const path of removals) await worktree.remove(path);
9555
- if (untrackedPlan) await writeTreeRestorePlan(worktree, this.blobs, untrackedPlan, STASH_APPLY);
9556
- if (mergedIndexTree !== void 0) {
9557
- await this.staging.readTree(this.trees, mergedIndexTree);
9558
- await this.staging.write();
11081
+ if (restoredIndex) for (const path of /* @__PURE__ */ new Set([...index.keys(), ...restoredIndex.keys()])) {
11082
+ const entry = restoredIndex.get(path);
11083
+ if (sameEntry(index.get(path), entry)) continue;
11084
+ if (entry) await stage(path, entry, 0);
11085
+ else editor.remove(path);
11086
+ }
11087
+ else for (const path of changed) {
11088
+ const result = merge.result.get(path);
11089
+ if (result && !ours.has(path)) await stage(path, result, 0);
9559
11090
  }
11091
+ await editor.finish();
11092
+ await this.staging.write();
9560
11093
  return {
9561
11094
  status: "ok",
9562
11095
  stashCommit: stashId
9563
11096
  };
9564
11097
  }
11098
+ /** Writes a blob to the worktree (a link as a link where the worktree has them). */
11099
+ async writeBlob(worktree, path, entry, symlinks) {
11100
+ const content = await this.blobs.load(entry.objectId);
11101
+ if (!content) throw new Error(`${STASH_APPLY} cannot restore ${path}: blob missing`);
11102
+ const mode = entry.mode === FileMode.SYMLINK && !symlinks ? FileMode.REGULAR_FILE : entry.mode;
11103
+ await worktree.writeContent(path, content, {
11104
+ mode,
11105
+ createParents: true,
11106
+ replaceInTheWay: true
11107
+ });
11108
+ }
11109
+ /**
11110
+ * git's ort merge of a stash: `base` (the stash's parent) to `ours` (the current index)
11111
+ * and to `theirs` (the stash). Renames on one side (exact, then by similarity of at least
11112
+ * {@link DEFAULT_RENAME_SCORE}%) carry the other side's change to the new path; files both
11113
+ * sides changed are merged line by line (`Updated upstream` / `Stashed changes` markers);
11114
+ * binary files, modify/delete and file/directory collisions are conflicts as in git.
11115
+ */
11116
+ async mergeFlat(baseIn, oursIn, theirsIn, ignoreCase = false) {
11117
+ const base = new Map(baseIn);
11118
+ const ours = new Map(oursIn);
11119
+ const theirs = new Map(theirsIn);
11120
+ const conflicts = /* @__PURE__ */ new Map();
11121
+ const oursRenames = await this.detectRenames(baseIn, oursIn);
11122
+ const theirsRenames = await this.detectRenames(baseIn, theirsIn);
11123
+ for (const [from, oursTo] of [...oursRenames]) {
11124
+ const theirsTo = theirsRenames.get(from);
11125
+ const original = base.get(from);
11126
+ if (theirsTo === void 0 || !original) continue;
11127
+ oursRenames.delete(from);
11128
+ theirsRenames.delete(from);
11129
+ if (theirsTo === oursTo) {
11130
+ base.delete(from);
11131
+ base.set(oursTo, original);
11132
+ continue;
11133
+ }
11134
+ const o = ours.get(oursTo);
11135
+ const t = theirs.get(theirsTo);
11136
+ if (!o || !t || theirs.has(oursTo) || ours.has(theirsTo)) continue;
11137
+ base.delete(from);
11138
+ ours.delete(oursTo);
11139
+ theirs.delete(theirsTo);
11140
+ conflicts.set(from, {
11141
+ base: original,
11142
+ stagePath: from,
11143
+ mode: original.mode
11144
+ });
11145
+ conflicts.set(oursTo, {
11146
+ ours: o,
11147
+ stagePath: oursTo,
11148
+ mode: o.mode
11149
+ });
11150
+ conflicts.set(theirsTo, {
11151
+ theirs: t,
11152
+ stagePath: theirsTo,
11153
+ mode: t.mode,
11154
+ write: t
11155
+ });
11156
+ }
11157
+ for (const [renames, side, other, sideIsOurs] of [[
11158
+ oursRenames,
11159
+ ours,
11160
+ theirs,
11161
+ true
11162
+ ], [
11163
+ theirsRenames,
11164
+ theirs,
11165
+ ours,
11166
+ false
11167
+ ]]) for (const [from, to] of renames) {
11168
+ const original = base.get(from);
11169
+ if (!original || other.has(to)) continue;
11170
+ const moved = other.get(from);
11171
+ base.delete(from);
11172
+ if (moved) {
11173
+ other.delete(from);
11174
+ other.set(to, moved);
11175
+ base.set(to, original);
11176
+ continue;
11177
+ }
11178
+ const kept = side.get(to);
11179
+ if (!kept) continue;
11180
+ side.delete(to);
11181
+ conflicts.set(to, {
11182
+ base: original,
11183
+ ...sideIsOurs ? { ours: kept } : {
11184
+ theirs: kept,
11185
+ write: kept
11186
+ },
11187
+ stagePath: to,
11188
+ mode: kept.mode
11189
+ });
11190
+ }
11191
+ const result = /* @__PURE__ */ new Map();
11192
+ const read = async (e) => {
11193
+ if (!e) return /* @__PURE__ */ new Uint8Array(0);
11194
+ const chunks = [];
11195
+ for await (const chunk of await this.blobs.load(e.objectId) ?? []) chunks.push(chunk);
11196
+ return concatBytes(chunks);
11197
+ };
11198
+ for (const path of /* @__PURE__ */ new Set([
11199
+ ...base.keys(),
11200
+ ...ours.keys(),
11201
+ ...theirs.keys()
11202
+ ])) {
11203
+ const b = base.get(path);
11204
+ const o = ours.get(path);
11205
+ const t = theirs.get(path);
11206
+ if (sameEntry(o, t) || sameEntry(b, t)) {
11207
+ if (o) result.set(path, o);
11208
+ continue;
11209
+ }
11210
+ if (sameEntry(b, o)) {
11211
+ if (t) result.set(path, t);
11212
+ continue;
11213
+ }
11214
+ if (!o || !t) {
11215
+ conflicts.set(path, {
11216
+ base: b,
11217
+ ours: o,
11218
+ theirs: t,
11219
+ stagePath: path,
11220
+ mode: (o ?? t)?.mode ?? 0,
11221
+ ...t ? { write: t } : {}
11222
+ });
11223
+ continue;
11224
+ }
11225
+ const textual = (e) => e === void 0 || e.mode === FileMode.REGULAR_FILE || e.mode === FileMode.EXECUTABLE_FILE;
11226
+ const mode = o.mode === t.mode ? o.mode : b && o.mode === b.mode ? t.mode : o.mode;
11227
+ if (textual(o) && textual(t) && textual(b)) {
11228
+ const [bb, ob, tb] = [
11229
+ await read(b),
11230
+ await read(o),
11231
+ await read(t)
11232
+ ];
11233
+ if (![
11234
+ bb,
11235
+ ob,
11236
+ tb
11237
+ ].some((bytes) => SimilarityIndex.isBinary(bytes))) {
11238
+ const lines = mergeLines(bb, ob, tb, {
11239
+ oursLabel: "Updated upstream",
11240
+ theirsLabel: "Stashed changes"
11241
+ });
11242
+ if (lines.conflicts === 0) result.set(path, {
11243
+ objectId: await this.blobs.store([lines.content]),
11244
+ mode
11245
+ });
11246
+ else conflicts.set(path, {
11247
+ base: b,
11248
+ ours: o,
11249
+ theirs: t,
11250
+ stagePath: path,
11251
+ content: lines.content,
11252
+ mode
11253
+ });
11254
+ continue;
11255
+ }
11256
+ }
11257
+ conflicts.set(path, {
11258
+ base: b,
11259
+ ours: o,
11260
+ theirs: t,
11261
+ stagePath: path,
11262
+ mode
11263
+ });
11264
+ }
11265
+ const dirsOf = (paths) => {
11266
+ const dirs = /* @__PURE__ */ new Set();
11267
+ for (const path of paths) for (let k = path.indexOf("/"); k > 0; k = path.indexOf("/", k + 1)) dirs.add(path.slice(0, k));
11268
+ return dirs;
11269
+ };
11270
+ const fold = (name) => ignoreCase ? name.toLowerCase() : name;
11271
+ const taken = /* @__PURE__ */ new Set();
11272
+ for (const map of [
11273
+ baseIn,
11274
+ oursIn,
11275
+ theirsIn,
11276
+ base,
11277
+ ours,
11278
+ theirs
11279
+ ]) {
11280
+ for (const path of map.keys()) taken.add(fold(path));
11281
+ for (const dir of dirsOf(map.keys())) taken.add(fold(dir));
11282
+ }
11283
+ const uniquePath = (path, label) => {
11284
+ let name = `${path}~${label}`;
11285
+ for (let n = 0; taken.has(fold(name)); n++) name = `${path}~${label}_${n}`;
11286
+ taken.add(fold(name));
11287
+ return name;
11288
+ };
11289
+ const outcomeDirs = dirsOf([...result.keys(), ...[...conflicts.values()].map((c) => c.stagePath)]);
11290
+ const theirsDirs = dirsOf(theirs.keys());
11291
+ const files = [...result.keys(), ...[...conflicts.entries()].filter(([, c]) => c.ours || c.theirs).map(([p]) => p)].sort();
11292
+ for (const path of files) {
11293
+ if (!outcomeDirs.has(path)) continue;
11294
+ const oursFile = theirsDirs.has(path);
11295
+ const label = oursFile ? "Updated upstream" : "Stashed changes";
11296
+ const moveFrom = oursFile && ours.has(path) ? { moveFrom: path } : {};
11297
+ const merged = result.get(path);
11298
+ if (merged) {
11299
+ result.delete(path);
11300
+ conflicts.set(path, {
11301
+ ...oursFile ? { ours: merged } : { theirs: merged },
11302
+ stagePath: uniquePath(path, label),
11303
+ mode: merged.mode,
11304
+ write: merged,
11305
+ ...moveFrom
11306
+ });
11307
+ continue;
11308
+ }
11309
+ const conflict = conflicts.get(path);
11310
+ const kept = oursFile ? conflict.ours : conflict.theirs;
11311
+ conflicts.set(path, {
11312
+ ...conflict,
11313
+ stagePath: uniquePath(path, label),
11314
+ ...kept && !conflict.content ? { write: kept } : {},
11315
+ ...moveFrom
11316
+ });
11317
+ }
11318
+ return {
11319
+ result,
11320
+ conflicts
11321
+ };
11322
+ }
11323
+ /**
11324
+ * The paths `side` renamed from `base`: a deleted path paired with an added one holding
11325
+ * the same blob, else (text files) the most similar added one scoring at least
11326
+ * {@link DEFAULT_RENAME_SCORE}, as git's rename detection.
11327
+ */
11328
+ async detectRenames(base, side) {
11329
+ const deleted = [...base.keys()].filter((p) => !side.has(p));
11330
+ const added = new Set([...side.keys()].filter((p) => !base.has(p)));
11331
+ const renames = /* @__PURE__ */ new Map();
11332
+ if (deleted.length === 0 || added.size === 0) return renames;
11333
+ for (const from of deleted) {
11334
+ const blob = base.get(from)?.objectId;
11335
+ const to = [...added].find((p) => side.get(p)?.objectId === blob);
11336
+ if (to) {
11337
+ renames.set(from, to);
11338
+ added.delete(to);
11339
+ }
11340
+ }
11341
+ const left = deleted.filter((p) => !renames.has(p));
11342
+ if (left.length === 0 || added.size === 0 || left.length * added.size > 1e3) return renames;
11343
+ const read = async (e) => {
11344
+ const chunks = [];
11345
+ for await (const chunk of await this.blobs.load(e?.objectId ?? "") ?? []) chunks.push(chunk);
11346
+ return concatBytes(chunks);
11347
+ };
11348
+ const candidates = /* @__PURE__ */ new Map();
11349
+ for (const p of added) {
11350
+ const bytes = await read(side.get(p));
11351
+ if (!SimilarityIndex.isBinary(bytes)) candidates.set(p, SimilarityIndex.create(bytes));
11352
+ }
11353
+ for (const from of left) {
11354
+ const bytes = await read(base.get(from));
11355
+ if (SimilarityIndex.isBinary(bytes)) continue;
11356
+ const index = SimilarityIndex.create(bytes);
11357
+ let best;
11358
+ let bestScore = 49;
11359
+ for (const [to, other] of candidates) {
11360
+ const score = index.score(other);
11361
+ if (score > bestScore) {
11362
+ best = to;
11363
+ bestScore = score;
11364
+ }
11365
+ }
11366
+ if (best) {
11367
+ renames.set(from, best);
11368
+ candidates.delete(best);
11369
+ }
11370
+ }
11371
+ return renames;
11372
+ }
11373
+ /** Stores a flat path map as a tree. */
11374
+ async storeFlat(entries) {
11375
+ const root = /* @__PURE__ */ new Map();
11376
+ for (const [path, entry] of entries) {
11377
+ const parts = path.split("/");
11378
+ let node = root;
11379
+ for (const part of parts.slice(0, -1)) {
11380
+ let next = node.get(part);
11381
+ if (!(next instanceof Map)) {
11382
+ next = /* @__PURE__ */ new Map();
11383
+ node.set(part, next);
11384
+ }
11385
+ node = next;
11386
+ }
11387
+ node.set(parts[parts.length - 1], entry);
11388
+ }
11389
+ const store = async (node) => {
11390
+ const list = [];
11391
+ for (const [name, value] of node) if (value instanceof Map) list.push({
11392
+ name,
11393
+ mode: FileMode.TREE,
11394
+ id: await store(value)
11395
+ });
11396
+ else list.push({
11397
+ name,
11398
+ mode: value.mode,
11399
+ id: value.objectId
11400
+ });
11401
+ return this.trees.storeTree(list);
11402
+ };
11403
+ return store(root);
11404
+ }
11405
+ /** The blobs, links and gitlinks of a tree, by path. */
11406
+ async flatTree(treeId) {
11407
+ const out = /* @__PURE__ */ new Map();
11408
+ const walk = async (id, prefix) => {
11409
+ for await (const entry of this.trees.loadTree(id)) {
11410
+ const path = prefix ? `${prefix}/${entry.name}` : entry.name;
11411
+ if (entry.mode === FileMode.TREE) await walk(entry.id, path);
11412
+ else out.set(path, {
11413
+ objectId: entry.id,
11414
+ mode: entry.mode
11415
+ });
11416
+ }
11417
+ };
11418
+ await walk(treeId, "");
11419
+ return out;
11420
+ }
9565
11421
  /**
9566
11422
  * Plan the restore of the stash's untracked files, if there are any to restore.
9567
11423
  *
@@ -9580,8 +11436,23 @@ var StashApplyCommand = class extends GitCommand {
9580
11436
  if (!this.restoreUntracked || !untrackedCommitId) return;
9581
11437
  const untrackedCommit = await this.commits.load(untrackedCommitId);
9582
11438
  if (!untrackedCommit) throw new RefNotFoundError(untrackedCommitId, "Stash untracked commit not found");
9583
- const plan = await planTreeRestore(this.trees, this.blobs, untrackedCommit.tree, STASH_APPLY);
9584
- for (const { path } of plan.entries) if (worktreePlan.paths.has(path) || await worktree.exists(path)) throw new StashApplyFailedError(untrackedCommitId, void 0, `stash apply would overwrite ${path} with a stashed untracked file`);
11439
+ const plan = await planTreeRestore(this.trees, this.blobs, untrackedCommit.tree, STASH_APPLY, {
11440
+ symlinks: true,
11441
+ ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
11442
+ windows: worktree.capabilities?.windowsPaths === true,
11443
+ reservedNames: worktree.capabilities?.reservedNames
11444
+ });
11445
+ const taken = [];
11446
+ for (const { path } of plan.entries) {
11447
+ const parts = path.split("/");
11448
+ for (let k = 1; k < parts.length; k++) {
11449
+ const prefix = parts.slice(0, k).join("/");
11450
+ const entry = await worktree.getEntry(prefix);
11451
+ if (entry && !entry.isDirectory) throw new StashApplyFailedError(untrackedCommitId, [prefix], `fatal: cannot create directory at '${prefix}': File exists\nerror: could not restore untracked files from stash`);
11452
+ }
11453
+ if (worktreePlan.paths.has(path) || await worktree.exists(path)) taken.push(path);
11454
+ }
11455
+ if (taken.length > 0) throw new StashApplyFailedError(untrackedCommitId, taken, [...taken.map((p) => `${p} already exists, no checkout`), "error: could not restore untracked files from stash"].join("\n"));
9585
11456
  return plan;
9586
11457
  }
9587
11458
  /**
@@ -9599,7 +11470,11 @@ var StashApplyCommand = class extends GitCommand {
9599
11470
  if (!ref?.objectId) throw new RefNotFoundError(refName);
9600
11471
  return ref.objectId;
9601
11472
  }
9602
- throw new RefNotFoundError(refName, `Stash entry ${index} not found (reflog not supported)`);
11473
+ const reflog = await this.refsStore.getReflog?.(baseRef);
11474
+ if (!reflog) throw new RefNotFoundError(refName, `Stash entry ${index} not found (no reflog)`);
11475
+ const entry = await reflog.getReverseEntry(index);
11476
+ if (!entry) throw new RefNotFoundError(refName, `Stash entry ${index} not found`);
11477
+ return entry.newId;
9603
11478
  }
9604
11479
  const ref = await this.refsStore.resolve(refName);
9605
11480
  if (ref?.objectId) return ref.objectId;
@@ -9608,6 +11483,195 @@ var StashApplyCommand = class extends GitCommand {
9608
11483
  }
9609
11484
  };
9610
11485
  //#endregion
11486
+ //#region src/commands/stash-working-tree.ts
11487
+ /**
11488
+ * The built-in working-tree side of `git stash push`, for a working copy with an index and
11489
+ * a worktree: the stash trees (index, worktree, untracked) as git builds them, and the
11490
+ * reset that follows (`git clean -fd` with `-u`, `git reset --hard`, and with
11491
+ * `--keep-index` the index tree checked out again).
11492
+ *
11493
+ * The index is compared with the worktree once per stash ({@link scanIndex}); the check for
11494
+ * changes, the worktree tree and the reset all use that one comparison, and the entries it
11495
+ * could only prove clean by hashing get their fresh stat in the index the reset writes.
11496
+ */
11497
+ /** Names this operation in restore failure messages. */
11498
+ const STASH = "stash";
11499
+ /**
11500
+ * The stash working-tree provider `git.stashCreate()` uses when none is set and the working
11501
+ * copy has an index and a worktree. One instance serves one stash: it compares the index
11502
+ * with the worktree once and reuses that comparison.
11503
+ */
11504
+ var WorkingCopyStashProvider = class {
11505
+ context;
11506
+ scanned;
11507
+ constructor(context) {
11508
+ this.context = context;
11509
+ }
11510
+ get source() {
11511
+ const { trees, blobs, staging, worktree, workingCopy } = this.context;
11512
+ return {
11513
+ trees,
11514
+ blobs,
11515
+ staging,
11516
+ worktree,
11517
+ trust: worktreeModeTrust(workingCopy, worktree)
11518
+ };
11519
+ }
11520
+ /** The index compared with the worktree, once. */
11521
+ scan() {
11522
+ this.scanned ??= scanIndex(this.source);
11523
+ return this.scanned;
11524
+ }
11525
+ getIndexTree() {
11526
+ return createIndexTree(this.source);
11527
+ }
11528
+ async getWorkingTree() {
11529
+ return createWorktreeTree(this.source, await this.context.headTree(), await this.scan());
11530
+ }
11531
+ async getUntrackedTree(options) {
11532
+ return (await createUntrackedTree(this.source, options)).treeId;
11533
+ }
11534
+ async hasLocalChanges(options) {
11535
+ const scan = await this.scan();
11536
+ if (await hasTrackedChanges(this.source, await this.context.headTree(), scan)) return true;
11537
+ if (!options?.includeUntracked) return false;
11538
+ for await (const file of findUntrackedFiles(this.context.worktree, (p) => scan.paths.has(p), {
11539
+ hasTrackedUnder: trackedUnder(scan.paths),
11540
+ includeIgnored: options.includeIgnored
11541
+ })) if (!file.path.endsWith("/")) return true;
11542
+ return false;
11543
+ }
11544
+ /**
11545
+ * As `git stash push` after saving: with `includeUntracked` the untracked files go
11546
+ * (`git clean -fd`, `-x` too with `includeIgnored`), then the index and the worktree's
11547
+ * tracked files are reset to HEAD (`git reset --hard`); with `keepIndex` the index tree is
11548
+ * then checked out again (`git checkout --no-overlay <index tree> -- :/`). Only paths
11549
+ * that differ are written; untracked files are kept unless removed by the clean.
11550
+ */
11551
+ async resetHard(options = {}) {
11552
+ const scan = await this.scan();
11553
+ if (options.includeUntracked) await this.clean(scan, options.includeIgnored === true);
11554
+ const headTree = await this.context.headTree();
11555
+ await this.resetToHead(scan, headTree);
11556
+ if (options.keepIndex && options.indexTree) await this.checkoutTree(headTree, options.indexTree);
11557
+ }
11558
+ /**
11559
+ * `git clean -fd` (`-x` with `ignored`): the untracked files, then the untracked
11560
+ * directories left empty, deepest first. A directory is removed only when nothing at all
11561
+ * is in it, so a nested repository (and, without `-x`, an ignored file) keeps its own.
11562
+ */
11563
+ async clean(scan, ignored) {
11564
+ const { worktree } = this.context;
11565
+ const tracked = scan.paths;
11566
+ const trackedDirs = directoriesOf(tracked);
11567
+ const untracked = [];
11568
+ const dirs = [];
11569
+ for await (const entry of worktree.walk({
11570
+ includeIgnored: ignored,
11571
+ includeDirectories: true
11572
+ })) {
11573
+ if (entry.isDirectory) {
11574
+ if (entry.mode !== FileMode.GITLINK && !trackedDirs.has(entry.path)) dirs.push(entry.path);
11575
+ continue;
11576
+ }
11577
+ if (!tracked.has(entry.path) && (ignored || !entry.isIgnored)) untracked.push(entry.path);
11578
+ }
11579
+ for (const path of untracked) await worktree.remove(path);
11580
+ dirs.sort((a, b) => b.split("/").length - a.split("/").length || (a < b ? 1 : -1));
11581
+ for (const dir of dirs) await removeDirectoryIfEmpty(worktree, dir);
11582
+ for (const path of untracked) await pruneEmptyParents(worktree, path);
11583
+ }
11584
+ /**
11585
+ * The index and the worktree's tracked files made to match HEAD, as `git reset --hard`:
11586
+ * every path whose index entry or worktree file differs is written (or removed) and staged
11587
+ * with its fresh stat; paths that already match are not touched, and those the scan only
11588
+ * proved clean by hashing get their fresh stat.
11589
+ */
11590
+ async resetToHead(scan, headTree) {
11591
+ const target = await flattenTree(this.context.trees, headTree);
11592
+ const stale = new Set(scan.unmerged);
11593
+ for (const { entry, compared } of scan.entries) {
11594
+ const t = target.get(entry.path);
11595
+ if (!t || t.id !== entry.objectId || t.mode !== entry.mode) stale.add(entry.path);
11596
+ else if (entry.mode !== FileMode.GITLINK && compared?.kind) stale.add(entry.path);
11597
+ }
11598
+ for (const path of target.keys()) if (!scan.paths.has(path)) stale.add(path);
11599
+ const refresh = refreshableEntries(scan).filter((u) => !stale.has(u.path));
11600
+ await this.write(headTree, target, stale);
11601
+ await refreshIndexStats(this.context.staging, refresh);
11602
+ }
11603
+ /** `git checkout --no-overlay <tree> -- :/` after the reset: index and worktree at `to`. */
11604
+ async checkoutTree(from, to) {
11605
+ const { trees } = this.context;
11606
+ const before = await flattenTree(trees, from);
11607
+ const target = await flattenTree(trees, to);
11608
+ const stale = /* @__PURE__ */ new Set();
11609
+ for (const [path, t] of target) {
11610
+ const b = before.get(path);
11611
+ if (!b || b.id !== t.id || b.mode !== t.mode) stale.add(path);
11612
+ }
11613
+ for (const path of before.keys()) if (!target.has(path)) stale.add(path);
11614
+ await this.write(to, target, stale);
11615
+ }
11616
+ /** Writes (or removes) the `stale` paths of the worktree and the index to `treeId`. */
11617
+ async write(treeId, target, stale) {
11618
+ if (stale.size === 0) return;
11619
+ const { trees, blobs, staging, worktree, workingCopy } = this.context;
11620
+ const trust = worktreeModeTrust(workingCopy, worktree);
11621
+ const plan = treeId ? await planTreeRestore(trees, blobs, treeId, STASH, {
11622
+ symlinks: true,
11623
+ ignoreCase: coreBool(workingCopy, "ignorecase", false),
11624
+ windows: worktree.capabilities?.windowsPaths === true,
11625
+ reservedNames: worktree.capabilities?.reservedNames,
11626
+ writing: stale
11627
+ }) : void 0;
11628
+ const editor = staging.createEditor();
11629
+ for (const path of [...stale].sort()) {
11630
+ if (target.has(path)) continue;
11631
+ editor.remove(path);
11632
+ const current = await worktree.getEntry(path);
11633
+ if (current && !current.isDirectory) {
11634
+ await worktree.remove(path);
11635
+ await pruneEmptyParents(worktree, path);
11636
+ }
11637
+ }
11638
+ if (plan) {
11639
+ const writing = plan.entries.filter((e) => stale.has(e.path));
11640
+ await writeTreeRestorePlan(worktree, blobs, {
11641
+ ...plan,
11642
+ entries: writing,
11643
+ gitlinks: []
11644
+ }, STASH, {
11645
+ symlinks: trust.symlinks,
11646
+ replaceInTheWay: true
11647
+ });
11648
+ for (const path of stale) {
11649
+ const t = target.get(path);
11650
+ if (!t) continue;
11651
+ editor.remove(path);
11652
+ const current = t.mode === FileMode.GITLINK ? void 0 : await worktree.getEntry(path);
11653
+ editor.upsert({
11654
+ path,
11655
+ objectId: t.id,
11656
+ mode: t.mode,
11657
+ stage: 0,
11658
+ size: current?.size ?? 0,
11659
+ mtime: current?.mtime ?? 0,
11660
+ ...current?.ctime !== void 0 ? { ctime: current.ctime } : {},
11661
+ ...current?.mtimeNs !== void 0 ? { mtimeNs: current.mtimeNs } : {},
11662
+ ...current?.ctimeNs !== void 0 ? { ctimeNs: current.ctimeNs } : {},
11663
+ ...current?.dev !== void 0 ? { dev: current.dev } : {},
11664
+ ...current?.ino !== void 0 ? { ino: current.ino } : {},
11665
+ ...current?.uid !== void 0 ? { uid: current.uid } : {},
11666
+ ...current?.gid !== void 0 ? { gid: current.gid } : {}
11667
+ });
11668
+ }
11669
+ }
11670
+ await editor.finish();
11671
+ await staging.write();
11672
+ }
11673
+ };
11674
+ //#endregion
9611
11675
  //#region src/commands/stash-create-command.ts
9612
11676
  /**
9613
11677
  * Get timezone offset string in Git format (+HHMM or -HHMM).
@@ -9637,22 +11701,21 @@ const MSG_UNTRACKED = "untracked files on {0}: {1} {2}";
9637
11701
  *
9638
11702
  * Based on JGit's StashCreateCommand.
9639
11703
  *
9640
- * Note: This command requires a working tree provider to access
9641
- * uncommitted changes. Without a provider, it creates a stash
9642
- * from the current HEAD state (no actual changes stashed).
11704
+ * On a working copy with an index and a worktree it stashes as `git stash push` does:
11705
+ * the index tree, the worktree tree (tracked files as they are on disk), with `-u` the
11706
+ * untracked files, then resets the index and the worktree to HEAD (keeping untracked files
11707
+ * unless they were stashed). A working copy without a worktree has nothing to stash:
11708
+ * `call()` throws `StoreNotAvailableError` unless a provider is set.
9643
11709
  *
9644
11710
  * @example
9645
11711
  * ```typescript
9646
- * // Create a stash with working tree provider
9647
- * const stashCommit = await git.stashCreate()
9648
- * .setWorkingTreeProvider(provider)
9649
- * .setMessage("WIP: feature work")
9650
- * .call();
11712
+ * // git stash push -m "WIP: feature work"
11713
+ * const stashCommit = await git.stashCreate().setMessage("WIP: feature work").call();
9651
11714
  *
9652
- * // Create stash including untracked files
11715
+ * // git stash push -u --keep-index
9653
11716
  * const stashCommit = await git.stashCreate()
9654
- * .setWorkingTreeProvider(provider)
9655
11717
  * .setIncludeUntracked(true)
11718
+ * .setKeepIndex(true)
9656
11719
  * .call();
9657
11720
  * ```
9658
11721
  */
@@ -9661,6 +11724,8 @@ var StashCreateCommand = class extends GitCommand {
9661
11724
  workingDirectoryMessage = MSG_WORKING_DIR;
9662
11725
  ref = STASH_REF;
9663
11726
  includeUntracked = false;
11727
+ includeIgnored = false;
11728
+ keepIndex = false;
9664
11729
  workingTreeProvider;
9665
11730
  customMessage;
9666
11731
  author;
@@ -9688,7 +11753,7 @@ var StashCreateCommand = class extends GitCommand {
9688
11753
  return this;
9689
11754
  }
9690
11755
  /**
9691
- * Set a custom stash message.
11756
+ * Set a custom stash message; the stash is then "On <branch>: <message>", as `git stash push -m`.
9692
11757
  *
9693
11758
  * @param message The custom message
9694
11759
  */
@@ -9699,7 +11764,8 @@ var StashCreateCommand = class extends GitCommand {
9699
11764
  }
9700
11765
  /**
9701
11766
  * Set the reference to update with the stashed commit ID.
9702
- * If null, no reference is updated.
11767
+ * If null, no reference is updated and the index and worktree are left as they are
11768
+ * (`git stash create`).
9703
11769
  *
9704
11770
  * @param ref The ref name (default: refs/stash)
9705
11771
  */
@@ -9725,6 +11791,25 @@ var StashCreateCommand = class extends GitCommand {
9725
11791
  return this.includeUntracked;
9726
11792
  }
9727
11793
  /**
11794
+ * Set whether to stash (and remove) the ignored files too, as `git stash --all`; implies
11795
+ * untracked files.
11796
+ */
11797
+ setIncludeIgnored(includeIgnored) {
11798
+ this.checkCallable();
11799
+ this.includeIgnored = includeIgnored;
11800
+ if (includeIgnored) this.includeUntracked = true;
11801
+ return this;
11802
+ }
11803
+ /**
11804
+ * Set whether the staged changes stay in the index and the worktree after the stash, as
11805
+ * `git stash push --keep-index`.
11806
+ */
11807
+ setKeepIndex(keepIndex) {
11808
+ this.checkCallable();
11809
+ this.keepIndex = keepIndex;
11810
+ return this;
11811
+ }
11812
+ /**
9728
11813
  * Set the working tree provider for accessing uncommitted changes.
9729
11814
  *
9730
11815
  * @param provider The working tree provider
@@ -9752,6 +11837,10 @@ var StashCreateCommand = class extends GitCommand {
9752
11837
  async call() {
9753
11838
  this.checkCallable();
9754
11839
  this.setCallable(false);
11840
+ const worktree = this.worktreeAccess;
11841
+ return worktree?.batch ? worktree.batch(() => this.stash()) : this.stash();
11842
+ }
11843
+ async stash() {
9755
11844
  const headRef = await this.refsStore.resolve("HEAD");
9756
11845
  if (!headRef?.objectId) throw new NoHeadError("HEAD is required to stash");
9757
11846
  const headCommit = await this.commits.load(headRef.objectId);
@@ -9763,22 +11852,20 @@ var StashCreateCommand = class extends GitCommand {
9763
11852
  timestamp: Math.floor(Date.now() / 1e3),
9764
11853
  tzOffset: getTimezoneOffset$1()
9765
11854
  };
9766
- let indexTree;
9767
- let workingTree;
9768
- let untrackedTree;
9769
- if (this.workingTreeProvider) {
9770
- if (!await this.workingTreeProvider.hasLocalChanges()) return;
9771
- indexTree = await this.workingTreeProvider.getIndexTree();
9772
- workingTree = await this.workingTreeProvider.getWorkingTree();
9773
- if (this.includeUntracked && this.workingTreeProvider.getUntrackedTree) untrackedTree = await this.workingTreeProvider.getUntrackedTree();
9774
- } else {
9775
- indexTree = headCommit.tree;
9776
- workingTree = headCommit.tree;
9777
- }
11855
+ const provider = this.workingTreeProvider ?? this.defaultProvider();
11856
+ if (!provider) throw new StoreNotAvailableError("worktree", "stash requires a working tree");
11857
+ const untrackedOptions = {
11858
+ includeUntracked: this.includeUntracked,
11859
+ includeIgnored: this.includeIgnored
11860
+ };
11861
+ if (!await provider.hasLocalChanges(untrackedOptions)) return;
11862
+ const indexTree = await provider.getIndexTree();
11863
+ const workingTree = await provider.getWorkingTree();
11864
+ const untrackedTree = this.includeUntracked && provider.getUntrackedTree ? await provider.getUntrackedTree({ includeIgnored: this.includeIgnored }) : void 0;
9778
11865
  const abbrev = headRef.objectId.substring(0, 7);
9779
11866
  const shortMessage = headCommit.message.split("\n")[0];
9780
11867
  const indexMsg = this.formatMessage(this.indexMessage, branch, abbrev, shortMessage);
9781
- const workingMsg = this.customMessage ?? this.formatMessage(this.workingDirectoryMessage, branch, abbrev, shortMessage);
11868
+ const workingMsg = this.customMessage !== void 0 ? `On ${branch}: ${this.customMessage}` : this.formatMessage(this.workingDirectoryMessage, branch, abbrev, shortMessage);
9782
11869
  const indexCommit = await this.commits.store({
9783
11870
  tree: indexTree,
9784
11871
  parents: [headRef.objectId],
@@ -9806,10 +11893,37 @@ var StashCreateCommand = class extends GitCommand {
9806
11893
  committer: author,
9807
11894
  message: workingMsg
9808
11895
  });
9809
- if (this.ref) await this.updateStashRef(this.ref, stashCommit, workingMsg);
9810
- if (this.workingTreeProvider) await this.workingTreeProvider.resetHard();
11896
+ if (!this.ref) return stashCommit;
11897
+ await this.updateStashRef(this.ref, stashCommit, workingMsg, author);
11898
+ await provider.resetHard({
11899
+ ...untrackedOptions,
11900
+ keepIndex: this.keepIndex,
11901
+ indexTree
11902
+ });
9811
11903
  return stashCommit;
9812
11904
  }
11905
+ /** The built-in provider, for a working copy with an index and a worktree. */
11906
+ defaultProvider() {
11907
+ const worktree = this.worktreeAccess;
11908
+ if (!worktree) return void 0;
11909
+ let staging;
11910
+ try {
11911
+ staging = this.staging;
11912
+ } catch {
11913
+ return;
11914
+ }
11915
+ return new WorkingCopyStashProvider({
11916
+ workingCopy: this.workingCopy,
11917
+ trees: this.trees,
11918
+ blobs: this.blobs,
11919
+ staging,
11920
+ worktree,
11921
+ headTree: async () => {
11922
+ const head = await this.refsStore.resolve("HEAD");
11923
+ return head?.objectId ? (await this.commits.load(head.objectId))?.tree : void 0;
11924
+ }
11925
+ });
11926
+ }
9813
11927
  /**
9814
11928
  * Format a message template.
9815
11929
  */
@@ -9822,16 +11936,27 @@ var StashCreateCommand = class extends GitCommand {
9822
11936
  async getCurrentBranchName() {
9823
11937
  const branch = await this.getCurrentBranch();
9824
11938
  if (branch) return branch.replace(/^refs\/heads\//, "");
9825
- return "HEAD";
9826
- }
9827
- /**
9828
- * Update the stash ref.
9829
- *
9830
- * Note: Reflog support is not part of the core Refs interface.
9831
- * Stash history is tracked via parent commit chain instead.
9832
- */
9833
- async updateStashRef(ref, commitId, _message) {
9834
- await this.refsStore.set(ref, commitId);
11939
+ return "(no branch)";
11940
+ }
11941
+ /**
11942
+ * Update the stash ref as `git stash` does (update_ref with REF_FORCE_CREATE_REFLOG):
11943
+ * a one-ref batch, under `<ref>.lock` on git files, that creates the ref's reflog and
11944
+ * appends a line with the stash commit's message, so the stash is `stash@{0}` and the
11945
+ * earlier ones move down the reflog.
11946
+ */
11947
+ async updateStashRef(ref, commitId, message, who) {
11948
+ const result = await this.refsStore.batch([{
11949
+ name: ref,
11950
+ new: commitId
11951
+ }], {
11952
+ ident: formatPersonIdent(who),
11953
+ message,
11954
+ createReflog: true
11955
+ });
11956
+ if (!result.ok) {
11957
+ const why = result.rejected.map((r) => `${r.name}: ${r.reason}`).join(", ");
11958
+ throw new Error(`Cannot save the current status: ${why}`);
11959
+ }
9835
11960
  }
9836
11961
  };
9837
11962
  //#endregion
@@ -9843,8 +11968,9 @@ var StashCreateCommand = class extends GitCommand {
9843
11968
  *
9844
11969
  * Based on JGit's StashDropCommand.
9845
11970
  *
9846
- * Note: Without reflog support in Refs, only the most recent stash (index 0)
9847
- * can be dropped. Dropping by index > 0 requires reflog support.
11971
+ * With a ref store that keeps reflogs (`getReflog`, `deleteReflogEntry`), any
11972
+ * `stash@{n}` can be dropped, as git drops it; otherwise only the most recent
11973
+ * stash (index 0).
9848
11974
  *
9849
11975
  * @example
9850
11976
  * ```typescript
@@ -9913,49 +12039,89 @@ var StashDropCommand = class extends GitCommand {
9913
12039
  const stashRef = await this.refsStore.get(STASH_REF);
9914
12040
  if (!stashRef || !("objectId" in stashRef) || !stashRef.objectId) return;
9915
12041
  if (this.dropAll) {
9916
- await this.refsStore.delete(STASH_REF);
12042
+ await this.deleteStashRef(stashRef.objectId);
9917
12043
  return;
9918
12044
  }
12045
+ const refs = this.refsStore;
12046
+ const reflog = await refs.getReflog?.(STASH_REF);
12047
+ if (reflog && refs.deleteReflogEntry) {
12048
+ if (!await reflog.getReverseEntry(this.stashRefEntry)) throw new InvalidStashIndexError(this.stashRefEntry, `stash@{${this.stashRefEntry}} does not exist`);
12049
+ const left = await refs.deleteReflogEntry(STASH_REF, this.stashRefEntry, {
12050
+ rewrite: true,
12051
+ updateRef: true
12052
+ });
12053
+ const top = await (await refs.getReflog?.(STASH_REF))?.getReverseEntry(0);
12054
+ if (left > 0 || top) return top?.newId;
12055
+ const current = await refs.get(STASH_REF);
12056
+ if (current && "objectId" in current && current.objectId) await this.deleteStashRef(current.objectId, { ignoreMismatch: true });
12057
+ return (await (await refs.getReflog?.(STASH_REF))?.getReverseEntry(0))?.newId;
12058
+ }
9919
12059
  if (this.stashRefEntry > 0) throw new InvalidStashIndexError(this.stashRefEntry, `Stash entry ${this.stashRefEntry} cannot be dropped without reflog support. Only stash@{0} can be dropped.`);
9920
- await this.refsStore.delete(STASH_REF);
12060
+ await this.deleteStashRef(stashRef.objectId);
12061
+ }
12062
+ /**
12063
+ * Delete `refs/stash` and its reflog if it still holds `expected` (git's clear_stash).
12064
+ * With `ignoreMismatch`, a ref another writer moved meanwhile is left alone.
12065
+ */
12066
+ async deleteStashRef(expected, options = {}) {
12067
+ const result = await this.refsStore.batch([{
12068
+ name: STASH_REF,
12069
+ old: expected,
12070
+ new: null,
12071
+ noDeref: true
12072
+ }]);
12073
+ const moved = result.rejected.every((r) => r.reason === "mismatch");
12074
+ if (!result.ok && !(options.ignoreMismatch && moved)) {
12075
+ const why = result.rejected.map((r) => `${r.name}: ${r.reason}`).join(", ");
12076
+ throw new Error(`Cannot drop the stash: ${why}`);
12077
+ }
9921
12078
  }
9922
12079
  };
9923
12080
  //#endregion
9924
12081
  //#region src/commands/status-command.ts
12082
+ /** The porcelain `XY` of an unmerged path, by which of stages 1-3 it has. */
12083
+ const UNMERGED_CODES = {
12084
+ 1: ["D", "D"],
12085
+ 2: ["A", "U"],
12086
+ 3: ["U", "D"],
12087
+ 4: ["U", "A"],
12088
+ 5: ["D", "U"],
12089
+ 6: ["A", "A"],
12090
+ 7: ["U", "U"]
12091
+ };
12092
+ const S_IFMT = 61440;
12093
+ const typeOf = (mode) => mode & S_IFMT;
9925
12094
  /**
9926
- * Shows the staging area status compared to HEAD.
12095
+ * Shows the working tree status, as `git status`: the index against HEAD (staged changes),
12096
+ * the worktree against the index (unstaged changes: modified, deleted, type changed),
12097
+ * unmerged entries, untracked files and, on request, ignored ones.
9927
12098
  *
9928
- * This is a simplified version for repositories without working trees,
9929
- * focusing on staged changes and conflicts.
12099
+ * Worktree files are compared with the index through the stat it recorded: a file whose
12100
+ * size and modification time still match is not read, unless its entry is racily clean
12101
+ * (modified at or after the index was written), which is re-hashed as git does. Links are
12102
+ * compared as links (mode 120000), the executable bit only where `core.filemode` trusts it,
12103
+ * and the ignore rules are read afresh for each status. Untracked files are listed one by
12104
+ * one (`--untracked-files=all`). Renames are not detected.
9930
12105
  *
9931
- * Equivalent to `git status` but only for staged changes.
12106
+ * Without a worktree only the index is compared with HEAD.
9932
12107
  *
9933
- * Based on JGit's StatusCommand (staged-only subset).
12108
+ * Based on JGit's StatusCommand.
9934
12109
  *
9935
12110
  * @example
9936
12111
  * ```typescript
9937
- * // Get repository status
9938
12112
  * const status = await git.status().call();
9939
- *
9940
- * // Check if clean
9941
- * if (status.isClean()) {
9942
- * console.log("Nothing to commit");
9943
- * }
9944
- *
9945
- * // Check for changes
9946
- * console.log("Added:", status.added);
9947
- * console.log("Changed:", status.changed);
9948
- * console.log("Removed:", status.removed);
9949
- * console.log("Conflicting:", status.conflicting);
9950
- *
9951
- * // Filter by path
9952
- * const subStatus = await git.status()
9953
- * .addPath("src/")
9954
- * .call();
12113
+ * if (status.isClean()) console.log("nothing to commit, working tree clean");
12114
+ * console.log("Staged:", status.added, status.changed, status.removed);
12115
+ * console.log("Unstaged:", status.modified, status.missing);
12116
+ * console.log("Untracked:", status.untracked);
12117
+ * // the lines of `git status --porcelain`
12118
+ * console.log(formatStatusPorcelain(status));
9955
12119
  * ```
9956
12120
  */
9957
12121
  var StatusCommand = class extends GitCommand {
9958
12122
  paths = [];
12123
+ showIgnored = false;
12124
+ showUntracked = true;
9959
12125
  /**
9960
12126
  * Add a path filter.
9961
12127
  *
@@ -9968,44 +12134,188 @@ var StatusCommand = class extends GitCommand {
9968
12134
  this.paths.push(path);
9969
12135
  return this;
9970
12136
  }
12137
+ /**
12138
+ * Whether to report the ignored files the index does not track (`--ignored`). Off by
12139
+ * default.
12140
+ */
12141
+ setIgnored(ignored) {
12142
+ this.checkCallable();
12143
+ this.showIgnored = ignored;
12144
+ return this;
12145
+ }
12146
+ /**
12147
+ * Whether to report untracked files (`--untracked-files=all`, the default, or `=no`).
12148
+ */
12149
+ setUntracked(untracked) {
12150
+ this.checkCallable();
12151
+ this.showUntracked = untracked;
12152
+ return this;
12153
+ }
9971
12154
  async call() {
9972
12155
  this.checkCallable();
9973
12156
  this.setCallable(false);
9974
- const conflicting = /* @__PURE__ */ new Set();
9975
- for (const path of await this.staging.getConflictedPaths()) if (this.matchesPath(path)) conflicting.add(path);
9976
- const headEntries = /* @__PURE__ */ new Map();
12157
+ const worktree = this.worktreeAccess;
12158
+ return worktree?.batch ? worktree.batch(() => this.compute(worktree)) : this.compute(worktree);
12159
+ }
12160
+ async compute(worktree) {
12161
+ const head = /* @__PURE__ */ new Map();
9977
12162
  const headRef = await this.refsStore.resolve("HEAD");
9978
- if (headRef?.objectId) try {
9979
- const headCommit = await this.commits.load(headRef.objectId);
9980
- if (headCommit) await this.collectTreeEntries(headCommit.tree, "", headEntries);
9981
- } catch {}
9982
- const stagingEntries = /* @__PURE__ */ new Map();
9983
- for await (const entry of this.staging.entries()) if (entry.stage === MergeStage.MERGED) stagingEntries.set(entry.path, {
9984
- path: entry.path,
9985
- mode: entry.mode,
9986
- id: entry.objectId
9987
- });
12163
+ if (headRef?.objectId) {
12164
+ const headCommit = await this.commits.load(headRef.objectId).catch(() => void 0);
12165
+ if (headCommit) await this.collectTreeEntries(headCommit.tree, "", head);
12166
+ }
9988
12167
  const added = /* @__PURE__ */ new Set();
9989
12168
  const changed = /* @__PURE__ */ new Set();
9990
12169
  const removed = /* @__PURE__ */ new Set();
9991
- for (const [path, stagingEntry] of stagingEntries) {
9992
- if (!this.matchesPath(path)) continue;
9993
- const headEntry = headEntries.get(path);
9994
- if (!headEntry) added.add(path);
9995
- else if (headEntry.id !== stagingEntry.id || headEntry.mode !== stagingEntry.mode) changed.add(path);
12170
+ const conflicting = /* @__PURE__ */ new Set();
12171
+ const conflictingStageState = /* @__PURE__ */ new Map();
12172
+ const modified = /* @__PURE__ */ new Set();
12173
+ const missing = /* @__PURE__ */ new Set();
12174
+ const untracked = /* @__PURE__ */ new Set();
12175
+ const ignored = /* @__PURE__ */ new Set();
12176
+ const files = [];
12177
+ const trust = worktree ? worktreeModeTrust(this.workingCopy, worktree) : void 0;
12178
+ const indexTime = this.staging.getUpdateTime();
12179
+ const tracked = /* @__PURE__ */ new Set();
12180
+ const refresh = [];
12181
+ const unmerged = /* @__PURE__ */ new Map();
12182
+ for await (const entry of this.staging.entries()) {
12183
+ tracked.add(entry.path);
12184
+ if (!this.matchesPath(entry.path)) continue;
12185
+ if (entry.stage !== 0) {
12186
+ const stages = unmerged.get(entry.path) ?? [
12187
+ void 0,
12188
+ void 0,
12189
+ void 0
12190
+ ];
12191
+ stages[entry.stage - 1] = {
12192
+ mode: entry.mode,
12193
+ id: entry.objectId
12194
+ };
12195
+ unmerged.set(entry.path, stages);
12196
+ continue;
12197
+ }
12198
+ const h = head.get(entry.path);
12199
+ const staged = {
12200
+ mode: entry.mode,
12201
+ id: entry.objectId
12202
+ };
12203
+ let x = " ";
12204
+ if (!h) {
12205
+ if (!entry.intentToAdd) {
12206
+ x = "A";
12207
+ added.add(entry.path);
12208
+ }
12209
+ } else if (h.id !== entry.objectId || h.mode !== entry.mode) {
12210
+ x = typeOf(h.mode) === typeOf(entry.mode) ? "M" : "T";
12211
+ changed.add(entry.path);
12212
+ }
12213
+ let y = " ";
12214
+ let worktreeMode = entry.mode;
12215
+ let commitChanged = false;
12216
+ if (worktree && !entry.skipWorktree && !entry.assumeValid) {
12217
+ const result = await compareWithWorktree(worktree, entry, {
12218
+ trust,
12219
+ indexTime
12220
+ });
12221
+ worktreeMode = result.worktreeMode;
12222
+ const update = statUpdateOf(entry, result);
12223
+ if (update) refresh.push(update);
12224
+ if (entry.mode === FileMode.GITLINK && result.kind === "modified") commitChanged = true;
12225
+ if (result.kind === "deleted") {
12226
+ y = "D";
12227
+ missing.add(entry.path);
12228
+ } else if (result.kind) {
12229
+ y = result.kind === "typechange" ? "T" : "M";
12230
+ modified.add(entry.path);
12231
+ } else if (entry.intentToAdd) {
12232
+ y = "A";
12233
+ added.add(entry.path);
12234
+ }
12235
+ }
12236
+ if (x !== " " || y !== " ") {
12237
+ const ita = entry.intentToAdd;
12238
+ files.push({
12239
+ path: entry.path,
12240
+ index: x,
12241
+ worktree: y,
12242
+ head: ita && y === "D" ? staged : h,
12243
+ staged: ita && y === "A" ? void 0 : staged,
12244
+ worktreeMode,
12245
+ ...commitChanged ? { submoduleCommitChanged: true } : {}
12246
+ });
12247
+ }
12248
+ }
12249
+ for (const [path, stages] of unmerged) {
12250
+ conflicting.add(path);
12251
+ const [base, ours, theirs] = stages;
12252
+ conflictingStageState.set(path, getStageState(!!base, !!ours, !!theirs));
12253
+ const [x, y] = UNMERGED_CODES[(base ? 1 : 0) | (ours ? 2 : 0) | (theirs ? 4 : 0)];
12254
+ let worktreeMode;
12255
+ const current = worktree ? await worktree.getEntry(path) : void 0;
12256
+ if (current && !current.isDirectory && trust) worktreeMode = modeFromWorktree(current.mode, (ours ?? theirs ?? base)?.mode, trust);
12257
+ files.push({
12258
+ path,
12259
+ index: x,
12260
+ worktree: y,
12261
+ worktreeMode,
12262
+ stages: [
12263
+ base,
12264
+ ours,
12265
+ theirs
12266
+ ]
12267
+ });
12268
+ }
12269
+ for (const [path, h] of head) {
12270
+ if (tracked.has(path) || !this.matchesPath(path)) continue;
12271
+ removed.add(path);
12272
+ files.push({
12273
+ path,
12274
+ index: "D",
12275
+ worktree: " ",
12276
+ head: h
12277
+ });
9996
12278
  }
9997
- for (const [path] of headEntries) {
9998
- if (!this.matchesPath(path)) continue;
9999
- if (!stagingEntries.has(path)) removed.add(path);
12279
+ if (worktree && this.showUntracked) for await (const file of findUntrackedFiles(worktree, (p) => tracked.has(p), {
12280
+ hasTrackedUnder: trackedUnder(tracked),
12281
+ includeIgnored: this.showIgnored,
12282
+ filter: (p) => this.matchesPath(p)
12283
+ })) if (file.ignored) {
12284
+ ignored.add(file.path);
12285
+ files.push({
12286
+ path: file.path,
12287
+ index: "!",
12288
+ worktree: "!"
12289
+ });
12290
+ } else {
12291
+ untracked.add(file.path);
12292
+ files.push({
12293
+ path: file.path,
12294
+ index: "?",
12295
+ worktree: "?"
12296
+ });
10000
12297
  }
10001
- return new StatusImpl(added, changed, removed, conflicting);
12298
+ await refreshIndexStats(this.staging, refresh);
12299
+ return new StatusImpl(added, changed, removed, conflicting, {
12300
+ modified,
12301
+ missing,
12302
+ untracked,
12303
+ ignored,
12304
+ conflictingStageState,
12305
+ files
12306
+ });
10002
12307
  }
10003
12308
  /**
10004
12309
  * Check if a path matches the configured path filters.
10005
12310
  */
10006
12311
  matchesPath(path) {
10007
12312
  if (this.paths.length === 0) return true;
10008
- for (const filterPath of this.paths) if (path === filterPath || path.startsWith(`${filterPath}/`) || filterPath.startsWith(`${path}/`)) return true;
12313
+ const p = path.endsWith("/") ? path.slice(0, -1) : path;
12314
+ for (const raw of this.paths) {
12315
+ const filterPath = raw.replace(/\/+$/, "");
12316
+ if (filterPath === "" || filterPath === ".") return true;
12317
+ if (p === filterPath || p.startsWith(`${filterPath}/`) || filterPath.startsWith(`${p}/`)) return true;
12318
+ }
10009
12319
  return false;
10010
12320
  }
10011
12321
  /**
@@ -10016,7 +12326,6 @@ var StatusCommand = class extends GitCommand {
10016
12326
  const path = prefix ? `${prefix}/${entry.name}` : entry.name;
10017
12327
  if (entry.mode === FileMode.TREE) await this.collectTreeEntries(entry.id, path, entries);
10018
12328
  else entries.set(path, {
10019
- path,
10020
12329
  mode: entry.mode,
10021
12330
  id: entry.id
10022
12331
  });
@@ -10275,4 +12584,4 @@ var ListTagCommand = class extends GitCommand {
10275
12584
  }
10276
12585
  };
10277
12586
  //#endregion
10278
- export { GitCommand as $, DiffCommand as A, CleanCommand as B, MergeCommand as C, InitCommand as D, RevFilter as E, FetchCommand as F, CreateBranchCommand as G, CheckoutCommand as H, TagOption as I, RenameBranchCommand as J, DeleteBranchCommand as K, toTagMode as L, DescribeCommand as M, CommitCommand as N, Git as O, CloneCommand as P, AddCommand as Q, toTrackingRefUpdate as R, PackRefsCommand as S, LogCommand as T, CheckoutStage as U, CherryPickCommand as V, CheckoutStatus as W, ResetMode as X, ListBranchMode as Y, BlameCommand as Z, ReflogCommand as _, StashDropCommand as a, PushCommand as b, STASH_REF as c, RevertCommand as d, ResetCommand as f, RemoteSetUrlCommand as g, RemoteRemoveCommand as h, StatusCommand as i, formatDiffEntry as j, GarbageCollectCommand as k, StashListCommand as l, RemoteListCommand as m, ListTagCommand as n, StashCreateCommand as o, RemoteAddCommand as p, ListBranchCommand as q, TagCommand as r, StashApplyCommand as s, DeleteTagCommand as t, RmCommand as u, RebaseCommand as v, LsRemoteCommand as w, PullCommand as x, RebaseOperation as y, TransportCommand as z };
12587
+ export { ResetMode as $, InitCommand as A, toTagMode as B, PushCommand as C, LsRemoteCommand as D, MergeCommand as E, DescribeCommand as F, CheckoutCommand as G, TransportCommand as H, CommitCommand as I, CreateBranchCommand as J, CheckoutStage as K, CloneCommand as L, GarbageCollectCommand as M, DiffCommand as N, LogCommand as O, formatDiffEntry as P, ListBranchMode as Q, FetchCommand as R, RebaseOperation as S, PackRefsCommand as T, CleanCommand as U, toTrackingRefUpdate as V, CherryPickCommand as W, ListBranchCommand as X, DeleteBranchCommand as Y, RenameBranchCommand as Z, RemoteRenameCommand as _, StashDropCommand as a, ReflogCommand as b, StashApplyCommand as c, RmCommand as d, BlameCommand as et, RevertCommand as f, RemoteRemoveCommand as g, RemoteListCommand as h, StatusCommand as i, Git as j, RevFilter as k, STASH_REF as l, RemoteAddCommand as m, ListTagCommand as n, GitCommand as nt, StashCreateCommand as o, ResetCommand as p, CheckoutStatus as q, TagCommand as r, WorkingCopyStashProvider as s, DeleteTagCommand as t, AddCommand as tt, StashListCommand as u, RemoteSetHeadCommand as v, PullCommand as w, RebaseCommand as x, RemoteSetUrlCommand as y, TagOption as z };