@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
@@ -3,16 +3,23 @@ import type { ObjectId } from "@statewalker/vcs-core";
3
3
  // (dist/index.js); its subpaths resolve for types but not at runtime.
4
4
  import { isSymbolicRef } from "@statewalker/vcs-core";
5
5
  import {
6
- expandFromSource,
6
+ createRepositoryFacade,
7
+ createTransportRefStore,
8
+ expandFromDestination,
9
+ type FetchClientResult,
10
+ type FetchHeadEntry,
11
+ type FetchRefUpdate,
12
+ formatFetchHead,
13
+ matchDestination,
7
14
  matchSource,
8
15
  parseRefSpec,
9
16
  type RefSpec,
17
+ type TagMode,
10
18
  fetch as transportFetch,
11
19
  } from "@statewalker/vcs-transport";
12
20
 
13
21
  import { InvalidArgumentError, InvalidRemoteError } from "../errors/index.js";
14
- import { importPackIntoHistory } from "../pack-import/index.js";
15
- import { RemoteConfigStore } from "../remote-config/index.js";
22
+ import { deleteRefs, RemoteConfigStore } from "../remote-config/index.js";
16
23
  import {
17
24
  type FetchResult,
18
25
  RefUpdateStatus,
@@ -70,9 +77,13 @@ export enum TagOption {
70
77
  export class FetchCommand extends TransportCommand<FetchResult> {
71
78
  private remote = "origin";
72
79
  private refSpecs: string[] = [];
73
- private removeDeletedRefs = false;
74
- // biome-ignore lint/correctness/noUnusedPrivateClassMembers: Set by setTagOpt(), to be used in call()
80
+ private removeDeletedRefs?: boolean;
81
+ private pruneTags?: boolean;
82
+ private refmap?: string[];
75
83
  private tagOption: TagOption = TagOption.AUTO_FOLLOW;
84
+ private tagOptionSet = false;
85
+ private writeFetchHead = true;
86
+ private appendFetchHead = false;
76
87
  private thin = true;
77
88
  private depth?: number;
78
89
  private dryRun = false;
@@ -131,7 +142,11 @@ export class FetchCommand extends TransportCommand<FetchResult> {
131
142
  /**
132
143
  * Set whether to remove refs that no longer exist on the remote.
133
144
  *
134
- * 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.
135
150
  *
136
151
  * @param remove Whether to prune deleted refs
137
152
  */
@@ -142,18 +157,88 @@ export class FetchCommand extends TransportCommand<FetchResult> {
142
157
  }
143
158
 
144
159
  /**
145
- * 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).
146
162
  */
147
163
  isRemoveDeletedRefs(): boolean {
148
- return this.removeDeletedRefs;
164
+ return this.removeDeletedRefs ?? false;
149
165
  }
150
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
+ */
151
204
  setTagOpt(option: TagOption): this {
152
205
  this.checkCallable();
153
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;
154
234
  return this;
155
235
  }
156
236
 
237
+ /** Whether `FETCH_HEAD` is appended to. */
238
+ isAppend(): boolean {
239
+ return this.appendFetchHead;
240
+ }
241
+
157
242
  /**
158
243
  * Set thin-pack preference.
159
244
  *
@@ -334,6 +419,12 @@ export class FetchCommand extends TransportCommand<FetchResult> {
334
419
  /**
335
420
  * Execute the fetch operation.
336
421
  *
422
+ * Runs the transport's fetch client (git's fetch-pack): the local refs are offered as
423
+ * haves, so only the objects the working copy lacks are downloaded; shallow options and
424
+ * the shallow file are honoured; tags follow the tag option; each tracking ref is
425
+ * updated when it fast-forwards or its refspec (or {@link setForceUpdate}) forces it, and
426
+ * rejected otherwise.
427
+ *
337
428
  * @returns Fetch result with updated refs
338
429
  * @throws InvalidRemoteError if remote cannot be resolved
339
430
  */
@@ -347,128 +438,323 @@ export class FetchCommand extends TransportCommand<FetchResult> {
347
438
  throw new InvalidRemoteError(this.remote);
348
439
  }
349
440
 
350
- // Parse refspecs for source→destination mapping
351
- const parsedSpecs = this.effectiveRefSpecs().map((s) => parseRefSpec(s));
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
+ }
352
462
 
353
- // Save old ref values before fetch for status computation
354
- const oldRefValues = new Map<string, string | undefined>();
355
- for await (const ref of this.refsStore.list()) {
356
- if (!isSymbolicRef(ref) && ref.objectId) {
357
- oldRefValues.set(ref.name, ref.objectId);
358
- }
463
+ // git: without a refspec the remote's HEAD is fetched, and no ref is written (nor any
464
+ // tag); explicit refspecs must name refs the remote has, configured ones may not
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
+ );
359
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];
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[] = [];
360
496
 
361
- // Execute fetch using high-level fetch API
362
- const transportResult = await transportFetch({
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?.("");
501
+
502
+ const result = await transportFetch({
363
503
  url: remoteUrl,
364
504
  auth: this.credentials,
365
505
  headers: this.headers,
366
506
  timeout: this.timeout,
507
+ gzipRequests: this.gzipRequests,
508
+ repository: createRepositoryFacade({ history }),
509
+ refStore: createTransportRefStore(history.refs),
510
+ refspecs,
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()),
367
527
  depth: this.depth,
368
- onProgressMessage: this.progressMessageCallback,
528
+ deepenSince: this.shallowSince,
529
+ deepenNot: this.shallowExcludes.length > 0 ? this.shallowExcludes : undefined,
530
+ unshallow: this.unshallow || undefined,
531
+ force: this.forceUpdate,
532
+ dryRun: this.dryRun,
533
+ onProgress: this.progressMessageCallback,
534
+ reflogMessage: `fetch: ${remoteUrl}`,
369
535
  });
370
536
 
371
- // Convert refs from Uint8Array to hex strings
372
- const bytesToHex = (bytes: Uint8Array): string =>
373
- Array.from(bytes)
374
- .map((b) => b.toString(16).padStart(2, "0"))
375
- .join("");
376
-
377
537
  const advertisedRefs = new Map<string, ObjectId>();
378
- for (const [refName, objectId] of transportResult.refs) {
379
- advertisedRefs.set(refName, bytesToHex(objectId));
380
- }
381
-
382
- // Build tracking ref updates by mapping server refs through refspecs
383
- const trackingUpdates: TrackingRefUpdate[] = [];
384
- for (const [serverRefName, objectIdBytes] of transportResult.refs) {
385
- const objectId = bytesToHex(objectIdBytes);
386
-
387
- // Map server ref name to local ref name via refspecs
388
- const localRefName = this.mapServerRef(serverRefName, parsedSpecs);
389
- if (!localRefName) continue;
390
-
391
- const isForce = this.forceUpdate || this.isRefSpecForced(serverRefName, parsedSpecs);
392
- const update = await this.computeRefUpdate(
393
- localRefName,
394
- serverRefName,
395
- objectId,
396
- oldRefValues,
397
- isForce,
398
- );
399
-
400
- // Write the mapped ref to local store (unless dry-run)
401
- if (!this.dryRun) {
402
- await this.refsStore.set(localRefName, objectId);
403
- }
404
-
405
- trackingUpdates.push(update);
538
+ for (const ref of result.remoteRefs) {
539
+ if (ref.oid) advertisedRefs.set(ref.name, ref.oid);
406
540
  }
407
-
408
- // Handle prune
409
- if (!this.dryRun && this.removeDeletedRefs) {
410
- const pruned = await this.pruneDeletedRefs(transportResult.refs);
411
- trackingUpdates.push(...pruned);
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 });
412
555
  }
413
556
 
414
- // Store pack data
415
- if (transportResult.packData.length > 0 && !this.dryRun) {
416
- await this.storePack(transportResult.packData);
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
+ }
417
564
  }
418
565
 
419
566
  return {
420
567
  uri: remoteUrl,
421
568
  advertisedRefs,
422
569
  trackingRefUpdates: trackingUpdates,
423
- defaultBranch: transportResult.defaultBranch,
424
- bytesReceived: transportResult.bytesReceived,
425
- isEmpty: transportResult.isEmpty,
426
- messages: [],
570
+ defaultBranch: result.defaultBranch,
571
+ bytesReceived: result.packBytes,
572
+ isEmpty: result.isEmpty,
573
+ messages,
574
+ ...(errors.length > 0 ? { errors } : {}),
427
575
  };
428
576
  }
