@statewalker/vcs-commands 0.3.2 → 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 (133) hide show
  1. package/README.md +19 -0
  2. package/dist/commands/add-command.d.ts +0 -6
  3. package/dist/commands/add-command.d.ts.map +1 -1
  4. package/dist/commands/blame-command.d.ts +14 -0
  5. package/dist/commands/blame-command.d.ts.map +1 -1
  6. package/dist/commands/branch-command.d.ts.map +1 -1
  7. package/dist/commands/checkout-command.d.ts +7 -24
  8. package/dist/commands/checkout-command.d.ts.map +1 -1
  9. package/dist/commands/clean-command.d.ts +34 -4
  10. package/dist/commands/clean-command.d.ts.map +1 -1
  11. package/dist/commands/clone-command.d.ts +61 -21
  12. package/dist/commands/clone-command.d.ts.map +1 -1
  13. package/dist/commands/core-config.d.ts +16 -0
  14. package/dist/commands/core-config.d.ts.map +1 -0
  15. package/dist/commands/fetch-command.d.ts +104 -37
  16. package/dist/commands/fetch-command.d.ts.map +1 -1
  17. package/dist/commands/index.d.ts +1 -0
  18. package/dist/commands/index.d.ts.map +1 -1
  19. package/dist/commands/index.js +2 -2
  20. package/dist/commands/init-command.d.ts.map +1 -1
  21. package/dist/commands/merge-command.d.ts +15 -2
  22. package/dist/commands/merge-command.d.ts.map +1 -1
  23. package/dist/commands/push-command.d.ts +58 -25
  24. package/dist/commands/push-command.d.ts.map +1 -1
  25. package/dist/commands/remote-command.d.ts +115 -6
  26. package/dist/commands/remote-command.d.ts.map +1 -1
  27. package/dist/commands/reset-command.d.ts.map +1 -1
  28. package/dist/commands/stash-apply-command.d.ts +35 -13
  29. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  30. package/dist/commands/stash-create-command.d.ts +59 -25
  31. package/dist/commands/stash-create-command.d.ts.map +1 -1
  32. package/dist/commands/stash-drop-command.d.ts +8 -2
  33. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  34. package/dist/commands/stash-list-command.d.ts +2 -4
  35. package/dist/commands/stash-list-command.d.ts.map +1 -1
  36. package/dist/commands/stash-working-tree.d.ts +72 -0
  37. package/dist/commands/stash-working-tree.d.ts.map +1 -0
  38. package/dist/commands/status-command.d.ts +29 -22
  39. package/dist/commands/status-command.d.ts.map +1 -1
  40. package/dist/commands/tag-command.d.ts.map +1 -1
  41. package/dist/commands/tree-restore.d.ts +52 -5
  42. package/dist/commands/tree-restore.d.ts.map +1 -1
  43. package/dist/commands/worktree-overwrite-checks.d.ts +64 -0
  44. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -0
  45. package/dist/{commands-COO4tJhv.js → commands-CsLNyvZ1.js} +3370 -1057
  46. package/dist/core-commands/add.command.impl.d.ts +0 -4
  47. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  48. package/dist/core-commands/index.d.ts +1 -3
  49. package/dist/core-commands/index.d.ts.map +1 -1
  50. package/dist/core-commands/store-worktree-file.d.ts +6 -0
  51. package/dist/core-commands/store-worktree-file.d.ts.map +1 -0
  52. package/dist/errors/checkout-errors.d.ts +13 -0
  53. package/dist/errors/checkout-errors.d.ts.map +1 -1
  54. package/dist/errors/index.js +18 -1
  55. package/dist/git-command.d.ts +10 -1
  56. package/dist/git-command.d.ts.map +1 -1
  57. package/dist/git.d.ts +21 -3
  58. package/dist/git.d.ts.map +1 -1
  59. package/dist/index.js +4 -4
  60. package/dist/remote-config/index.d.ts +1 -0
  61. package/dist/remote-config/index.d.ts.map +1 -1
  62. package/dist/remote-config/remote-config-store.d.ts +22 -0
  63. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  64. package/dist/remote-config/remote-refs.d.ts +37 -0
  65. package/dist/remote-config/remote-refs.d.ts.map +1 -0
  66. package/dist/results/clone-result.d.ts +6 -0
  67. package/dist/results/clone-result.d.ts.map +1 -1
  68. package/dist/results/diff-formatter.d.ts +14 -7
  69. package/dist/results/diff-formatter.d.ts.map +1 -1
  70. package/dist/results/fetch-result.d.ts +16 -1
  71. package/dist/results/fetch-result.d.ts.map +1 -1
  72. package/dist/results/index.js +28 -23
  73. package/dist/results/push-result.d.ts +9 -2
  74. package/dist/results/push-result.d.ts.map +1 -1
  75. package/dist/results/status-result.d.ts +91 -20
  76. package/dist/results/status-result.d.ts.map +1 -1
  77. package/dist/{status-result-BwAyxq6R.js → status-result-BpyUK1Sg.js} +115 -5
  78. package/dist/transport-command.d.ts +12 -0
  79. package/dist/transport-command.d.ts.map +1 -1
  80. package/package.json +14 -12
  81. package/src/commands/add-command.ts +23 -30
  82. package/src/commands/blame-command.ts +41 -0
  83. package/src/commands/branch-command.ts +2 -53
  84. package/src/commands/checkout-command.ts +205 -127
  85. package/src/commands/clean-command.ts +187 -81
  86. package/src/commands/clone-command.ts +334 -137
  87. package/src/commands/core-config.ts +41 -0
  88. package/src/commands/fetch-command.ts +536 -211
  89. package/src/commands/gc-command.ts +1 -1
  90. package/src/commands/index.ts +1 -0
  91. package/src/commands/init-command.ts +108 -11
  92. package/src/commands/merge-command.ts +60 -27
  93. package/src/commands/pack-refs-command.ts +2 -2
  94. package/src/commands/push-command.ts +242 -308
  95. package/src/commands/reflog-command.ts +2 -2
  96. package/src/commands/remote-command.ts +429 -19
  97. package/src/commands/reset-command.ts +18 -5
  98. package/src/commands/stash-apply-command.ts +632 -97
  99. package/src/commands/stash-create-command.ts +142 -62
  100. package/src/commands/stash-drop-command.ts +53 -5
  101. package/src/commands/stash-list-command.ts +10 -4
  102. package/src/commands/stash-working-tree.ts +243 -0
  103. package/src/commands/status-command.ts +197 -91
  104. package/src/commands/tag-command.ts +2 -53
  105. package/src/commands/tree-restore.ts +143 -18
  106. package/src/commands/worktree-overwrite-checks.ts +215 -0
  107. package/src/core-commands/add.command.impl.ts +15 -20
  108. package/src/core-commands/index.ts +1 -8
  109. package/src/core-commands/store-worktree-file.ts +5 -0
  110. package/src/errors/checkout-errors.ts +20 -0
  111. package/src/git-command.ts +42 -1
  112. package/src/git.ts +30 -2
  113. package/src/remote-config/index.ts +1 -0
  114. package/src/remote-config/remote-config-store.ts +95 -8
  115. package/src/remote-config/remote-refs.ts +103 -0
  116. package/src/results/clone-result.ts +6 -0
  117. package/src/results/diff-formatter.ts +31 -38
  118. package/src/results/fetch-result.ts +16 -1
  119. package/src/results/push-result.ts +9 -2
  120. package/src/results/status-result.ts +212 -29
  121. package/src/transport-command.ts +18 -0
  122. package/dist/core-commands/checkout.command.d.ts +0 -103
  123. package/dist/core-commands/checkout.command.d.ts.map +0 -1
  124. package/dist/core-commands/checkout.command.impl.d.ts +0 -114
  125. package/dist/core-commands/checkout.command.impl.d.ts.map +0 -1
  126. package/dist/pack-import/index.d.ts +0 -8
  127. package/dist/pack-import/index.d.ts.map +0 -1
  128. package/dist/pack-import/pack-import.d.ts +0 -11
  129. package/dist/pack-import/pack-import.d.ts.map +0 -1
  130. package/src/core-commands/checkout.command.impl.ts +0 -586
  131. package/src/core-commands/checkout.command.ts +0 -125
  132. package/src/pack-import/index.ts +0 -8
  133. package/src/pack-import/pack-import.ts +0 -24
