@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
@@ -6,7 +6,10 @@ import {
6
6
  createRepositoryFacade,
7
7
  createTransportRefStore,
8
8
  expandFromDestination,
9
+ type FetchClientResult,
10
+ type FetchHeadEntry,
9
11
  type FetchRefUpdate,
12
+ formatFetchHead,
10
13
  matchDestination,
11
14
  matchSource,
12
15
  parseRefSpec,
@@ -16,7 +19,7 @@ import {
16
19
  } from "@statewalker/vcs-transport";
17
20
 
18
21
  import { InvalidArgumentError, InvalidRemoteError } from "../errors/index.js";
19
- import { RemoteConfigStore } from "../remote-config/index.js";
22
+ import { deleteRefs, RemoteConfigStore } from "../remote-config/index.js";
20
23
  import {
21
24
  type FetchResult,
22
25
  RefUpdateStatus,
@@ -74,8 +77,13 @@ export enum TagOption {
74
77
  export class FetchCommand extends TransportCommand<FetchResult> {
75
78
  private remote = "origin";
76
79
  private refSpecs: string[] = [];
77
- private removeDeletedRefs = false;
80
+ private removeDeletedRefs?: boolean;
81
+ private pruneTags?: boolean;
82
+ private refmap?: string[];
78
83
  private tagOption: TagOption = TagOption.AUTO_FOLLOW;
84
+ private tagOptionSet = false;
85
+ private writeFetchHead = true;
86
+ private appendFetchHead = false;
79
87
  private thin = true;
80
88
  private depth?: number;
81
89
  private dryRun = false;
@@ -134,7 +142,11 @@ export class FetchCommand extends TransportCommand<FetchResult> {
134
142
  /**
135
143
  * Set whether to remove refs that no longer exist on the remote.
136
144
  *
137
- * Equivalent to `git fetch --prune`.
145
+ * Equivalent to `git fetch --prune` (true) and `--no-prune` (false). Unset, the
146
+ * remote's `remote.<name>.prune`, else `fetch.prune`, decides, as in git; neither set,
147
+ * nothing is pruned. The remote-tracking refs the refspecs map from a ref the remote no
148
+ * longer has are deleted before anything is fetched (so `foo` can become `foo/bar`); the
149
+ * command-line refspecs are used when given, else the configured ones.
138
150
  *
139
151
  * @param remove Whether to prune deleted refs
140
152
  */
@@ -145,18 +157,88 @@ export class FetchCommand extends TransportCommand<FetchResult> {
145
157
  }
146
158
 
147
159
  /**
148
- * Whether to remove deleted refs.
160
+ * Whether to remove deleted refs, as set with {@link setRemoveDeletedRefs} (false when
161
+ * unset: the configuration is read when the fetch runs).
149
162
  */
150
163
  isRemoveDeletedRefs(): boolean {
151
- return this.removeDeletedRefs;
164
+ return this.removeDeletedRefs ?? false;
152
165
  }
153
166
 
167
+ /**
168
+ * Set whether local tags the remote no longer has are pruned too (`git fetch
169
+ * --prune-tags` / `--no-prune-tags`). Unset, `remote.<name>.pruneTags`, else
170
+ * `fetch.pruneTags`, decides.
171
+ *
172
+ * As in git, this adds `refs/tags/*:refs/tags/*` to the refspecs (so every remote tag is
173
+ * fetched), and only when no refspec is given: to the remote's configured refspecs, or for
174
+ * a URL to the refspecs of the fetch. Tags are pruned only when pruning is on.
175
+ */
176
+ setPruneTags(pruneTags: boolean): this {
177
+ this.checkCallable();
178
+ this.pruneTags = pruneTags;
179
+ return this;
180
+ }
181
+
182
+ /**
183
+ * Set the refspecs that map the refs named on the command line to remote-tracking refs
184
+ * (`git fetch --refmap=<refspec>`), in place of the remote's `remote.<name>.fetch`.
185
+ *
186
+ * With explicit refspecs ({@link setRefSpecs}), git also updates the remote-tracking
187
+ * ref each fetched ref maps to through the configured refspecs (`git fetch origin main`
188
+ * moves `refs/remotes/origin/main`); a refmap replaces those, and an empty one
189
+ * (`setRefmap()`, git's `--refmap=`) turns the update off. Without explicit refspecs a
190
+ * refmap is an error, as in git.
191
+ */
192
+ setRefmap(...refspecs: string[]): this {
193
+ this.checkCallable();
194
+ this.refmap = refspecs;
195
+ return this;
196
+ }
197
+
198
+ /**
199
+ * Set how tags are fetched (`--tags`, `--no-tags`, or auto-follow).
200
+ *
201
+ * Unset, a configured remote's `remote.<name>.tagOpt` (`--tags`, `--no-tags`) decides, as
202
+ * in git; otherwise tags are auto-followed.
203
+ */
154
204
  setTagOpt(option: TagOption): this {
155
205
  this.checkCallable();
156
206
  this.tagOption = option;
207
+ this.tagOptionSet = true;
208
+ return this;
209
+ }
210
+
211
+ /**
212
+ * Set whether the fetch writes `FETCH_HEAD` (default true; `--no-write-fetch-head`).
213
+ *
214
+ * Written through the checkout's `writeFetchHead`; a checkout without it keeps none.
215
+ */
216
+ setWriteFetchHead(write: boolean): this {
217
+ this.checkCallable();
218
+ this.writeFetchHead = write;
219
+ return this;
220
+ }
221
+
222
+ /** Whether the fetch writes `FETCH_HEAD`. */
223
+ isWriteFetchHead(): boolean {
224
+ return this.writeFetchHead;
225
+ }
226
+
227
+ /**
228
+ * Set whether the fetched refs are added after what `FETCH_HEAD` holds instead of
229
+ * replacing it (`git fetch --append`).
230
+ */
231
+ setAppend(append: boolean): this {
232
+ this.checkCallable();
233
+ this.appendFetchHead = append;
157
234
  return this;
158
235
  }
159
236
 
237
+ /** Whether `FETCH_HEAD` is appended to. */
238
+ isAppend(): boolean {
239
+ return this.appendFetchHead;
240
+ }
241
+
160
242
  /**
161
243
  * Set thin-pack preference.
162
244
  *
@@ -356,23 +438,92 @@ export class FetchCommand extends TransportCommand<FetchResult> {
356
438
  throw new InvalidRemoteError(this.remote);
357
439
  }
358
440
 
441
+ const store = RemoteConfigStore.from(this.workingCopy);
442
+ // git's remote_is_configured: a remote name with a config section, not a URL
443
+ const viaConfig = store.isConfigured(this.remote);
444
+ const prune =
445
+ this.removeDeletedRefs ??
446
+ configBool(store.value(`remote.${this.remote}.prune`)) ??
447
+ configBool(store.value("fetch.prune")) ??
448
+ false;
449
+ const pruneTags =
450
+ this.pruneTags ??
451
+ configBool(store.value(`remote.${this.remote}.pruneTags`)) ??
452
+ configBool(store.value("fetch.pruneTags")) ??
453
+ false;
454
+ const configured = viaConfig ? store.configuredFetchRefspecs(this.remote) : [];
455
+ const explicitSpecs = [...this.refSpecs];
456
+ // fetch.c fetch_one: --prune-tags (only without command-line refspecs) adds the tag
457
+ // refspec to the configured ones, or for a URL to those of the fetch
458
+ if (pruneTags && this.refSpecs.length === 0) {
459
+ if (viaConfig) configured.push(TAG_REFSPEC);
460
+ else explicitSpecs.push(TAG_REFSPEC);
461
+ }
462
+
359
463
  // git: without a refspec the remote's HEAD is fetched, and no ref is written (nor any
360
464
  // tag); explicit refspecs must name refs the remote has, configured ones may not
361
- const fromConfig = this.refSpecs.length === 0;
362
- const configured = this.effectiveRefSpecs();
363
- const refspecs = configured.length > 0 ? configured : ["HEAD"];
465
+ const fromConfig = explicitSpecs.length === 0;
466
+ if (fromConfig && this.refmap !== undefined) {
467
+ throw new InvalidArgumentError(
468
+ "refmap",
469
+ this.refmap,
470
+ "--refmap option is only meaningful with command-line refspec(s)",
471
+ );
472
+ }
473
+ // git's has_merge (branch_has_merge_config): the current branch has an upstream, on
474
+ // whichever remote
475
+ const upstream = fromConfig ? await this.upstreamConfig() : undefined;
476
+ const upstreamHere = upstream?.remote === this.remote;
477
+ // git (fetch.c get_ref_map): the remote's configured refspecs, or with none the current
478
+ // branch's upstream refs when this remote is its upstream; else the remote HEAD
479
+ const useConfig = fromConfig && (configured.length > 0 || upstreamHere);
480
+ const given = !fromConfig ? explicitSpecs : useConfig ? configured : ["HEAD"];
481
+ // add_merge_config: fetching the current branch's upstream remote also takes the
482
+ // branch's `branch.<name>.merge` refs, for FETCH_HEAD
483
+ const mergeRefs = useConfig && upstream && upstreamHere ? upstream.merge : [];
484
+ const refspecs = [...given, ...mergeRefs];
364
485
  const history = this._workingCopy.history;
486
+ // get_ref_map: refs named on the command line also update the remote-tracking refs the
487
+ // refmap (or the remote's configured refspecs) maps them to
488
+ const opportunistic = fromConfig
489
+ ? []
490
+ : (this.refmap ?? configured).filter((spec) => spec !== "");
491
+ // do_fetch: refs/remotes/<name>/HEAD follows the remote HEAD on a configured fetch
492
+ const followHead = fromConfig && configured.length > 0 ? this.followRemoteHead(store) : null;
493
+ const messages: string[] = [];
494
+ const errors: string[] = [];
495
+ const trackingUpdates: TrackingRefUpdate[] = [];
496
+
497
+ // git truncates FETCH_HEAD when the fetch starts: a failed fetch leaves it empty
498
+ const checkout = this._workingCopy.checkout;
499
+ const writesFetchHead = !this.dryRun && this.writeFetchHead && !!checkout?.writeFetchHead;
500
+ if (writesFetchHead && !this.appendFetchHead) await checkout.writeFetchHead?.("");
365
501
 
366
502
  const result = await transportFetch({
367
503
  url: remoteUrl,
368
504
  auth: this.credentials,
369
505
  headers: this.headers,
370
506
  timeout: this.timeout,
507
+ gzipRequests: this.gzipRequests,
371
508
  repository: createRepositoryFacade({ history }),
372
509
  refStore: createTransportRefStore(history.refs),
373
510
  refspecs,
374
- missingRefsOk: fromConfig && configured.length > 0,
375
- tags: toTagMode(this.tagOption),
511
+ opportunisticRefspecs: opportunistic.length > 0 ? opportunistic : undefined,
512
+ // fetch.c do_fetch: stale refs are pruned before anything is fetched; with
513
+ // command-line refspecs by those, else by the configured ones
514
+ beforeFetch: prune
515
+ ? async (remoteRefs) => {
516
+ const names = new Set(remoteRefs.filter((r) => r.oid).map((r) => r.name));
517
+ const pruneSpecs = (fromConfig ? configured : explicitSpecs).map((s) =>
518
+ parseRefSpec(s),
519
+ );
520
+ trackingUpdates.push(
521
+ ...(await this.pruneDeletedRefs(names, pruneSpecs, messages, errors)),
522
+ );
523
+ }
524
+ : undefined,
525
+ missingRefsOk: useConfig,
526
+ tags: toTagMode(this.effectiveTagOption()),
376
527
  depth: this.depth,
377
528
  deepenSince: this.shallowSince,
378
529
  deepenNot: this.shallowExcludes.length > 0 ? this.shallowExcludes : undefined,
@@ -387,14 +538,29 @@ export class FetchCommand extends TransportCommand<FetchResult> {
387
538
  for (const ref of result.remoteRefs) {
388
539
  if (ref.oid) advertisedRefs.set(ref.name, ref.oid);
389
540
  }
390
- const trackingUpdates = result.refUpdates.map(toTrackingRefUpdate);
541
+ trackingUpdates.push(...result.refUpdates.map(toTrackingRefUpdate));
542
+
543
+ if (writesFetchHead && checkout?.writeFetchHead) {
544
+ const entries = await this.fetchHeadEntries(result, {
545
+ given: given.length,
546
+ merge: mergeRefs,
547
+ // explicit refspecs (and the HEAD of an unconfigured remote) are all to merge;
548
+ // configured ones only when the first names one ref and no upstream is set
549
+ explicit: !useConfig,
550
+ firstIsExact: given.length > 0 && !parseRefSpec(given[0]).wildcard,
551
+ hasMerge: upstream !== undefined,
552
+ });
553
+ // after the truncation above, every fetch adds its lines
554
+ await checkout.writeFetchHead(formatFetchHead(entries, remoteUrl), { append: true });
555
+ }
391
556
 
392
- // Handle prune
393
- if (!this.dryRun && this.removeDeletedRefs) {
394
- const parsed = refspecs.map((s) => parseRefSpec(s));
395
- trackingUpdates.push(
396
- ...(await this.pruneDeletedRefs(new Set(advertisedRefs.keys()), parsed)),
397
- );
557
+ if (followHead) {
558
+ // git: "way too many cases where this can go wrong ... fail silently"
559
+ try {
560
+ await this.setRemoteHead(result.remoteRefs, followHead, store, messages);
561
+ } catch {
562
+ // the refs are updated; refs/remotes/<name>/HEAD is left as it was
563
+ }
398
564
  }
399
565
 
400
566
  return {
@@ -404,22 +570,189 @@ export class FetchCommand extends TransportCommand<FetchResult> {
404
570
  defaultBranch: result.defaultBranch,
405
571
  bytesReceived: result.packBytes,
406
572
  isEmpty: result.isEmpty,
407
- messages: [],
573
+ messages,
574
+ ...(errors.length > 0 ? { errors } : {}),
408
575
  };
409
576
  }
410
577
 
411
578
  /**
412
- * The refspecs this fetch runs with.
413
- *
414
- * Explicit refspecs win; otherwise a configured remote contributes its
415
- * `remote.<name>.fetch` lines, which is what makes `fetch().setRemote("origin")`
416
- * update tracking refs without being told how. A remote given as a bare URL
417
- * has no config and so still needs its refspecs spelled out.
579
+ * How `refs/remotes/<name>/HEAD` follows the remote HEAD (git 2.48+): the remote's
580
+ * `remote.<name>.followRemoteHEAD`, else `fetch.followRemoteHEAD`, else `create`; an
581
+ * unrecognized value is ignored, as git warns and ignores it. Null for `never`.
418
582
  */
419
- private effectiveRefSpecs(): string[] {
420
- if (this.refSpecs.length > 0) return this.refSpecs;
583
+ private followRemoteHead(store: RemoteConfigStore): FollowRemoteHead | null {
584
+ const mode = parseFollowRemoteHead(
585
+ store.value(`remote.${this.remote}.followRemoteHEAD`),
586
+ true,
587
+ ) ??
588
+ parseFollowRemoteHead(store.value("fetch.followRemoteHEAD"), false) ?? {
589
+ mode: "create",
590
+ };
591
+ return mode.mode === "never" ? null : mode;
592
+ }
593
+
594
+ /**
595
+ * git's set_head (fetch.c): the one branch the remote HEAD names (its symref, or else the
596
+ * only branch at its commit) becomes `refs/remotes/<name>/HEAD`, if that tracking ref
597
+ * exists here: created when missing (`create`, `warn`), or always set (`always`). In a
598
+ * bare repository mirroring the remote (`remote.<name>.mirror`), HEAD itself is set to
599
+ * the branch. `warn` reports a local HEAD that differs, in git's words, into `messages`.
600
+ * As in git, failures are silent and a dry run is no exception.
601
+ */
602
+ private async setRemoteHead(
603
+ remoteRefs: readonly { name: string; oid?: string; symref?: string }[],
604
+ follow: FollowRemoteHead,
605
+ store: RemoteConfigStore,
606
+ messages: string[],
607
+ ): Promise<void> {
608
+ const head = remoteRefs.find((r) => r.name === "HEAD");
609
+ if (!head) return;
610
+ const branches = remoteRefs.filter((r) => r.oid && r.name.startsWith("refs/heads/"));
611
+ const heads = head.symref
612
+ ? branches.filter((r) => r.name === head.symref)
613
+ : branches.filter((r) => r.oid === head.oid);
614
+ if (heads.length !== 1) return;
615
+ const headName = heads[0].name.slice("refs/heads/".length);
616
+ const remote = this.remote;
617
+ const baremirror =
618
+ configBool(store.value("core.bare")) === true &&
619
+ configBool(store.value(`remote.${remote}.mirror`)) === true;
620
+ const createOnly = follow.mode === "always" ? false : !baremirror;
621
+ const name = baremirror ? "HEAD" : `refs/remotes/${remote}/HEAD`;
622
+ const target = baremirror ? `refs/heads/${headName}` : `refs/remotes/${remote}/${headName}`;
623
+ if (!baremirror && !(await this.refsStore.resolve(target))?.objectId) return;
624
+ const previous = await this.refsStore.get(name);
625
+ if (!createOnly || !previous) await this.refsStore.setSymbolic(name, target);
626
+ if (follow.mode !== "warn" || follow.noWarnBranch === headName || !previous) return;
627
+ // warn_set_head
628
+ const prefix = `refs/remotes/${remote}/`;
629
+ let warning: string | undefined;
630
+ if (isSymbolicRef(previous)) {
631
+ const was = previous.target.startsWith(prefix) ? previous.target.slice(prefix.length) : "";
632
+ if (was && was !== headName) {
633
+ warning = `'HEAD' at '${remote}' is '${headName}', but we have '${was}' locally.`;
634
+ }
635
+ } else {
636
+ warning = `'HEAD' at '${remote}' is '${headName}', but we have a detached HEAD pointing to '${previous.objectId}' locally.`;
637
+ }
638
+ if (!warning) return;
639
+ messages.push(warning);
640
+ // set_head_advice_msg, unless advice.fetchRemoteHEADWarn is false
641
+ if (configBool(store.value("advice.fetchRemoteHEADWarn")) === false) return;
642
+ const advice = [
643
+ `Run 'git remote set-head ${remote} ${headName}' to follow the change, or modify`,
644
+ `either of the 'remote.${remote}.followRemoteHEAD' or 'fetch.followRemoteHEAD'`,
645
+ "configuration variables to handle the situation differently.",
646
+ "",
647
+ "Using this specific setting",
648
+ "",
649
+ ` git config set remote.${remote}.followRemoteHEAD warn-if-not-${headName}`,
650
+ "",
651
+ "will suppress the warning until the remote changes HEAD to something else.",
652
+ 'Disable this message with "git config set advice.fetchRemoteHEADWarn false"',
653
+ ];
654
+ messages.push(...advice.map((line) => (line ? `hint: ${line}` : "hint:")));
655
+ }
656
+
657
+ /** The tag option given, else the remote's `remote.<name>.tagOpt`, else auto-follow. */
658
+ private effectiveTagOption(): TagOption {
659
+ if (this.tagOptionSet) return this.tagOption;
660
+ const tagOpt = RemoteConfigStore.from(this.workingCopy).value(`remote.${this.remote}.tagOpt`);
661
+ if (tagOpt === "--no-tags") return TagOption.NO_TAGS;
662
+ if (tagOpt === "--tags") return TagOption.FETCH_TAGS;
663
+ return this.tagOption;
664
+ }
665
+
666
+ /**
667
+ * The current branch's upstream: its `branch.<name>.remote` and `branch.<name>.merge`
668
+ * refs, when both are set (git's branch_has_merge_config); undefined on a detached HEAD
669
+ * or without upstream configuration.
670
+ */
671
+ private async upstreamConfig(): Promise<{ remote: string; merge: string[] } | undefined> {
672
+ const head = await this.refsStore.get("HEAD");
673
+ if (!head || !isSymbolicRef(head) || !head.target.startsWith("refs/heads/")) return undefined;
674
+ const branch = head.target.slice("refs/heads/".length);
421
675
  const store = RemoteConfigStore.from(this.workingCopy);
422
- return store.isConfigured(this.remote) ? store.read(this.remote).fetchRefspecs : [];
676
+ const remote = store.value(`branch.${branch}.remote`);
677
+ const merge = store.values(`branch.${branch}.merge`);
678
+ return remote !== undefined && merge.length > 0 ? { remote, merge } : undefined;
679
+ }
680
+
681
+ /**
682
+ * The `FETCH_HEAD` lines of a fetch, marked as git's get_ref_map marks them: refs from
683
+ * explicit refspecs (or the HEAD of an unconfigured remote) are to merge; with configured
684
+ * refspecs, the refs the current branch's `branch.<name>.merge` names (fetched for this
685
+ * alone when no refspec took them), or else the first ref when the first refspec names
686
+ * one ref. Tags (`--tags`, auto-follow), the rest, and anything that does not peel to a
687
+ * commit are `not-for-merge`.
688
+ */
689
+ private async fetchHeadEntries(
690
+ result: FetchClientResult,
691
+ marks: {
692
+ given: number;
693
+ merge: string[];
694
+ explicit: boolean;
695
+ firstIsExact: boolean;
696
+ hasMerge: boolean;
697
+ },
698
+ ): Promise<FetchHeadEntry[]> {
699
+ const mergeSpec = (index: number | undefined) =>
700
+ index !== undefined && index >= marks.given && index < marks.given + marks.merge.length
701
+ ? index - marks.given
702
+ : undefined;
703
+ const entries: (FetchHeadEntry & { refspec?: number })[] = [];
704
+ for (const fetched of result.fetched) {
705
+ if (mergeSpec(fetched.refspec) !== undefined) continue;
706
+ const fromGiven = fetched.refspec !== undefined && fetched.refspec < marks.given;
707
+ entries.push({
708
+ oid: fetched.oid,
709
+ remoteRef: fetched.remoteRef,
710
+ notForMerge: !(marks.explicit && fromGiven),
711
+ refspec: fetched.refspec,
712
+ });
713
+ }
714
+ if (!marks.explicit) {
715
+ if (!marks.hasMerge && marks.firstIsExact && entries[0]?.refspec === 0) {
716
+ entries[0].notForMerge = false;
717
+ }
718
+ // each merge ref marks the first ref a configured refspec took that it names...
719
+ const matched = new Set<number>();
720
+ for (const [k, ref] of marks.merge.entries()) {
721
+ const match = entries.find(
722
+ (e) =>
723
+ e.refspec !== undefined && e.refspec < marks.given && refNameMatches(ref, e.remoteRef),
724
+ );
725
+ if (match) {
726
+ match.notForMerge = false;
727
+ matched.add(k);
728
+ }
729
+ }
730
+ // ...or else is listed itself, after the refs the configured refspecs took
731
+ const extra: typeof entries = [];
732
+ for (const fetched of result.fetched) {
733
+ const k = mergeSpec(fetched.refspec);
734
+ if (k === undefined || matched.has(k)) continue;
735
+ extra.push({ oid: fetched.oid, remoteRef: fetched.remoteRef, notForMerge: false });
736
+ }
737
+ const tagsAt = entries.findIndex((e) => e.refspec === undefined || e.refspec >= marks.given);
738
+ entries.splice(tagsAt < 0 ? entries.length : tagsAt, 0, ...extra);
739
+ }
740
+ for (const entry of entries) {
741
+ if (!entry.notForMerge && !(await this.peelsToCommit(entry.oid))) entry.notForMerge = true;
742
+ }
743
+ return entries.map(({ oid, remoteRef, notForMerge }) => ({ oid, remoteRef, notForMerge }));
744
+ }
745
+
746
+ /** Whether `id` is a commit, or a tag (chain) of one (git's lookup_commit_reference_gently). */
747
+ private async peelsToCommit(id: ObjectId): Promise<boolean> {
748
+ const history = this._workingCopy.history;
749
+ let current: ObjectId | undefined = id;
750
+ for (let i = 0; current && i < 16; i++) {
751
+ if (await history.commits.has(current)) return true;
752
+ if (!(await history.tags.has(current))) return false;
753
+ current = await history.tags.getTarget(current);
754
+ }
755
+ return false;
423
756
  }
424
757
 
425
758
  /**
@@ -439,47 +772,85 @@ export class FetchCommand extends TransportCommand<FetchResult> {
439
772
  }
440
773
 
441
774
  /**
442
- * Prune local refs that a refspec maps from a remote ref that no longer exists (git's
443
- * `--prune`): for each refspec with a destination, the local refs matching the
444
- * destination whose source is not among the remote refs are deleted, unless a negative
445
- * refspec excludes that source (git's query_matches_negative_refspec).
775
+ * The stale remote-tracking refs (git's get_stale_heads): every local ref that the
776
+ * refspecs map from remote refs (all of the matching refspecs: overlapping ones count
777
+ * together), none of which the remote has, unless a negative refspec excludes it or it is
778
+ * a symbolic ref. They are deleted (reflogs too) in one batch, logged `fetch: prune`, and
779
+ * reported as deleted; a dry run reports them only. The symbolic refs left dangling are
780
+ * named in `messages` as git does. A refused delete does not stop the fetch: as in git
781
+ * (which then exits 1), the error goes into `errors` and nothing is reported deleted.
446
782
  */
447
783
  private async pruneDeletedRefs(
448
784
  remoteRefNames: Set<string>,
449
785
  specs: RefSpec[],
786
+ messages: string[],
787
+ errors: string[],
450
788
  ): Promise<TrackingRefUpdate[]> {
451
- const updates: TrackingRefUpdate[] = [];
452
- const done = new Set<string>();
453
789
  const negative = specs.filter((s) => s.negative && s.source);
454
- for (const spec of specs) {
455
- if (spec.negative || !spec.source || !spec.destination) continue;
456
- const prefix = spec.wildcard
457
- ? spec.destination.slice(0, spec.destination.indexOf("*"))
458
- : spec.destination;
459
- for await (const ref of this.refsStore.list(prefix)) {
460
- if (isSymbolicRef(ref) || done.has(ref.name)) continue;
461
- let source: string | null;
790
+ const mapping = specs.filter((s) => !s.negative && s.source && s.destination);
791
+ const stale: { name: string; objectId: ObjectId; source: string }[] = [];
792
+ for await (const ref of this.refsStore.list("refs/")) {
793
+ const sources: string[] = [];
794
+ for (const spec of mapping) {
462
795
  if (spec.wildcard) {
463
796
  if (!matchDestination(spec, ref.name)) continue;
464
- source = expandFromDestination(spec, ref.name).source;
465
- } else {
466
- if (ref.name !== spec.destination) continue;
467
- source = spec.source;
797
+ const source = expandFromDestination(spec, ref.name).source;
798
+ if (source) sources.push(source);
799
+ } else if (ref.name === spec.destination && spec.source) {
800
+ sources.push(spec.source);
468
801
  }
469
- if (!source || remoteRefNames.has(source)) continue;
470
- if (negative.some((n) => matchSource(n, source))) continue;
471
- done.add(ref.name);
472
- await this.refsStore.delete(ref.name);
473
- updates.push({
474
- localRef: ref.name,
475
- remoteRef: source,
476
- oldObjectId: ref.objectId,
477
- newObjectId: "", // Empty indicates deletion
478
- status: RefUpdateStatus.DELETED,
479
- });
802
+ }
803
+ if (sources.length === 0 || isSymbolicRef(ref) || !ref.objectId) continue;
804
+ if (sources.some((src) => negative.some((n) => matchSource(n, src)))) continue;
805
+ if (sources.some((src) => remoteRefNames.has(src))) continue;
806
+ stale.push({ name: ref.name, objectId: ref.objectId, source: sources[0] });
807
+ }
808
+ if (stale.length === 0) return [];
809
+ // refs_warn_dangling_symrefs: listed before the deletion, as the targets go
810
+ const dangling = await this.danglingSymrefs(new Set(stale.map((r) => r.name)));
811
+ if (!this.dryRun) {
812
+ try {
813
+ await deleteRefs(
814
+ this.refsStore,
815
+ stale.map((r) => r.name),
816
+ "fetch: prune",
817
+ );
818
+ } catch (error) {
819
+ errors.push(error instanceof Error ? error.message : String(error));
820
+ return [];
480
821
  }
481
822
  }
482
- return updates;
823
+ for (const { name, target } of dangling) {
824
+ messages.push(
825
+ this.dryRun
826
+ ? ` ${name} will become dangling after ${target} is deleted`
827
+ : ` ${name} has become dangling after ${target} was deleted`,
828
+ );
829
+ }
830
+ return stale.map((ref) => ({
831
+ localRef: ref.name,
832
+ remoteRef: ref.source,
833
+ oldObjectId: ref.objectId,
834
+ newObjectId: "", // Empty indicates deletion
835
+ status: RefUpdateStatus.DELETED,
836
+ summary: "[deleted]",
837
+ }));
838
+ }
839
+
840
+ /** The symbolic refs whose chain ends at one of `names` (git's warn_if_dangling_symref). */
841
+ private async danglingSymrefs(names: Set<string>): Promise<{ name: string; target: string }[]> {
842
+ const found: { name: string; target: string }[] = [];
843
+ for await (const ref of this.refsStore.list("refs/")) {
844
+ if (!isSymbolicRef(ref)) continue;
845
+ let target = ref.target;
846
+ for (let i = 0; i < 5; i++) {
847
+ const next = await this.refsStore.get(target);
848
+ if (!next || !isSymbolicRef(next)) break;
849
+ target = next.target;
850
+ }
851
+ if (names.has(target)) found.push({ name: ref.name, target });
852
+ }
853
+ return found.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
483
854
  }
484
855
  }
485
856
 
@@ -519,3 +890,51 @@ export function toTrackingRefUpdate(update: FetchRefUpdate): TrackingRefUpdate {
519
890
  reason: update.reason,
520
891
  };
521
892
  }
893
+
894
+ /** git's TAG_REFSPEC, which `--prune-tags` adds. */
895
+ const TAG_REFSPEC = "refs/tags/*:refs/tags/*";
896
+
897
+ /** How `refs/remotes/<name>/HEAD` follows the remote HEAD (`remote.<name>.followRemoteHEAD`). */
898
+ interface FollowRemoteHead {
899
+ mode: "never" | "create" | "warn" | "always";
900
+ /** `warn-if-not-<branch>`: no warning while the remote HEAD is this branch */
901
+ noWarnBranch?: string;
902
+ }
903
+
904
+ /**
905
+ * A `followRemoteHEAD` value; undefined when unset or unrecognized. `warn-if-not-<branch>`
906
+ * is read from `remote.<name>.followRemoteHEAD` only, as git's remote.c does.
907
+ */
908
+ function parseFollowRemoteHead(
909
+ value: string | undefined,
910
+ perRemote: boolean,
911
+ ): FollowRemoteHead | undefined {
912
+ if (value === "never" || value === "create" || value === "warn" || value === "always") {
913
+ return { mode: value };
914
+ }
915
+ if (perRemote && value?.startsWith("warn-if-not-")) {
916
+ return { mode: "warn", noWarnBranch: value.slice("warn-if-not-".length) };
917
+ }
918
+ return undefined;
919
+ }
920
+
921
+ /** A git boolean config value; undefined when unset or not a boolean. */
922
+ function configBool(value: string | undefined): boolean | undefined {
923
+ if (value === undefined) return undefined;
924
+ const v = value.trim().toLowerCase();
925
+ if (v === "true" || v === "yes" || v === "on" || v === "1") return true;
926
+ if (v === "false" || v === "no" || v === "off" || v === "0" || v === "") return false;
927
+ return undefined;
928
+ }
929
+
930
+ /** git's refname_match: `ref` (`main`, `heads/main`, `refs/heads/main`) names `fullName`. */
931
+ function refNameMatches(ref: string, fullName: string): boolean {
932
+ return [
933
+ ref,
934
+ `refs/${ref}`,
935
+ `refs/tags/${ref}`,
936
+ `refs/heads/${ref}`,
937
+ `refs/remotes/${ref}`,
938
+ `refs/remotes/${ref}/HEAD`,
939
+ ].includes(fullName);
940
+ }
@@ -27,5 +27,6 @@ export * from "./stash-apply-command.js";
27
27
  export * from "./stash-create-command.js";
28
28
  export * from "./stash-drop-command.js";
29
29
  export * from "./stash-list-command.js";
30
+ export * from "./stash-working-tree.js";
30
31
  export * from "./status-command.js";
31
32
  export * from "./tag-command.js";