429
577
 
430
578
  /**
431
- * Map a server ref name to a local ref name using parsed refspecs.
432
- * Returns undefined if no refspec matches.
433
- */
434
- private mapServerRef(serverRef: string, specs: RefSpec[]): string | undefined {
435
- for (const spec of specs) {
436
- if (spec.negative) continue;
437
- if (!spec.source || !spec.destination) continue;
438
- if (!matchSource(spec, serverRef)) continue;
439
-
440
- const expanded = expandFromSource(spec, serverRef);
441
- return expanded.destination ?? undefined;
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`.
582
+ */
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);
675
+ const store = RemoteConfigStore.from(this.workingCopy);
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);
442
739
  }
443
- return undefined;
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 }));
444
744
  }
445
745
 
446
- /**
447
- * Check if any matching refspec has the force flag for a given server ref.
448
- */
449
- private isRefSpecForced(serverRef: string, specs: RefSpec[]): boolean {
450
- for (const spec of specs) {
451
- if (spec.negative) continue;
452
- if (!spec.source) continue;
453
- if (matchSource(spec, serverRef) && spec.force) return true;
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);
454
754
  }
455
755
  return false;
456
756
  }
457
757
 
458
- /**
459
- * The refspecs this fetch runs with.
460
- *
461
- * Explicit refspecs win; otherwise a configured remote contributes its
462
- * `remote.<name>.fetch` lines, which is what makes `fetch().setRemote("origin")`
463
- * update tracking refs without being told how. A remote given as a bare URL
464
- * has no config and so still needs its refspecs spelled out.
465
- */
466
- private effectiveRefSpecs(): string[] {
467
- if (this.refSpecs.length > 0) return this.refSpecs;
468
- const store = RemoteConfigStore.from(this.workingCopy);
469
- return store.isConfigured(this.remote) ? store.read(this.remote).fetchRefspecs : [];
470
- }
471
-
472
758
  /**
473
759
  * Resolve remote name to URL.
474
760
  *
@@ -486,130 +772,169 @@ export class FetchCommand extends TransportCommand<FetchResult> {
486
772
  }
487
773
 
488
774
  /**
489
- * Compute ref update status using pre-fetch ref values.
490
- *
491
- * Uses saved pre-fetch values to correctly determine
492
- * NEW vs NO_CHANGE vs FAST_FORWARD status.
493
- */
494
- private async computeRefUpdate(
495
- localRef: string,
496
- remoteRef: string,
497
- newObjectId: ObjectId,
498
- oldRefValues: Map<string, string | undefined>,
499
- force: boolean,
500
- ): Promise<TrackingRefUpdate> {
501
- const oldObjectId = oldRefValues.get(localRef);
502
-
503
- let status: RefUpdateStatus;
504
- if (!oldObjectId) {
505
- status = RefUpdateStatus.NEW;
506
- } else if (oldObjectId === newObjectId) {
507
- status = RefUpdateStatus.NO_CHANGE;
508
- } else if (force) {
509
- status = RefUpdateStatus.FORCED;
510
- } else {
511
- // Check if fast-forward
512
- const isAncestor = await this.isAncestor(oldObjectId, newObjectId);
513
- status = isAncestor ? RefUpdateStatus.FAST_FORWARD : RefUpdateStatus.REJECTED;
514
- }
515
-
516
- return {
517
- localRef,
518
- remoteRef,
519
- oldObjectId,
520
- newObjectId,
521
- status,
522
- };
523
- }
524
-
525
- /**
526
- * Check if one commit is an ancestor of another.
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.
527
782
  */
528
- private async isAncestor(ancestor: ObjectId, descendant: ObjectId): Promise<boolean> {
529
- // Walk from descendant back to see if we hit ancestor
530
- const visited = new Set<ObjectId>();
531
- const queue: ObjectId[] = [descendant];
532
-
533
- while (queue.length > 0) {
534
- const current = queue.shift();
535
- if (current === undefined) break;
536
- if (current === ancestor) {
537
- return true;
538
- }
539
- if (visited.has(current)) {
540
- continue;
783
+ private async pruneDeletedRefs(
784
+ remoteRefNames: Set<string>,
785
+ specs: RefSpec[],
786
+ messages: string[],
787
+ errors: string[],
788
+ ): Promise<TrackingRefUpdate[]> {
789
+ const negative = specs.filter((s) => s.negative && s.source);
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) {
795
+ if (spec.wildcard) {
796
+ if (!matchDestination(spec, ref.name)) continue;
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);
801
+ }
541
802
  }
542
- visited.add(current);
543
-
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) {
544
812
  try {
545
- const commit = await this.commits.load(current);
546
- if (commit) {
547
- queue.push(...commit.parents);
548
- }
549
- } catch {
550
- // Commit not found, skip
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 [];
551
821
  }
552
-
553
- // Limit walk depth for performance
554
- if (visited.size > 10000) {
555
- break;
822
+ }
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;
556
850
  }
851
+ if (names.has(target)) found.push({ name: ref.name, target });
557
852
  }
558
-
559
- return false;
853
+ return found.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
560
854
  }
855
+ }
561
856
 
562
- /**
563
- * Prune refs that no longer exist on remote.
564
- */
565
- private async pruneDeletedRefs(
566
- remoteRefs: Map<string, Uint8Array>,
567
- ): Promise<TrackingRefUpdate[]> {
568
- const updates: TrackingRefUpdate[] = [];
569
- const prefix = `refs/remotes/${this.remote}/`;
857
+ /** The transport's tag mode for a {@link TagOption}. */
858
+ export function toTagMode(option: TagOption): TagMode {
859
+ switch (option) {
860
+ case TagOption.FETCH_TAGS:
861
+ return "all";
862
+ case TagOption.NO_TAGS:
863
+ return "none";
864
+ default:
865
+ return "auto";
866
+ }
867
+ }
570
868
 
571
- // Get remote ref names for comparison
572
- const remoteRefNames = new Set<string>();
573
- for (const refName of remoteRefs.keys()) {
574
- remoteRefNames.add(refName);
575
- }
869
+ /** A transport ref update as a {@link TrackingRefUpdate}. */
870
+ export function toTrackingRefUpdate(update: FetchRefUpdate): TrackingRefUpdate {
871
+ const status =
872
+ update.status === "new"
873
+ ? RefUpdateStatus.NEW
874
+ : update.status === "up-to-date"
875
+ ? RefUpdateStatus.NO_CHANGE
876
+ : update.status === "fast-forward"
877
+ ? RefUpdateStatus.FAST_FORWARD
878
+ : update.status === "forced"
879
+ ? RefUpdateStatus.FORCED
880
+ : update.reason === "non-fast-forward" || update.reason === "would clobber existing tag"
881
+ ? RefUpdateStatus.REJECTED
882
+ : RefUpdateStatus.LOCK_FAILURE;
883
+ return {
884
+ localRef: update.localRef,
885
+ remoteRef: update.remoteRef,
886
+ oldObjectId: update.oldOid,
887
+ newObjectId: update.newOid,
888
+ status,
889
+ summary: update.summary,
890
+ reason: update.reason,
891
+ };
892
+ }
576
893
 
577
- // Find local tracking refs that don't exist on remote
578
- for await (const ref of this.refsStore.list(prefix)) {
579
- // Skip symbolic refs
580
- if (isSymbolicRef(ref)) {
581
- continue;
582
- }
894
+ /** git's TAG_REFSPEC, which `--prune-tags` adds. */
895
+ const TAG_REFSPEC = "refs/tags/*:refs/tags/*";
583
896
 
584
- // Derive remote ref name
585
- const localName = ref.name.slice(prefix.length);
586
- const remoteRefName = `refs/heads/${localName}`;
587
-
588
- if (!remoteRefNames.has(ref.name) && !remoteRefNames.has(remoteRefName)) {
589
- // Delete the local tracking ref
590
- await this.refsStore.delete(ref.name);
591
- updates.push({
592
- localRef: ref.name,
593
- remoteRef: remoteRefName,
594
- oldObjectId: ref.objectId,
595
- newObjectId: "", // Empty indicates deletion
596
- status: RefUpdateStatus.DELETED,
597
- });
598
- }
599
- }
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
+ }
600
903
 
601
- return updates;
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 };
602
914
  }
603
-
604
- /**
605
- * Store received pack data.
606
- *
607
- * Unpacks the pack into the working copy's history, so the objects the
608
- * freshly written tracking refs point at are actually available locally.
609
- * Import is idempotent: the stores are content-addressed, so re-importing
610
- * a pack rewrites the same object IDs.
611
- */
612
- private async storePack(packData: Uint8Array): Promise<void> {
613
- await importPackIntoHistory(this._workingCopy.history, packData);
915
+ if (perRemote && value?.startsWith("warn-if-not-")) {
916
+ return { mode: "warn", noWarnBranch: value.slice("warn-if-not-".length) };
614
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);
615
940
  }