@@ -1,15 +1,32 @@
1
+ import { isSymbolicRef, isValidRefName, type OwnReflogLine } from "@statewalker/vcs-core";
1
2
  import {
3
+ expandFromDestination,
4
+ lsRefs,
5
+ matchDestination,
6
+ openHttpConnection,
7
+ parseRefSpec,
8
+ type RefSpec,
9
+ type RemoteRef as TransportRemoteRef,
10
+ } from "@statewalker/vcs-transport";
11
+
12
+ import {
13
+ InvalidArgumentError,
14
+ InvalidRemoteError,
2
15
  MissingArgumentError,
16
+ RefNotFoundError,
3
17
  RemoteAlreadyExistsError,
4
18
  RemoteNotFoundError,
5
19
  } from "../errors/index.js";
6
20
  import { GitCommand } from "../git-command.js";
7
21
  import {
8
22
  defaultFetchRefspec,
23
+ deleteRefs,
9
24
  listRemoteNames,
25
+ moveRefs,
10
26
  type RemoteConfig,
11
27
  RemoteConfigStore,
12
28
  } from "../remote-config/index.js";
29
+ import { TransportCommand } from "../transport-command.js";
13
30
 
14
31
  export type { RemoteConfig };
15
32
 
@@ -141,6 +158,14 @@ export class RemoteAddCommand extends GitCommand<RemoteConfig> {
141
158
  *
142
159
  * Based on JGit's RemoteRemoveCommand.
143
160
  *
161
+ * As git's builtin/remote.c `rm`: the branches whose upstream is the remote lose
162
+ * `branch.<b>.remote` and `branch.<b>.merge`, those pushing to it `branch.<b>.pushRemote`;
163
+ * the remote-tracking refs its fetch refspecs map to (under `refs/remotes/`, and not mapped
164
+ * by another remote too) are deleted with their reflogs, `refs/remotes/<name>/HEAD`
165
+ * included; `remote.pushDefault` naming it is unset; the `[remote "<name>"]` section goes.
166
+ * Local branches a refspec maps to are kept, and git's note naming them is in
167
+ * {@link getMessages}. A remote without a config section is refused, as git refuses it.
168
+ *
144
169
  * @example
145
170
  * ```typescript
146
171
  * await git.remoteRemove()
@@ -148,8 +173,9 @@ export class RemoteAddCommand extends GitCommand<RemoteConfig> {
148
173
  * .call();
149
174
  * ```
150
175
  */
151
- export class RemoteRemoveCommand extends GitCommand<RemoteConfig | undefined> {
176
+ export class RemoteRemoveCommand extends GitCommand<RemoteConfig> {
152
177
  private remoteName?: string;
178
+ private messages: string[] = [];
153
179
 
154
180
  /**
155
181
  * Set the remote name to remove.
@@ -169,48 +195,284 @@ export class RemoteRemoveCommand extends GitCommand<RemoteConfig | undefined> {
169
195
  return this.remoteName;
170
196
  }
171
197
 
198
+ /**
199
+ * What git prints after the removal (on stderr): the note on local branches a refspec
200
+ * maps to, which are not removed. Empty until {@link call} has run.
201
+ */
202
+ getMessages(): string[] {
203
+ return [...this.messages];
204
+ }
205
+
172
206
  /**
173
207
  * Execute the remote remove operation.
174
208
  *
175
- * Drops both halves of a remote: its config section and its tracking refs.
176
- * A remote that has only one of the two is still removable.
177
- *
178
- * @returns Removed remote config, or undefined if not found
209
+ * @returns Removed remote config
210
+ * @throws RemoteNotFoundError when the remote has no config section (git: "No such
211
+ * remote: '<name>'"); nothing is changed then
179
212
  */
180
- async call(): Promise<RemoteConfig | undefined> {
213
+ async call(): Promise<RemoteConfig> {
181
214
  this.checkCallable();
182
215
  this.setCallable(false);
183
216
 
184
- if (!this.remoteName) {
217
+ const name = this.remoteName;
218
+ if (!name) {
185
219
  throw new MissingArgumentError("remoteName", "Remote name must be specified");
186
220
  }
187
221
 
188
222
  const store = RemoteConfigStore.from(this.workingCopy);
189
- const configured = store.isConfigured(this.remoteName);
223
+ if (!store.isConfigured(name)) {
224
+ throw new RemoteNotFoundError(name, `No such remote: '${name}'`);
225
+ }
190
226
 
227
+ // Read before removing: this is what we report back.
228
+ const removed = store.read(name);
229
+
230
+ // the refs its refspecs map to, unless another remote maps them too (add_branch_for_removal)
231
+ const own = store.configuredFetchRefspecs(name).map((spec) => parseRefSpec(spec));
232
+ const others = store
233
+ .configuredNames()
234
+ .filter((other) => other !== name)
235
+ .map((other) => store.configuredFetchRefspecs(other).map((spec) => parseRefSpec(spec)));
191
236
  const refsToDelete: string[] = [];
192
- for await (const ref of this.refsStore.list(`refs/remotes/${this.remoteName}/`)) {
237
+ const skipped: string[] = [];
238
+ for await (const ref of this.refsStore.list("refs/")) {
239
+ if (!tracks(own, ref.name)) continue;
240
+ if (others.some((specs) => tracks(specs, ref.name))) continue;
241
+ // refs outside refs/remotes/ are kept, as git; local branches are named in a note
242
+ if (!ref.name.startsWith("refs/remotes/")) {
243
+ if (ref.name.startsWith("refs/heads/")) skipped.push(ref.name.slice("refs/heads/".length));
244
+ continue;
245
+ }
193
246
  refsToDelete.push(ref.name);
194
247
  }
195
248
 
196
- if (!configured && refsToDelete.length === 0) {
197
- return undefined;
249
+ for (const branch of store.subsections("branch")) {
250
+ if (store.value(`branch.${branch}.remote`) === name) {
251
+ store.unset(`branch.${branch}.remote`);
252
+ store.unset(`branch.${branch}.merge`);
253
+ }
254
+ if (store.value(`branch.${branch}.pushRemote`) === name) {
255
+ store.unset(`branch.${branch}.pushRemote`);
256
+ }
198
257
  }
199
258
 
200
- // Read before removing: this is what we report back.
201
- const removed = store.read(this.remoteName);
259
+ await deleteRefs(this.refsStore, refsToDelete, "remote: remove");
260
+ if (skipped.length > 0) {
261
+ this.messages.push(
262
+ skipped.length === 1
263
+ ? "Note: A branch outside the refs/remotes/ hierarchy was not removed;\nto delete it, use:"
264
+ : "Note: Some branches outside the refs/remotes/ hierarchy were not removed;\nto delete them, use:",
265
+ ...skipped.map((branch) => ` git branch -d ${branch}`),
266
+ );
267
+ }
268
+
269
+ store.remove(name);
270
+ // handle_push_default: a local remote.pushDefault naming it is unset
271
+ if (store.value("remote.pushDefault") === name) store.unset("remote.pushDefault");
272
+ await store.save();
273
+
274
+ return removed;
275
+ }
276
+ }
277
+
278
+ /** What {@link RemoteRenameCommand} did. */
279
+ export interface RemoteRenameResult {
280
+ /** The remote under its new name */
281
+ remote: RemoteConfig;
282
+ /**
283
+ * git's warnings: each fetch refspec that does not write under `refs/remotes/<old>/`
284
+ * is kept as it is ("Not updating non-default fetch refspec ...")
285
+ */
286
+ warnings: string[];
287
+ }
288
+
289
+ /**
290
+ * Rename a remote.
291
+ *
292
+ * Equivalent to `git remote rename <old> <new>`.
293
+ *
294
+ * As git's builtin/remote.c `mv`: the `[remote "<old>"]` section is renamed in place; each
295
+ * fetch refspec writing under `refs/remotes/<old>/` is rewritten to `refs/remotes/<new>/`,
296
+ * the others kept with git's warning; `branch.<b>.remote` and `branch.<b>.pushRemote`
297
+ * naming the remote are updated. When a refspec was rewritten, the refs under
298
+ * `refs/remotes/<old>/` move to `refs/remotes/<new>/` in one batch, each with its reflog
299
+ * and a `remote: renamed <old ref> to <new ref>` line, symbolic refs (`HEAD`) re-pointed
300
+ * at the moved refs, and `remote.pushDefault` follows the new name.
301
+ *
302
+ * @example
303
+ * ```typescript
304
+ * const { remote, warnings } = await git.remoteRename().setOldName("origin").setNewName("upstream").call();
305
+ * ```
306
+ */
307
+ export class RemoteRenameCommand extends GitCommand<RemoteRenameResult> {
308
+ private oldName?: string;
309
+ private newName?: string;
310
+
311
+ /** Set the remote to rename. */
312
+ setOldName(name: string): this {
313
+ this.checkCallable();
314
+ this.oldName = name;
315
+ return this;
316
+ }
317
+
318
+ /** Set the remote's new name. */
319
+ setNewName(name: string): this {
320
+ this.checkCallable();
321
+ this.newName = name;
322
+ return this;
323
+ }
324
+
325
+ /**
326
+ * @throws RemoteNotFoundError if the remote has no config section (git: "No such remote: '<old>'")
327
+ * @throws RemoteAlreadyExistsError if the new name is taken (git: "remote <new> already exists.")
328
+ * @throws InvalidArgumentError for an invalid new name (git: "'<new>' is not a valid remote name")
329
+ */
330
+ async call(): Promise<RemoteRenameResult> {
331
+ this.checkCallable();
332
+ this.setCallable(false);
333
+ const { oldName, newName } = this;
334
+ if (!oldName) throw new MissingArgumentError("oldName", "Old remote name must be specified");
335
+ if (!newName) throw new MissingArgumentError("newName", "New remote name must be specified");
202
336
 
203
- for (const refName of refsToDelete) {
204
- await this.refsStore.delete(refName);
337
+ const store = RemoteConfigStore.from(this.workingCopy);
338
+ if (!store.isConfigured(oldName)) {
339
+ throw new RemoteNotFoundError(oldName, `No such remote: '${oldName}'`);
340
+ }
341
+ if (store.isConfigured(newName)) {
342
+ throw new RemoteAlreadyExistsError(newName, `remote ${newName} already exists.`);
343
+ }
344
+ if (!isValidRemoteName(newName)) {
345
+ throw new InvalidArgumentError("newName", newName, `'${newName}' is not a valid remote name`);
205
346
  }
206
347
 
207
- if (configured) {
208
- store.remove(this.remoteName);
209
- await store.save();
348
+ const fetch = store.configuredFetchRefspecs(oldName);
349
+ const oldContext = `:refs/remotes/${oldName}/`;
350
+ const refspecsNeedUpdate = fetch.some((spec) => spec.includes(oldContext));
351
+ const oldTop = `refs/remotes/${oldName}/`;
352
+ const renamed = (ref: string) => `refs/remotes/${newName}/${ref.slice(oldTop.length)}`;
353
+
354
+ // the refs first: a refused batch (a name conflict) leaves everything as it was
355
+ if (refspecsNeedUpdate) {
356
+ const moves = [];
357
+ for await (const ref of this.refsStore.list(oldTop)) {
358
+ const to = renamed(ref.name);
359
+ const reflog: OwnReflogLine[] = [];
360
+ const id = isSymbolicRef(ref) ? undefined : ref.objectId;
361
+ const log = id ? await this.refsStore.getReflog?.(ref.name) : undefined;
362
+ if (log && id) {
363
+ for (const entry of (await log.getReverseEntries()).reverse()) {
364
+ reflog.push({
365
+ oldId: entry.oldId,
366
+ newId: entry.newId,
367
+ ident: formatIdent(entry.who),
368
+ message: entry.comment,
369
+ });
370
+ }
371
+ reflog.push({
372
+ oldId: id,
373
+ newId: id,
374
+ message: `remote: renamed ${ref.name} to ${to}`,
375
+ });
376
+ }
377
+ moves.push({ from: ref.name, to, reflog: reflog.length > 0 ? reflog : undefined });
378
+ }
379
+ await moveRefs(this.refsStore, moves, (target) =>
380
+ target.startsWith(oldTop) ? renamed(target) : target,
381
+ );
210
382
  }
211
383
 
212
- return removed;
384
+ store.rename(oldName, newName);
385
+ const warnings: string[] = [];
386
+ if (fetch.length > 0) {
387
+ const rewritten = fetch.map((spec) => {
388
+ const at = spec.indexOf(oldContext);
389
+ if (at < 0) {
390
+ warnings.push(
391
+ `Not updating non-default fetch refspec\n\t${spec}\n\tPlease update the configuration manually if necessary.`,
392
+ );
393
+ return spec;
394
+ }
395
+ const nameAt = at + ":refs/remotes/".length;
396
+ return `${spec.slice(0, nameAt)}${newName}${spec.slice(nameAt + oldName.length)}`;
397
+ });
398
+ store.setValues(`remote.${newName}.fetch`, rewritten);
399
+ }
400
+ for (const branch of store.subsections("branch")) {
401
+ if (store.value(`branch.${branch}.remote`) === oldName) {
402
+ store.setValue(`branch.${branch}.remote`, newName);
403
+ }
404
+ if (store.value(`branch.${branch}.pushRemote`) === oldName) {
405
+ store.setValue(`branch.${branch}.pushRemote`, newName);
406
+ }
407
+ }
408
+ if (refspecsNeedUpdate && store.value("remote.pushDefault") === oldName) {
409
+ store.setValue("remote.pushDefault", newName);
410
+ }
411
+ await store.save();
412
+ return { remote: store.read(newName), warnings };
413
+ }
414
+ }
415
+
416
+ /** git's report_set_head_auto (builtin/remote.c), from what `refs/remotes/<remote>/HEAD` held. */
417
+ function reportSetHeadAuto(
418
+ remote: string,
419
+ head: string,
420
+ previous: { target?: string; objectId?: string } | undefined,
421
+ ): string {
422
+ const prefix = `refs/remotes/${remote}/`;
423
+ const target = previous && "target" in previous ? previous.target : undefined;
424
+ const prev = target?.startsWith(prefix) ? target.slice(prefix.length) : undefined;
425
+ if (prev === head) return `'${remote}/HEAD' is unchanged and points to '${head}'`;
426
+ if (prev !== undefined) {
427
+ return `'${remote}/HEAD' has changed from '${prev}' and now points to '${head}'`;
428
+ }
429
+ if (!previous) return `'${remote}/HEAD' is now created and points to '${head}'`;
430
+ if (target === undefined) {
431
+ return `'${remote}/HEAD' was detached at '${previous.objectId}' and now points to '${head}'`;
432
+ }
433
+ return `'${remote}/HEAD' used to point to '${target}' (which is not a remote branch), but now points to '${head}'`;
434
+ }
435
+
436
+ /** git's remote_find_tracking: whether a fetch refspec writes `refName` (and no negative one excludes it). */
437
+ function tracks(specs: RefSpec[], refName: string): boolean {
438
+ const sources: string[] = [];
439
+ for (const spec of specs) {
440
+ if (spec.negative || !spec.source || !spec.destination) continue;
441
+ if (spec.wildcard) {
442
+ if (!matchDestination(spec, refName)) continue;
443
+ const source = expandFromDestination(spec, refName).source;
444
+ if (source) sources.push(source);
445
+ } else if (spec.destination === refName) {
446
+ sources.push(spec.source);
447
+ }
213
448
  }
449
+ // git's query_refspecs: a source a negative refspec matches excludes the ref
450
+ const negative = specs.filter((spec) => spec.negative && spec.source);
451
+ const excluded = sources.some((source) =>
452
+ negative.some((n) =>
453
+ n.wildcard ? matchesPattern(n.source as string, source) : n.source === source,
454
+ ),
455
+ );
456
+ return sources.length > 0 && !excluded;
457
+ }
458
+
459
+ /** A `*` pattern of a negative refspec matches `name`. */
460
+ function matchesPattern(pattern: string, name: string): boolean {
461
+ const star = pattern.indexOf("*");
462
+ if (star < 0) return pattern === name;
463
+ const head = pattern.slice(0, star);
464
+ const tail = pattern.slice(star + 1);
465
+ return name.length >= head.length + tail.length && name.startsWith(head) && name.endsWith(tail);
466
+ }
467
+
468
+ /** git's valid_remote_name: `refs/remotes/<name>/test` is a valid ref name. */
469
+ function isValidRemoteName(name: string): boolean {
470
+ return name.length > 0 && isValidRefName(`refs/remotes/${name}/test`);
471
+ }
472
+
473
+ /** A reflog identity, as git writes it: `Name <email> <seconds> <tz>`. */
474
+ function formatIdent(who: { name: string; email: string; timestamp: number; tzOffset: string }) {
475
+ return `${who.name} <${who.email}> ${Math.floor(who.timestamp)} ${who.tzOffset}`;
214
476
  }
215
477
 
216
478
  /**
@@ -383,3 +645,151 @@ export class RemoteSetUrlCommand extends GitCommand<RemoteConfig> {
383
645
  return false;
384
646
  }
385
647
  }
648
+
649
+ /**
650
+ * Point `refs/remotes/<name>/HEAD` at one of the remote's tracking branches, or delete it.
651
+ *
652
+ * Equivalent to `git remote set-head <name> <branch>`, `git remote set-head <name> -a`
653
+ * and `git remote set-head <name> -d`. The symbolic ref names the remote's default branch,
654
+ * so the remote name alone resolves to that branch (`git log origin`); `git clone` creates
655
+ * it. With {@link setAuto} the remote is asked which branch its HEAD is (its HEAD symref,
656
+ * or else the one branch at HEAD's commit). As git 2.48+, setting it on a remote whose
657
+ * `remote.<name>.followRemoteHEAD` is `always` turns that into `warn`, so the next fetch
658
+ * does not undo the choice.
659
+ *
660
+ * @example
661
+ * ```typescript
662
+ * await git.remoteSetHead().setRemoteName("origin").setBranch("develop").call();
663
+ * await git.remoteSetHead().setRemoteName("origin").setAuto(true).call();
664
+ * await git.remoteSetHead().setRemoteName("origin").setDelete(true).call();
665
+ * ```
666
+ */
667
+ export class RemoteSetHeadCommand extends TransportCommand<string | undefined> {
668
+ private remoteName?: string;
669
+ private branch?: string;
670
+ private deleteHead = false;
671
+ private auto = false;
672
+ private messages: string[] = [];
673
+
674
+ /** Set the remote whose HEAD is set. */
675
+ setRemoteName(name: string): this {
676
+ this.checkCallable();
677
+ this.remoteName = name;
678
+ return this;
679
+ }
680
+
681
+ /** Set the branch (`develop`, or `refs/remotes/origin/develop`) HEAD names. */
682
+ setBranch(branch: string): this {
683
+ this.checkCallable();
684
+ this.branch = branch;
685
+ return this;
686
+ }
687
+
688
+ /** Delete `refs/remotes/<name>/HEAD` instead (`-d`). */
689
+ setDelete(deleteHead: boolean): this {
690
+ this.checkCallable();
691
+ this.deleteHead = deleteHead;
692
+ return this;
693
+ }
694
+
695
+ /**
696
+ * What `git remote set-head -a` prints (git 2.48+): `'origin/HEAD' is now created and
697
+ * points to 'main'`, `… is unchanged and points to …`, `… has changed from 'a' and now
698
+ * points to 'b'`, and so on. Empty without {@link setAuto}, or before {@link call}.
699
+ */
700
+ getMessages(): string[] {
701
+ return [...this.messages];
702
+ }
703
+
704
+ /** Ask the remote which branch its HEAD is, and point at that one (`-a`). */
705
+ setAuto(auto: boolean): this {
706
+ this.checkCallable();
707
+ this.auto = auto;
708
+ return this;
709
+ }
710
+
711
+ /**
712
+ * @returns The tracking ref HEAD now names, or undefined after a delete
713
+ * @throws RefNotFoundError if the tracking branch does not exist (git: "Not a valid ref: <ref>")
714
+ * @throws RefNotFoundError with `-a` when the remote HEAD names no branch (git: "Cannot
715
+ * determine remote HEAD"), or several ("Multiple remote HEAD branches. Please choose
716
+ * one explicitly with:" and a `git remote set-head` line for each)
717
+ */
718
+ async call(): Promise<string | undefined> {
719
+ this.checkCallable();
720
+ this.setCallable(false);
721
+ const remote = this.remoteName;
722
+ if (!remote) {
723
+ throw new MissingArgumentError("remoteName", "Remote name must be specified");
724
+ }
725
+ const top = `refs/remotes/${remote}/`;
726
+ if (this.deleteHead) {
727
+ await this.refsStore.delete(`${top}HEAD`);
728
+ return undefined;
729
+ }
730
+ let branch = this.branch;
731
+ if (this.auto) {
732
+ const heads = await this.remoteHeads(remote);
733
+ if (heads.length === 0) {
734
+ throw new RefNotFoundError(`${top}HEAD`, "Cannot determine remote HEAD");
735
+ }
736
+ if (heads.length > 1) {
737
+ const lines = heads.map((h) => ` git remote set-head ${remote} ${h}`);
738
+ throw new RefNotFoundError(
739
+ `${top}HEAD`,
740
+ ["Multiple remote HEAD branches. Please choose one explicitly with:", ...lines].join(
741
+ "\n",
742
+ ),
743
+ );
744
+ }
745
+ branch = heads[0];
746
+ }
747
+ if (!branch) {
748
+ throw new MissingArgumentError("branch", "Branch must be specified, or auto or delete set");
749
+ }
750
+ const target = branch.startsWith(top) ? branch : `${top}${branch}`;
751
+ if (!(await this.refsStore.resolve(target))?.objectId) {
752
+ throw new RefNotFoundError(target, `Not a valid ref: ${target}`);
753
+ }
754
+ const previous = await this.refsStore.get(`${top}HEAD`);
755
+ await this.refsStore.setSymbolic(`${top}HEAD`, target);
756
+ if (this.auto)
757
+ this.messages.push(reportSetHeadAuto(remote, target.slice(top.length), previous));
758
+ const store = RemoteConfigStore.from(this.workingCopy);
759
+ if (store.value(`remote.${remote}.followRemoteHEAD`) === "always") {
760
+ store.setValue(`remote.${remote}.followRemoteHEAD`, "warn");
761
+ await store.save();
762
+ }
763
+ return target;
764
+ }
765
+
766
+ /**
767
+ * The remote's HEAD branches, as git's get_remote_ref_states (GET_HEAD_NAMES) finds them:
768
+ * every ref listed, then the branch HEAD's symref names, or else every branch at HEAD's
769
+ * commit (git's guess_remote_head with all matches).
770
+ */
771
+ private async remoteHeads(remote: string): Promise<string[]> {
772
+ const url = RemoteConfigStore.from(this.workingCopy).urlFor(remote);
773
+ if (!url) throw new InvalidRemoteError(remote);
774
+ const connection = await openHttpConnection({
775
+ url,
776
+ auth: this.credentials,
777
+ headers: this.headers,
778
+ timeout: this.timeout,
779
+ });
780
+ let refs: readonly TransportRemoteRef[];
781
+ try {
782
+ refs =
783
+ connection.version === 2 ? await lsRefs(connection, []) : (connection.advertisedRefs ?? []);
784
+ } finally {
785
+ await connection.close();
786
+ }
787
+ const head = refs.find((r) => r.name === "HEAD");
788
+ if (!head) return [];
789
+ const branches = refs.filter((r) => r.oid && r.name.startsWith("refs/heads/"));
790
+ const matches = head.symref
791
+ ? branches.filter((r) => r.name === head.symref)
792
+ : branches.filter((r) => r.oid === head.oid);
793
+ return matches.map((r) => r.name.slice("refs/heads/".length));
794
+ }
795
+ }
@@ -4,6 +4,7 @@ import { isSymbolicRef } from "@statewalker/vcs-core";
4
4
  import { RefNotFoundError } from "../errors/ref-errors.js";
5
5
  import { GitCommand } from "../git-command.js";
6
6
  import { ResetMode } from "../types.js";
7
+ import { coreBool, worktreeModeTrust } from "./core-config.js";
7
8
  import { planTreeRestore, writeTreeRestorePlan } from "./tree-restore.js";
8
9
 
9
10
  /** Names this operation in restore failure messages. */
@@ -238,15 +239,27 @@ export class ResetCommand extends GitCommand<Ref> {
238
239
 
239
240
  // Plan the whole restore first. Anything unrestorable then fails while the
240
241
  // working tree is still untouched, instead of half-way through rewriting it.
241
- const plan = await planTreeRestore(this.trees, this.blobs, commit.tree, RESET_HARD);
242
-
243
- await writeTreeRestorePlan(worktree, this.blobs, plan, RESET_HARD);
244
-
245
- // Delete files that were tracked but are not in the target tree.
242
+ const plan = await planTreeRestore(this.trees, this.blobs, commit.tree, RESET_HARD, {
243
+ symlinks: true,
244
+ ignoreCase: coreBool(this.workingCopy, "ignorecase", false),
245
+ windows: worktree.capabilities?.windowsPaths === true,
246
+ reservedNames: worktree.capabilities?.reservedNames,
247
+ });
248
+
249
+ // Delete the files that were tracked but are not in the target tree first, as git's
250
+ // unpack-trees does: a tracked file or symlink `d` then makes way for `d/x`, and is
251
+ // never written beneath or through.
246
252
  for (const path of trackedBefore) {
247
253
  if (plan.paths.has(path)) continue;
248
254
  await worktree.remove(path);
249
255
  }
256
+
257
+ // a forced checkout: a file or link where a directory must go is unlinked, never
258
+ // written through; links are written as links where the worktree has them
259
+ await writeTreeRestorePlan(worktree, this.blobs, plan, RESET_HARD, {
260
+ symlinks: worktreeModeTrust(this.workingCopy, worktree).symlinks,
261
+ replaceInTheWay: true,
262
+ });
250
263
  }
251
264
 
252
265
  /**