@gitkraken/core-gitlens 0.37.1 → 0.38.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 (118) hide show
  1. package/CHANGELOG.md +60 -1
  2. package/dist/git/cache.d.ts +128 -8
  3. package/dist/git/cache.js +425 -46
  4. package/dist/git/cache.js.map +1 -1
  5. package/dist/git/features.d.ts +1 -1
  6. package/dist/git/features.js +3 -0
  7. package/dist/git/features.js.map +1 -1
  8. package/dist/git/providers/branches.d.ts +42 -1
  9. package/dist/git/providers/diff.d.ts +17 -0
  10. package/dist/git/providers/provider.d.ts +7 -0
  11. package/dist/git/providers/shared/remotes.js +8 -4
  12. package/dist/git/providers/shared/remotes.js.map +1 -1
  13. package/dist/git/remotes/matcher.js +2 -2
  14. package/dist/git/remotes/matcher.js.map +1 -1
  15. package/dist/git/repositoryService.d.ts +16 -1
  16. package/dist/git/repositoryService.js +51 -3
  17. package/dist/git/repositoryService.js.map +1 -1
  18. package/dist/git/run.types.d.ts +1 -0
  19. package/dist/git/service.js +6 -2
  20. package/dist/git/service.js.map +1 -1
  21. package/dist/git/utils/fileStatus.utils.d.ts +5 -0
  22. package/dist/git/utils/fileStatus.utils.js +18 -1
  23. package/dist/git/utils/fileStatus.utils.js.map +1 -1
  24. package/dist/git/watching/changeEvent.d.ts +13 -3
  25. package/dist/git/watching/changeEvent.js +15 -4
  26. package/dist/git/watching/changeEvent.js.map +1 -1
  27. package/dist/git/watching/changeOrdinal.d.ts +9 -0
  28. package/dist/git/watching/changeOrdinal.js +14 -0
  29. package/dist/git/watching/changeOrdinal.js.map +1 -0
  30. package/dist/git/watching/unwatchedCacheValidator.d.ts +38 -5
  31. package/dist/git/watching/unwatchedCacheValidator.js +180 -36
  32. package/dist/git/watching/unwatchedCacheValidator.js.map +1 -1
  33. package/dist/git/watching/watchGroup.d.ts +63 -14
  34. package/dist/git/watching/watchGroup.js +213 -74
  35. package/dist/git/watching/watchGroup.js.map +1 -1
  36. package/dist/git/watching/watchService.js +4 -3
  37. package/dist/git/watching/watchService.js.map +1 -1
  38. package/dist/git/watching/watchSession.d.ts +10 -2
  39. package/dist/git/watching/watchSession.js +18 -4
  40. package/dist/git/watching/watchSession.js.map +1 -1
  41. package/dist/git/watching/watcherPatterns.d.ts +18 -4
  42. package/dist/git/watching/watcherPatterns.js +39 -8
  43. package/dist/git/watching/watcherPatterns.js.map +1 -1
  44. package/dist/git/watching/worktreeSummary.d.ts +23 -12
  45. package/dist/git/watching/worktreeSummary.js +164 -41
  46. package/dist/git/watching/worktreeSummary.js.map +1 -1
  47. package/dist/git-cli/cliGitProvider.d.ts +1 -0
  48. package/dist/git-cli/cliGitProvider.js +11 -2
  49. package/dist/git-cli/cliGitProvider.js.map +1 -1
  50. package/dist/git-cli/exec/git.d.ts +7 -2
  51. package/dist/git-cli/exec/git.js +46 -10
  52. package/dist/git-cli/exec/git.js.map +1 -1
  53. package/dist/git-cli/exec/headState.d.ts +24 -0
  54. package/dist/git-cli/exec/headState.js +46 -6
  55. package/dist/git-cli/exec/headState.js.map +1 -1
  56. package/dist/git-cli/parsers/logParser.js +6 -3
  57. package/dist/git-cli/parsers/logParser.js.map +1 -1
  58. package/dist/git-cli/providers/branches.d.ts +135 -10
  59. package/dist/git-cli/providers/branches.js +622 -80
  60. package/dist/git-cli/providers/branches.js.map +1 -1
  61. package/dist/git-cli/providers/commits.d.ts +16 -0
  62. package/dist/git-cli/providers/commits.js +80 -28
  63. package/dist/git-cli/providers/commits.js.map +1 -1
  64. package/dist/git-cli/providers/config.d.ts +10 -0
  65. package/dist/git-cli/providers/config.js +50 -12
  66. package/dist/git-cli/providers/config.js.map +1 -1
  67. package/dist/git-cli/providers/contributors.js +11 -7
  68. package/dist/git-cli/providers/contributors.js.map +1 -1
  69. package/dist/git-cli/providers/diff.d.ts +12 -0
  70. package/dist/git-cli/providers/diff.js +107 -15
  71. package/dist/git-cli/providers/diff.js.map +1 -1
  72. package/dist/git-cli/providers/graph.js +32 -25
  73. package/dist/git-cli/providers/graph.js.map +1 -1
  74. package/dist/git-cli/providers/operations.d.ts +37 -3
  75. package/dist/git-cli/providers/operations.js +124 -46
  76. package/dist/git-cli/providers/operations.js.map +1 -1
  77. package/dist/git-cli/providers/patch.js +1 -1
  78. package/dist/git-cli/providers/patch.js.map +1 -1
  79. package/dist/git-cli/providers/refs.d.ts +1 -1
  80. package/dist/git-cli/providers/refs.js +10 -11
  81. package/dist/git-cli/providers/refs.js.map +1 -1
  82. package/dist/git-cli/providers/status.d.ts +4 -5
  83. package/dist/git-cli/providers/status.js +36 -33
  84. package/dist/git-cli/providers/status.js.map +1 -1
  85. package/dist/git-cli/providers/tags.d.ts +8 -0
  86. package/dist/git-cli/providers/tags.js +53 -34
  87. package/dist/git-cli/providers/tags.js.map +1 -1
  88. package/dist/git-cli/service.d.ts +15 -0
  89. package/dist/git-cli/service.js +19 -1
  90. package/dist/git-cli/service.js.map +1 -1
  91. package/dist/plus/git-github/providers/github/diff.d.ts +1 -0
  92. package/dist/plus/git-github/providers/github/diff.js +6 -1
  93. package/dist/plus/git-github/providers/github/diff.js.map +1 -1
  94. package/dist/plus/integrations/integrationService.js +9 -0
  95. package/dist/plus/integrations/integrationService.js.map +1 -1
  96. package/dist/plus/integrations/providers/issueSorts.d.ts +1 -0
  97. package/dist/plus/integrations/providers/jira-server.js +1 -1
  98. package/dist/plus/integrations/providers/jira-server.js.map +1 -1
  99. package/dist/plus/integrations/providers/jira.d.ts +38 -6
  100. package/dist/plus/integrations/providers/jira.js +111 -69
  101. package/dist/plus/integrations/providers/jira.js.map +1 -1
  102. package/dist/plus/integrations/providers/linear.d.ts +31 -3
  103. package/dist/plus/integrations/providers/linear.js +77 -18
  104. package/dist/plus/integrations/providers/linear.js.map +1 -1
  105. package/dist/plus/integrations/providers/utils/discoveryCache.d.ts +41 -4
  106. package/dist/plus/integrations/providers/utils/discoveryCache.js +50 -11
  107. package/dist/plus/integrations/providers/utils/discoveryCache.js.map +1 -1
  108. package/dist/plus/integrations/reads/drains.d.ts +1 -0
  109. package/dist/utils/env/node/exec.d.ts +5 -4
  110. package/dist/utils/env/node/exec.js +52 -9
  111. package/dist/utils/env/node/exec.js.map +1 -1
  112. package/dist/utils/holdOffMap.d.ts +23 -0
  113. package/dist/utils/holdOffMap.js +43 -0
  114. package/dist/utils/holdOffMap.js.map +1 -0
  115. package/dist/utils/promiseCache.d.ts +15 -2
  116. package/dist/utils/promiseCache.js +34 -4
  117. package/dist/utils/promiseCache.js.map +1 -1
  118. package/package.json +1 -1
@@ -9,7 +9,7 @@ import { getBranchId } from "../../utils/gitRefs.js";
9
9
  import { joinUriPath } from "../../utils/uri.js";
10
10
  import { normalizePath } from "../../utils/path.js";
11
11
  import { createRevisionRange, isSha, shortenRevision } from "../../git/utils/revision.utils.js";
12
- import { formatDetachedHeadName, getLocalBranchByUpstream, isDetachedHead, isRemoteHEAD, parseBranchMetadataGkConfigKey, parseRefName, parseUpstream, setBranchMetadataValue, splitRemoteBranchName } from "../../git/utils/branch.utils.js";
12
+ import { formatDetachedHeadName, isDetachedHead, isRemoteHEAD, parseBranchMetadataGkConfigKey, parseRefName, parseUpstream, setBranchMetadataValue, splitRemoteBranchName } from "../../git/utils/branch.utils.js";
13
13
  import { createReference } from "../../git/utils/reference.utils.js";
14
14
  import __decorate from "../../_virtual/@oxc-project+runtime/helpers/esm/decorate.js";
15
15
  import { BranchError, GitWarnings } from "../../git/errors.js";
@@ -23,7 +23,8 @@ import _usingCtx from "../../_virtual/@oxc-project+runtime/helpers/esm/usingCtx.
23
23
  import { GitBranch } from "../../git/models/branch.js";
24
24
  import { createConflictDetectionError } from "../../git/utils/mergeConflicts.utils.js";
25
25
  import { sortBranches, sortContributors } from "../../git/utils/sorting.js";
26
- import { PageableResult, emptyPagedResult } from "../../utils/paging.js";
26
+ import { HoldOffMap } from "../../utils/holdOffMap.js";
27
+ import { emptyPagedResult } from "../../utils/paging.js";
27
28
  import { parseMergeTreeConflict } from "../parsers/mergeTreeParser.js";
28
29
  import { resolveBranchRemote } from "./branchRemote.js";
29
30
  import { mayConfigDifferByCheckout, parseConfigListing } from "./config.js";
@@ -45,6 +46,13 @@ const nonInteractiveNetworkOptions = {
45
46
  },
46
47
  timeout: 1e4
47
48
  };
49
+ /**
50
+ * How long after a failed read of a remote's default branch off the network (an unreachable host, a refused login, a
51
+ * timeout) the network isn't tried again for that remote
52
+ */
53
+ const failedDefaultBranchLookupWait = 6e4;
54
+ /** The clock a failed default branch lookup's wait is measured on, exported for testing */
55
+ const defaultBranchLookupClock = { now: () => Date.now() };
48
56
  const branchActivityKeys = [
49
57
  "gk-last-accessed",
50
58
  "gk-last-modified",
@@ -81,15 +89,35 @@ function parseReflogLines(content) {
81
89
  const second = first < 0 ? -1 : line.indexOf(" ", first + 1);
82
90
  if (first !== 40 && first !== 64) return void 0;
83
91
  if (second !== first * 2 + 1 || tab >= 0 && tab < second) return void 0;
92
+ const message = tab >= 0 ? line.slice(tab + 1) : void 0;
84
93
  lines.push({
85
94
  from: line.slice(0, first),
86
95
  to: line.slice(first + 1, second),
87
- forward: tab >= 0 && isForwardReflogMessage(line.slice(tab + 1))
96
+ forward: message != null && isForwardReflogMessage(message),
97
+ mergeOrRewrite: message != null && isMergeOrRewriteReflogMessage(message),
98
+ createdFrom: message != null ? getCreatedFromReflogName(message) : void 0
88
99
  });
89
100
  }
90
101
  return lines;
91
102
  }
92
103
  /**
104
+ * Whether git wrote `message` for a merge commit, an amend or a rebase, none of which leaves the ref on a commit whose
105
+ * only parent is the value it moved from. Any command can write any message (`GIT_REFLOG_ACTION`), so this only ever
106
+ * rules such a commit out, never in.
107
+ */
108
+ function isMergeOrRewriteReflogMessage(message) {
109
+ return /^commit \((?:amend|merge)\): /.test(message) || /^rebase\b/.test(message) || /^(?:merge|pull)\b.*: Merge made by /i.test(message);
110
+ }
111
+ /**
112
+ * The name `getReflogCreatedFrom` takes from `message` when its grep (`branch: Created from *.`, a basic regular
113
+ * expression, unanchored) matches it, which a commit's subject can as well as a branch's creation; `undefined` when it
114
+ * doesn't match
115
+ */
116
+ function getCreatedFromReflogName(message) {
117
+ if (!/branch: Created from *./.test(message)) return void 0;
118
+ return /branch: Created from (.*)$/.exec(message)?.[1] ?? "";
119
+ }
120
+ /**
93
121
  * Whether git wrote `message` only for a move to a descendant: a fetch, pull or merge that fast-forwarded, a merge
94
122
  * made, or a commit on the ref. Anything else (a forced update, an update by push, a reset, a rebase, an amend) says
95
123
  * nothing either way. The fetch, pull and merge notes are read only after their own verb, since the messages that
@@ -124,6 +152,20 @@ function isForkPointKeptByReflog(lines, forkPoint, tip) {
124
152
  return true;
125
153
  }
126
154
  /**
155
+ * Whether `lines`, a ref's reflog, show every value it took in the history of its newest one: each line, from the value
156
+ * the line before moved to, moving to a descendant (see {@link isForwardReflogMessage}) or nowhere; the oldest may
157
+ * create the ref
158
+ */
159
+ function isReflogOnlyForward(lines) {
160
+ for (let i = 0; i < lines.length; i++) {
161
+ const { from, to, forward } = lines[i];
162
+ if (i === 0 && /^0+$/.test(from)) continue;
163
+ if (i !== 0 && from !== lines[i - 1].to) return false;
164
+ if (from !== to && !forward) return false;
165
+ }
166
+ return true;
167
+ }
168
+ /**
127
169
  * Where HEAD forked from a base rewritten off `forkPoint`, from `rev-list --left-only --cherry-mark --parents` of
128
170
  * `<forkPoint>...<tip>`: the commits `forkPoint` holds that the base lacks, each `=` when the base holds one of the same
129
171
  * patch (it replayed it, as a rebase does) and `+` when not (HEAD's own). That's the newest commit on their line below
@@ -229,6 +271,18 @@ var BranchesGitSubProvider = class {
229
271
  * measured against one base shares one read of it until it changes
230
272
  */
231
273
  baseReflogs = new LruMap(64);
274
+ /**
275
+ * The fork points git found in their base's tip's history, by `<commonPath>\0<forkPoint>\0<tip>`, for a base carried
276
+ * past a commit (see `getAheadOfBaseAfterCommit`): every commit on a branch asks again while neither moves
277
+ */
278
+ forkPointsInTipHistory = new LruMap(256);
279
+ /**
280
+ * For the local branch tracking a base, what its reflog reaches at its tip (else `false`), by `<commonPath>\0<ref>`,
281
+ * held, as {@link baseMovedForward}'s reads are, for the tip, the reflog and the replace refs it was read under. A
282
+ * move of the branch reaches every worktree measured against the base, so they share the read, and the checked-out
283
+ * branches holding any commit it reaches off the tip's history (by tip sha), read once for the tips in `heads`
284
+ */
285
+ trackingReflogReaches = new LruMap(64);
232
286
  /** Whether the repository at a common git directory keeps its refs and reflogs in reftables, by `<commonPath>` */
233
287
  reftableRepositories = new LruMap(64);
234
288
  /**
@@ -238,6 +292,12 @@ var BranchesGitSubProvider = class {
238
292
  */
239
293
  unfinishedPatchChecks = new LruMap(256);
240
294
  /**
295
+ * Failed network reads of a remote's default branch, by common path and remote (see {@link getDefaultBranchName}),
296
+ * each with the drop stamp taken before it. A drop of the repository's cached default branch since (a change to its
297
+ * remotes or branches, a close or reset) ends it, so a fixed remote is tried again straight away
298
+ */
299
+ failedDefaultBranchLookups = new HoldOffMap(failedDefaultBranchLookupWait, 256, defaultBranchLookupClock);
300
+ /**
241
301
  * When each `commonPath\0branch\0key` was last stamped by this process. Bounded: a dropped entry only costs a
242
302
  * read of the stored stamp, which still holds off a write under 5 minutes old
243
303
  */
@@ -272,21 +332,22 @@ var BranchesGitSubProvider = class {
272
332
  async getBranch(repoPath, name, options, cancellation) {
273
333
  const scope = getScopedLogger();
274
334
  if (options?.force) this.cache.evictCaches(repoPath, "branches");
275
- if (name != null) return (await this.getBranchFromSharedList(repoPath, name, scope, cancellation)).branch;
335
+ if (name != null) return (await this.getBranchFromSharedList(repoPath, (b) => b.name === name, false, scope, cancellation)).branch;
276
336
  const validation = this.cache.validateBeforeRead(repoPath);
277
337
  if (validation != null) await validation;
278
338
  return this.cache.branch.getOrCreate(repoPath, async (cacheable, signal) => {
279
- const result = await this.getBranchFromSharedList(repoPath, void 0, scope, signal);
339
+ const result = await this.getBranchFromSharedList(repoPath, void 0, false, scope, signal);
280
340
  const branch = result.branch ?? await this.getCurrentBranch(repoPath, void 0, void 0, signal);
281
341
  if (!result.kept && (branch == null || branch.date != null || branch.sha != null || branch.upstream != null)) cacheable.invalidate();
282
342
  return branch;
283
343
  }, cancellation);
284
344
  }
285
345
  /**
286
- * What `getBranches(repoPath)` would answer for the named branch, or for the current one when `name` is omitted,
287
- * without keeping that worktree's copy of the whole list, and whether the shared list it read is still kept
346
+ * What `getBranches(repoPath)` would answer for the first branch `matches` accepts, or for the current one when
347
+ * `matches` is omitted, without keeping that worktree's copy of the whole list, and whether the shared list it read
348
+ * is still kept. `matches` sees each entry as the shared list holds it, or as `repoPath` sees it when `mapped`
288
349
  */
289
- async getBranchFromSharedList(repoPath, name, scope, cancellation) {
350
+ async getBranchFromSharedList(repoPath, matches, mapped, scope, cancellation) {
290
351
  if (repoPath == null) return {
291
352
  branch: void 0,
292
353
  kept: true
@@ -301,7 +362,7 @@ var BranchesGitSubProvider = class {
301
362
  };
302
363
  const { currentRef, defaultWorktreePath, isDetached } = await this.getCurrentRefAndDefaultWorktreePath(repoPath, commonPath, cancellation);
303
364
  const isCurrent = (b) => !b.remote && b.name === currentRef?.name && !isDetached;
304
- if (name == null) {
365
+ if (matches == null) {
305
366
  const current = values.find(isCurrent);
306
367
  if (current != null) return {
307
368
  branch: mapSharedBranch(current, repoPath, commonPath, true, defaultWorktreePath, false),
@@ -319,22 +380,27 @@ var BranchesGitSubProvider = class {
319
380
  }
320
381
  const special = isDetached || currentRef != null && !values.some(isCurrent) ? await this.getBranch(repoPath, void 0, void 0, cancellation) : void 0;
321
382
  const replaced = special != null ? values.findIndex((b) => b.remote === special.remote && b.name === special.name) : -1;
322
- if (replaced === -1 && special?.name === name) return {
383
+ if (replaced === -1 && special != null && matches(special)) return {
323
384
  branch: special,
324
385
  kept
325
386
  };
326
- const index = values.findIndex((b, i) => (i === replaced ? special?.name : b.name) === name);
327
- if (index === -1) return {
328
- branch: void 0,
329
- kept
330
- };
331
- if (index === replaced) return {
332
- branch: special,
333
- kept
334
- };
335
- const branch = values[index];
387
+ const mapEntry = (b) => mapSharedBranch(b, repoPath, commonPath, currentRef != null ? isCurrent(b) : void 0, defaultWorktreePath, false);
388
+ for (let i = 0; i < values.length; i++) {
389
+ if (i === replaced) {
390
+ if (special != null && matches(special)) return {
391
+ branch: special,
392
+ kept
393
+ };
394
+ continue;
395
+ }
396
+ const entry = mapped ? mapEntry(values[i]) : values[i];
397
+ if (matches(entry)) return {
398
+ branch: mapped ? entry : mapEntry(entry),
399
+ kept
400
+ };
401
+ }
336
402
  return {
337
- branch: mapSharedBranch(branch, repoPath, commonPath, currentRef != null ? isCurrent(branch) : void 0, defaultWorktreePath, false),
403
+ branch: void 0,
338
404
  kept
339
405
  };
340
406
  }
@@ -674,7 +740,7 @@ var BranchesGitSubProvider = class {
674
740
  return validation != null ? validation.then(() => this.readCurrentBranchReference(repoPath, ordering, cancellation)) : this.readCurrentBranchReference(repoPath, ordering, cancellation);
675
741
  }
676
742
  readCurrentBranchReference(repoPath, ordering, cancellation) {
677
- return this.cache.currentBranchReference.getOrCreate(repoPath, async (_cacheable, signal) => {
743
+ return this.cache.currentBranchReference.getOrCreate(repoPath, async (cacheable, signal) => {
678
744
  const commitOrdering = ordering;
679
745
  let data;
680
746
  let result;
@@ -706,7 +772,13 @@ var BranchesGitSubProvider = class {
706
772
  }
707
773
  if (data == null) {
708
774
  const defaultBranch = await this.provider.config.getConfig(repoPath, "init.defaultBranch") ?? "main";
709
- const configMap = await this.provider.config.getConfigRegex(repoPath, `branch\\.${defaultBranch}\\.+`, { runGitLocally: true });
775
+ let configMap;
776
+ try {
777
+ configMap = await this.provider.config.getConfigRegex(repoPath, `branch\\.${defaultBranch}\\.+`, { runGitLocally: true });
778
+ } catch {
779
+ cacheable.invalidate();
780
+ configMap = /* @__PURE__ */ new Map();
781
+ }
710
782
  const remote = configMap.get(`branch.${defaultBranch}.remote`);
711
783
  const merge = configMap.get(`branch.${defaultBranch}.merge`);
712
784
  const remoteBranch = merge?.startsWith("refs/heads/") ? merge.substring(11) : void 0;
@@ -767,41 +839,57 @@ var BranchesGitSubProvider = class {
767
839
  }
768
840
  }, cancellation);
769
841
  return this.cache.getDefaultBranchName(repoPath, remote, async (commonPath, cacheable, signal) => {
842
+ const failedKey = `${commonPath}\0${remote}`;
843
+ let dropStamp = this.cache.getDropStamp("defaultBranchName", commonPath);
844
+ const networkOptions = {
845
+ cwd: commonPath,
846
+ cancellation: signal ?? cancellation,
847
+ ...priorityOpts,
848
+ ...nonInteractiveNetworkOptions
849
+ };
770
850
  let retried = false;
771
851
  while (true) try {
772
- return (await this.git.run({
852
+ const result = await this.git.run({
773
853
  cwd: commonPath,
774
854
  cancellation: signal ?? cancellation,
775
855
  ...priorityOpts
776
- }, "symbolic-ref", "--short", `refs/remotes/${remote}/HEAD`)).stdout.trim() || void 0;
856
+ }, "symbolic-ref", "--short", `refs/remotes/${remote}/HEAD`);
857
+ this.failedDefaultBranchLookups.release(failedKey);
858
+ return result.stdout.trim() || void 0;
777
859
  } catch (ex) {
778
860
  let answered = false;
779
- if (/is not a symbolic ref/.test(ex.stderr)) try {
780
- if (!retried) {
781
- retried = true;
782
- await this.git.run({
783
- cwd: commonPath,
784
- cancellation: signal ?? cancellation,
785
- ...priorityOpts
786
- }, "remote", "set-head", "-a", remote);
787
- this.cache.deleteDefaultBranchName(commonPath, `${remote}:local`);
788
- continue;
861
+ if (/is not a symbolic ref/.test(ex.stderr)) {
862
+ const failedDropStamp = this.failedDefaultBranchLookups.get(failedKey);
863
+ if (failedDropStamp != null && !retried) {
864
+ if (!this.cache.isDroppedSince("defaultBranchName", commonPath, failedDropStamp)) {
865
+ cacheable.invalidate();
866
+ return;
867
+ }
868
+ this.failedDefaultBranchLookups.release(failedKey);
789
869
  }
790
- const result = await this.git.run({
791
- cwd: commonPath,
792
- cancellation: signal ?? cancellation,
793
- ...priorityOpts
794
- }, "ls-remote", "--symref", remote, "HEAD");
795
- if (result.stdout) {
796
- const match = /ref:\s(\S+)\s+HEAD/m.exec(result.stdout);
797
- if (match != null) {
798
- const [, branch] = match;
799
- return `${remote}/${branch.substring(11).trim()}`;
870
+ try {
871
+ if (!retried) {
872
+ retried = true;
873
+ await this.git.run(networkOptions, "remote", "set-head", "-a", remote);
874
+ this.failedDefaultBranchLookups.release(failedKey);
875
+ this.cache.deleteDefaultBranchName(commonPath, `${remote}:local`);
876
+ dropStamp = this.cache.getDropStamp("defaultBranchName", commonPath);
877
+ continue;
878
+ }
879
+ const result = await this.git.run(networkOptions, "ls-remote", "--symref", remote, "HEAD");
880
+ this.failedDefaultBranchLookups.release(failedKey);
881
+ if (result.stdout) {
882
+ const match = /ref:\s(\S+)\s+HEAD/m.exec(result.stdout);
883
+ if (match != null) {
884
+ const [, branch] = match;
885
+ return `${remote}/${branch.substring(11).trim()}`;
886
+ }
800
887
  }
888
+ answered = true;
889
+ } catch (networkEx) {
890
+ if (isCancellationError(networkEx) && networkEx.reason !== "timeout") throw networkEx;
891
+ if (!this.cache.isDroppedSince("defaultBranchName", commonPath, dropStamp)) this.failedDefaultBranchLookups.hold(failedKey, dropStamp);
801
892
  }
802
- answered = true;
803
- } catch {
804
- if (isCancellationError(ex)) throw ex;
805
893
  }
806
894
  if (!answered) cacheable.invalidate();
807
895
  return;
@@ -1043,8 +1131,18 @@ var BranchesGitSubProvider = class {
1043
1131
  }
1044
1132
  }
1045
1133
  async getLocalBranchByUpstream(repoPath, remoteBranchName, cancellation) {
1046
- const branches = new PageableResult((p) => this.getBranches(repoPath, p != null ? { paging: p } : void 0, cancellation));
1047
- return getLocalBranchByUpstream(remoteBranchName, branches);
1134
+ const scope = getScopedLogger();
1135
+ const qualifiedName = remoteBranchName.startsWith("remotes/") ? remoteBranchName : `remotes/${remoteBranchName}`;
1136
+ const name = qualifiedName.substring(8);
1137
+ return (await this.getBranchFromSharedList(repoPath, (b) => !b.remote && b.upstream?.name != null && (b.upstream.name === name || b.upstream.name === qualifiedName), false, scope, cancellation)).branch;
1138
+ }
1139
+ /**
1140
+ * Whether `getBranches(repoPath)` holds a branch `matches` accepts (any when omitted), judged on each as that list
1141
+ * would hold it, without keeping that worktree's copy of the list
1142
+ */
1143
+ async hasBranch(repoPath, matches, cancellation) {
1144
+ const scope = getScopedLogger();
1145
+ return (await this.getBranchFromSharedList(repoPath, matches ?? (() => true), true, scope, cancellation)).branch != null;
1048
1146
  }
1049
1147
  async getPushTarget(repoPath, branch, cancellation) {
1050
1148
  const records = await this.provider.refs.getRefs(repoPath, cancellation);
@@ -1389,10 +1487,23 @@ var BranchesGitSubProvider = class {
1389
1487
  }
1390
1488
  /**
1391
1489
  * The start point `ref`'s own reflog says it was created from (`branch: Created from <name>`), as git wrote it:
1392
- * a branch, `HEAD`, a sha, a tag or any other revision. `undefined` unless exactly one entry says so. Rejects
1490
+ * a branch, `HEAD`, a sha, a tag or any other revision. `undefined` unless exactly one entry says so. Read from the
1491
+ * reflog's file (see {@link readBaseReflog}) for a local branch the cached ref list names, else from git. Rejects
1393
1492
  * when the reflog can't be read, including for a ref that doesn't exist.
1394
1493
  */
1395
1494
  async getReflogCreatedFrom(repoPath, ref, priority, cancellation) {
1495
+ const lines = await this.readListedBranchReflog(repoPath, ref, cancellation);
1496
+ if (lines != null) {
1497
+ let name;
1498
+ let count = 0;
1499
+ for (const line of lines) {
1500
+ if (line.createdFrom == null) continue;
1501
+ count++;
1502
+ name = line.createdFrom;
1503
+ }
1504
+ if (count !== 1) return void 0;
1505
+ return name || void 0;
1506
+ }
1396
1507
  const entries = await this.provider.refs.getReflogEntries(repoPath, ref, {
1397
1508
  grep: "branch: Created from *.",
1398
1509
  priority
@@ -1557,10 +1668,22 @@ var BranchesGitSubProvider = class {
1557
1668
  }
1558
1669
  async getAheadOfBase(repoPath, branch, options, cancellation) {
1559
1670
  if (branch != null && isDetachedHead(branch)) branch = void 0;
1560
- const reads = createBaseReads("HEAD", branch != null ? [`refs/heads/${branch}`] : [], void 0);
1671
+ let from = "HEAD";
1672
+ if (branch != null && this.cache.readsAreValidated) {
1673
+ const records = await tolerateRead(() => this.provider.refs.getRefs(repoPath, cancellation)) ?? [];
1674
+ if (cancellation?.aborted) throw new CancellationError();
1675
+ const record = findRefRecord(records, `refs/heads/${branch}`);
1676
+ const tip = record != null ? record.peeledObjectname || record.objectname : void 0;
1677
+ if (tip != null && isSha(tip) && record?.worktreePath && normalizePath(record.worktreePath) === normalizePath(repoPath)) from = tip;
1678
+ }
1679
+ const reads = createBaseReads(from, branch != null ? [`refs/heads/${branch}`] : [], void 0);
1561
1680
  const { dependsOn } = reads;
1681
+ const measured = (answer) => answer.base != null && from !== "HEAD" ? {
1682
+ ...answer,
1683
+ measuredFrom: from
1684
+ } : answer;
1562
1685
  const resolved = await this.resolveBase(repoPath, branch, branch, false, options, reads, cancellation);
1563
- if (resolved.kind === "upstream") return withDefaultBranch(await this.measureAheadOfSelfUpstream(repoPath, resolved.upstream, reads, cancellation), reads.localDefault);
1686
+ if (resolved.kind === "upstream") return withBaseReads(measured(await this.measureAheadOfSelfUpstream(repoPath, resolved.upstream, reads, cancellation)), reads);
1564
1687
  if (resolved.kind === "none") {
1565
1688
  let unborn = false;
1566
1689
  if (branch != null) try {
@@ -1568,19 +1691,19 @@ var BranchesGitSubProvider = class {
1568
1691
  } catch (ex) {
1569
1692
  if (isCancellationError(ex)) throw ex;
1570
1693
  }
1571
- return withDefaultBranch({
1694
+ return withBaseReads({
1572
1695
  base: void 0,
1573
1696
  reason: unborn ? "unborn" : "none",
1574
1697
  dependsOn: [...dependsOn]
1575
- }, reads.localDefault);
1698
+ }, reads);
1576
1699
  }
1577
- if (resolved.tier !== "preferred" && branch != null && await this.isSelfAtTip(repoPath, resolved.target.ref, branch, reads, cancellation)) return withDefaultBranch({
1700
+ if (resolved.tier !== "preferred" && branch != null && await this.isSelfAtTip(repoPath, resolved.target.ref, branch, reads, cancellation)) return withBaseReads({
1578
1701
  base: void 0,
1579
1702
  reason: "self",
1580
1703
  dependsOn: [...dependsOn]
1581
- }, reads.localDefault);
1704
+ }, reads);
1582
1705
  const tier = resolved.tier;
1583
- return withDefaultBranch(await this.measureAheadOfBase(repoPath, resolved.target, tier, reads, cancellation), reads.localDefault);
1706
+ return withBaseReads(measured(await this.measureAheadOfBase(repoPath, resolved.target, tier, reads, cancellation)), reads);
1584
1707
  }
1585
1708
  async getAheadOfBaseAfterBaseMove(repoPath, branch, previous, moved, cancellation) {
1586
1709
  const { head, base } = previous;
@@ -1590,14 +1713,18 @@ var BranchesGitSubProvider = class {
1590
1713
  try {
1591
1714
  const records = await this.provider.refs.getRefs(repoPath, cancellation);
1592
1715
  const record = records.length ? resolveRefRecord(records, base.ref) : void 0;
1593
- if (record == null || !moved.includes(record.name)) return void 0;
1716
+ if (record == null) return void 0;
1717
+ const tracking = await this.getMovedTrackingBranch(repoPath, branch, previous, moved, records, record.name, cancellation);
1718
+ if (cancellation?.aborted) throw new CancellationError();
1719
+ if (!moved.includes(record.name) && (tracking == null || moved.some((r) => r !== tracking))) return void 0;
1594
1720
  if (isAmbiguousRefName(records, base.ref)) return void 0;
1721
+ if (!moved.includes(record.name)) return await this.getAheadOfBaseAfterTrackingBranchMove(repoPath, branch, previous, records, record, tracking, cancellation);
1595
1722
  const newTip = record.peeledObjectname || record.objectname;
1596
1723
  if (!newTip || newTip === oldTip) return void 0;
1597
1724
  if (branch != null && !isDetachedHead(branch) && findRefTip(records, `refs/heads/${branch}`) !== head) return;
1598
1725
  let remoteHeadMoved = false;
1599
1726
  for (const ref of moved) {
1600
- if (ref === record.name) continue;
1727
+ if (ref === record.name || ref === tracking) continue;
1601
1728
  if (findRefTip(records, ref) !== newTip || !await this.isRemoteHeadOf(repoPath, ref, record.name, cancellation)) return;
1602
1729
  remoteHeadMoved = true;
1603
1730
  }
@@ -1633,8 +1760,10 @@ var BranchesGitSubProvider = class {
1633
1760
  const past = result.stdout.split("\n").filter((sha) => sha.length > 0);
1634
1761
  if (past.length !== base.ahead || forkPoint != null && past.includes(forkPoint)) return void 0;
1635
1762
  }
1763
+ if (tracking != null && (rewritten || !await this.isTrackingBranchBehindBase(repoPath, records, record.name, tracking, head, newTip, forkPoint, false, cancellation))) return;
1636
1764
  if (rewritten) {
1637
1765
  const reads = {
1766
+ from: "HEAD",
1638
1767
  priority: void 0,
1639
1768
  pinnable: true
1640
1769
  };
@@ -1642,12 +1771,98 @@ var BranchesGitSubProvider = class {
1642
1771
  if (!reads.pinnable || !settled.counted || settled.forkPoint !== forkPoint) return void 0;
1643
1772
  if (settled.ahead !== base.ahead) return void 0;
1644
1773
  }
1645
- return withDefaultBranch({
1774
+ return withDefaultBranch(withMeasuredFrom({
1646
1775
  base: {
1647
1776
  ...base,
1648
1777
  sha: newTip
1649
1778
  },
1650
1779
  dependsOn: [...previous.dependsOn]
1780
+ }, previous.measuredFrom), previous.defaultBranch);
1781
+ } catch (ex) {
1782
+ if (isCancellationError(ex)) throw ex;
1783
+ return;
1784
+ }
1785
+ }
1786
+ async getAheadOfBaseAfterCommit(repoPath, branch, previous, head, cancellation) {
1787
+ const { base } = previous;
1788
+ const { forkPoint, sha: tip } = base;
1789
+ if (branch == null || isDetachedHead(branch) || tip == null) return void 0;
1790
+ if (head === previous.head || !isSha(head) || !isSha(previous.head)) return void 0;
1791
+ if (forkPoint == null || forkPoint === previous.head || base.ahead < 1 || base.tier === "preferred" || base.tier === "upstream" && forkPoint === tip) return;
1792
+ const branchRef = `refs/heads/${branch}`;
1793
+ try {
1794
+ const records = await this.provider.refs.getRefs(repoPath, cancellation);
1795
+ if (findRefTip(records, branchRef) !== head) return void 0;
1796
+ const record = resolveRefRecord(records, base.ref);
1797
+ if (record == null || (record.peeledObjectname || record.objectname) !== tip) return void 0;
1798
+ if (isAmbiguousRefName(records, base.ref) || records.some((r) => r.name.startsWith("refs/replace/"))) return;
1799
+ const lines = await this.readBaseReflog(repoPath, branchRef);
1800
+ if (lines == null) return void 0;
1801
+ const last = lines.at(-1);
1802
+ if (last != null && (last.from !== previous.head || last.to !== head || last.mergeOrRewrite || last.createdFrom != null)) return;
1803
+ if (lines.some((l, i) => i !== 0 && l.createdFrom != null)) return void 0;
1804
+ if ((base.tier === "created" || base.tier === "default") && await this.hasAppearedCandidate(repoPath, branch, previous.dependsOn, records, lines[0]?.createdFrom)) return;
1805
+ if (await this.isShallowRepository(repoPath) !== false) return void 0;
1806
+ if (await this.hasGrafts(repoPath) !== false) return void 0;
1807
+ if (previous.defaultBranch !== void 0) {
1808
+ const defaultBranch = await this.getLocalDefaultBranchName(repoPath, /* @__PURE__ */ new Set(), cancellation);
1809
+ if (cancellation?.aborted) throw new CancellationError();
1810
+ if ((defaultBranch ?? null) !== previous.defaultBranch) return void 0;
1811
+ }
1812
+ if (forkPoint !== tip) {
1813
+ const baseLines = record.name.endsWith("/HEAD") ? void 0 : await this.readBaseReflog(repoPath, record.name);
1814
+ const held = baseLines != null && (baseLines[0]?.from === forkPoint || baseLines.some((l) => l.to === forkPoint)) && isForkPointKeptByReflog(baseLines, forkPoint, tip);
1815
+ const key = `${this.cache.getCommonPath(repoPath)}\0${forkPoint}\0${tip}`;
1816
+ if (!held && !this.forkPointsInTipHistory.has(key)) {
1817
+ const reads = {
1818
+ priority: void 0,
1819
+ pinnable: true
1820
+ };
1821
+ const mergeBase = await this.readMergeBase(repoPath, forkPoint, tip, false, reads, cancellation);
1822
+ if (cancellation?.aborted) throw new CancellationError();
1823
+ if (!reads.pinnable || mergeBase !== forkPoint) return void 0;
1824
+ this.forkPointsInTipHistory.set(key, true);
1825
+ }
1826
+ }
1827
+ const refs = previous.dependsOn.filter((r) => r !== branchRef);
1828
+ const reflogs = await Promise.allSettled(refs.map((r) => this.readBaseReflog(repoPath, r)));
1829
+ const excluded = /* @__PURE__ */ new Set([previous.head]);
1830
+ for (const [i, ref] of refs.entries()) {
1831
+ const refLines = getSettledValue(reflogs[i]);
1832
+ if (refLines == null) return void 0;
1833
+ const refTip = getListedTip(records, ref);
1834
+ if (refTip != null) excluded.add(refTip);
1835
+ for (const { from, to } of refLines) {
1836
+ if (!/^0+$/.test(from)) excluded.add(from);
1837
+ if (!/^0+$/.test(to)) excluded.add(to);
1838
+ }
1839
+ }
1840
+ const result = await this.git.run({
1841
+ cwd: repoPath,
1842
+ cancellation,
1843
+ errors: "ignore",
1844
+ stdin: `${[head, ...Array.from(excluded, (sha) => `^${sha}`)].join("\n")}\n`
1845
+ }, "rev-list", "--parents", "--max-count=2", "--stdin");
1846
+ if (cancellation?.aborted) throw new CancellationError();
1847
+ if (result.completion.status !== "exited" || result.exitCode !== 0) return void 0;
1848
+ if (result.stdout.trim() !== `${head} ${previous.head}`) return void 0;
1849
+ if (previous.measuredFrom !== previous.head) {
1850
+ const counted = await this.git.run({
1851
+ cwd: repoPath,
1852
+ cancellation,
1853
+ errors: "ignore"
1854
+ }, "rev-list", "--count", previous.head, `^${tip}`, "--");
1855
+ if (cancellation?.aborted) throw new CancellationError();
1856
+ if (counted.completion.status !== "exited" || counted.exitCode !== 0) return void 0;
1857
+ if (counted.stdout.trim() !== String(base.ahead)) return void 0;
1858
+ }
1859
+ return withDefaultBranch({
1860
+ base: {
1861
+ ...base,
1862
+ ahead: base.ahead + 1
1863
+ },
1864
+ dependsOn: [...previous.dependsOn],
1865
+ measuredFrom: head
1651
1866
  }, previous.defaultBranch);
1652
1867
  } catch (ex) {
1653
1868
  if (isCancellationError(ex)) throw ex;
@@ -1655,6 +1870,247 @@ var BranchesGitSubProvider = class {
1655
1870
  }
1656
1871
  }
1657
1872
  /**
1873
+ * The full name of the local branch tracking the base `baseRef` (a remote-tracking ref), when `moved` names it: the
1874
+ * default branch the previous read resolved, which the base was compared with as that branch's tracking ref. Only a
1875
+ * branch that exists is ever named the default, so it existed for that read too. `undefined` when `moved` doesn't
1876
+ * name it, it is the branch measured, or anything else lets its move reach the answer: a ref of an `upstream`
1877
+ * remote, whose copy of a candidate contends with it and is skipped at its tip, or another branch that tracks it
1878
+ * locally, which a read would compare it with as that branch's upstream. Its tracking is read from both the ref list
1879
+ * and the config, which must agree.
1880
+ */
1881
+ async getMovedTrackingBranch(repoPath, branch, previous, moved, records, baseRef, cancellation) {
1882
+ const name = previous.defaultBranch;
1883
+ if (!name || name === branch || !baseRef.startsWith("refs/remotes/")) return void 0;
1884
+ const ref = `refs/heads/${name}`;
1885
+ if (!moved.includes(ref)) return void 0;
1886
+ if (findRefRecord(records, ref)?.upstream !== baseRef || isAmbiguousRefName(records, name)) return void 0;
1887
+ const isUpstreamCopy = (r) => r.startsWith("refs/remotes/upstream/") && !r.endsWith("/HEAD");
1888
+ if (previous.dependsOn.some(isUpstreamCopy) || records.some((r) => isUpstreamCopy(r.name))) return void 0;
1889
+ const entries = await this.getAheadOfBaseConfigEntries(repoPath, cancellation);
1890
+ if (entries == null) return void 0;
1891
+ const config = /* @__PURE__ */ new Map();
1892
+ for (const [key, value] of entries) {
1893
+ if (value == null || !key.startsWith("branch.")) continue;
1894
+ const values = config.get(key);
1895
+ if (values == null) config.set(key, [value]);
1896
+ else values.push(value);
1897
+ }
1898
+ const remotes = config.get(`branch.${name}.remote`);
1899
+ const merges = config.get(`branch.${name}.merge`);
1900
+ if (remotes?.length !== 1 || merges?.length !== 1 || !merges[0].startsWith("refs/heads/")) return void 0;
1901
+ if (`refs/remotes/${remotes[0]}/${merges[0].slice(11)}` !== baseRef) return void 0;
1902
+ for (const [key, values] of config) {
1903
+ if (!key.endsWith(".remote") || !values.includes(".")) continue;
1904
+ const other = key.slice(7, -7);
1905
+ if (other === branch) continue;
1906
+ const tracked = config.get(`branch.${other}.merge`);
1907
+ if (tracked?.includes(ref) || tracked?.includes(name)) return void 0;
1908
+ }
1909
+ return ref;
1910
+ }
1911
+ /**
1912
+ * {@link getAheadOfBaseAfterBaseMove} after only `tracking`, the local branch tracking the base (see
1913
+ * {@link getMovedTrackingBranch}), moved: the previous answer, unchanged, while the base, HEAD and the default
1914
+ * branch are as that answer left them and the branch still loses to the base (see
1915
+ * {@link isTrackingBranchBehindBase}). `record` is the base's listed ref.
1916
+ */
1917
+ async getAheadOfBaseAfterTrackingBranchMove(repoPath, branch, previous, records, record, tracking, cancellation) {
1918
+ const { head, base } = previous;
1919
+ const tip = record.peeledObjectname || record.objectname;
1920
+ if (!tip || tip !== base.sha) return void 0;
1921
+ if (branch != null && !isDetachedHead(branch) && findRefTip(records, `refs/heads/${branch}`) !== head) return;
1922
+ const defaultBranch = await this.getLocalDefaultBranchName(repoPath, /* @__PURE__ */ new Set(), cancellation);
1923
+ if (cancellation?.aborted) throw new CancellationError();
1924
+ if ((defaultBranch ?? null) !== previous.defaultBranch) return void 0;
1925
+ if (await this.isShallowRepository(repoPath) !== false) return void 0;
1926
+ if (!await this.isTrackingBranchBehindBase(repoPath, records, record.name, tracking, head, tip, base.forkPoint, true, cancellation)) return void 0;
1927
+ return withDefaultBranch(withMeasuredFrom({
1928
+ base: { ...base },
1929
+ dependsOn: [...previous.dependsOn]
1930
+ }, previous.measuredFrom), previous.defaultBranch);
1931
+ }
1932
+ /**
1933
+ * Whether `tracking`, the local branch tracking the base `baseRef` at `baseTip` (see {@link getMovedTrackingBranch}),
1934
+ * still loses to the base for HEAD at `head`, which forked from the base at `forkPoint`.
1935
+ *
1936
+ * A full read compares the branch with the base as its tracking ref (see {@link getNearestForkTarget}), and the base
1937
+ * wins, with its own settled fork point whatever the branch's tip, whenever git reads the branch (`--fork-point`,
1938
+ * else the merge base: either way a commit HEAD shares with the branch's tip or a value of its reflog) at or below
1939
+ * where it reads the base. Nothing else in that read depends on the branch (see {@link getMovedTrackingBranch}), so
1940
+ * the base's answer stands. Git's reading of the base is never below `forkPoint`: settling only moves down from it,
1941
+ * and the base's tip (when the base is in HEAD's history) and the merge base are at or below it too, as the base's
1942
+ * reflog holds its tip. So it is enough that HEAD shares nothing past `forkPoint` with the branch's tip and reflog:
1943
+ * HEAD's commits they don't reach are as many as HEAD's commits past `forkPoint`, which they reach. Those are counted
1944
+ * past the branch's tip and past `forkPoint` once for every checked-out branch, when nothing the reflog reaches off
1945
+ * the tip's history is HEAD's; else listed by HEAD's own walk past all of it, `forkPoint` not among them.
1946
+ *
1947
+ * At the base's own tip no count is needed: with nothing the branch's reflog reaches off the tip's history in HEAD's,
1948
+ * HEAD shares with the branch exactly what it shares with the base's tip, which the base's reflog holds. When git
1949
+ * finds the one best common ancestor of HEAD and the base's reflog, everything the branch shares with HEAD is at or
1950
+ * below it; when it reads the base's merge base with HEAD instead, the branch reads as that same commit, whether as
1951
+ * the one best common ancestor of HEAD and the tip both share or as the merge base of the same two commits.
1952
+ *
1953
+ * The base's reflog must hold its tip as its newest value, or be empty, when `--fork-point` reads the tip alone
1954
+ * (`checkBaseReflog` reads it for a caller that hasn't); the branch's must end at its tip.
1955
+ */
1956
+ async isTrackingBranchBehindBase(repoPath, records, baseRef, tracking, head, baseTip, forkPoint, checkBaseReflog, cancellation) {
1957
+ if (forkPoint == null) return false;
1958
+ const tip = getListedTip(records, tracking);
1959
+ if (tip == null) return false;
1960
+ if (checkBaseReflog) {
1961
+ const reflog = await this.readReflogValues(repoPath, this.cache.getCommonPath(repoPath), baseRef);
1962
+ if (cancellation?.aborted) throw new CancellationError();
1963
+ if (!reflog || reflog.values.length !== 0 && reflog.values[0] !== baseTip) return false;
1964
+ }
1965
+ const reach = await this.getTrackingReflogReach(repoPath, records, tracking, tip, head);
1966
+ if (cancellation?.aborted) throw new CancellationError();
1967
+ if (reach == null) return false;
1968
+ if (!reach.offHead && (tip === baseTip || tip === forkPoint)) return true;
1969
+ const pastForkPoint = await this.getAheadOfMovedBase(repoPath, records, forkPoint, head);
1970
+ if (cancellation?.aborted) throw new CancellationError();
1971
+ if (pastForkPoint == null) return false;
1972
+ if (reach.offHead) {
1973
+ const result = await this.git.run({
1974
+ cwd: repoPath,
1975
+ cancellation,
1976
+ errors: "ignore"
1977
+ }, "rev-list", `--max-count=${pastForkPoint + 1}`, head, "--not", tip, ...reach.offHistory, "--");
1978
+ if (cancellation?.aborted) throw new CancellationError();
1979
+ if (result.completion.status !== "exited" || result.exitCode !== 0) return false;
1980
+ const past = result.stdout.split("\n").filter((sha) => sha.length > 0);
1981
+ return past.length === pastForkPoint && !past.includes(forkPoint);
1982
+ }
1983
+ if (!reach.logged.has(forkPoint)) {
1984
+ const checks = {
1985
+ priority: void 0,
1986
+ pinnable: true
1987
+ };
1988
+ const mergeBase = await this.readMergeBase(repoPath, forkPoint, tip, false, checks, cancellation);
1989
+ if (cancellation?.aborted) throw new CancellationError();
1990
+ if (!checks.pinnable || mergeBase !== forkPoint) return false;
1991
+ }
1992
+ const pastTip = await this.getAheadOfMovedBase(repoPath, records, tip, head);
1993
+ if (cancellation?.aborted) throw new CancellationError();
1994
+ return pastTip === pastForkPoint;
1995
+ }
1996
+ /**
1997
+ * What `ref`'s reflog reaches at `tip` (see {@link trackingReflogReaches}), and whether any of it off the tip's
1998
+ * history is in `head`'s, or that can't be told from the checked-out branches; `undefined` when its reflog is empty
1999
+ * or doesn't end at `tip`, reaches too much off `tip`'s history to tell, or git couldn't say
2000
+ */
2001
+ async getTrackingReflogReach(repoPath, records, ref, tip, head) {
2002
+ const commonPath = this.cache.getCommonPath(repoPath);
2003
+ const key = `${commonPath}\0${ref}`;
2004
+ const inputs = getBaseMoveReadInputs(records);
2005
+ const reflog = (await this.getReflogSource(repoPath, ref))?.stamp ?? inputs;
2006
+ const { checkedOut, checkedOutTips, replaced } = inputs;
2007
+ let slot = this.trackingReflogReaches.get(key);
2008
+ if (slot == null || slot.tip !== tip || slot.reflog !== reflog || slot.replaced !== replaced) {
2009
+ slot = {
2010
+ tip,
2011
+ reflog,
2012
+ replaced,
2013
+ read: this.readTrackingReflogReach(repoPath, commonPath, ref, tip)
2014
+ };
2015
+ this.trackingReflogReaches.set(key, slot);
2016
+ } else this.trackingReflogReaches.touch(key);
2017
+ const { read } = slot;
2018
+ const reach = await read;
2019
+ if (reach === void 0 && this.trackingReflogReaches.get(key)?.read === read) this.trackingReflogReaches.delete(key);
2020
+ if (!reach) return void 0;
2021
+ if (!reach.offHistory.length) return {
2022
+ ...reach,
2023
+ offHead: false
2024
+ };
2025
+ if (!checkedOut?.size || !checkedOutTips.has(head)) return {
2026
+ ...reach,
2027
+ offHead: true
2028
+ };
2029
+ let { heads } = slot;
2030
+ if (heads == null || !heads.tips.has(head)) {
2031
+ heads = {
2032
+ tips: checkedOutTips,
2033
+ read: this.readHeadsHolding(commonPath, checkedOut, reach.offHistory)
2034
+ };
2035
+ slot.heads = heads;
2036
+ }
2037
+ const holding = await heads.read;
2038
+ if (holding === void 0 && slot.heads === heads) slot.heads = void 0;
2039
+ return {
2040
+ ...reach,
2041
+ offHead: holding?.has(head) ?? true
2042
+ };
2043
+ }
2044
+ /**
2045
+ * Reads {@link getTrackingReflogReach}'s reach, in `commonPath`, without spawning when the reflog's file shows only
2046
+ * moves forward. Not bound to one caller's cancellation, since every worktree the move reached rides this one read.
2047
+ * `false` when the reflog is empty or doesn't end at `tip`, or reaches too much off its history to tell; `undefined`
2048
+ * when git couldn't say.
2049
+ */
2050
+ async readTrackingReflogReach(repoPath, commonPath, ref, tip) {
2051
+ const lines = await this.readBaseReflog(repoPath, ref);
2052
+ if (lines?.length && lines.at(-1).to === tip && isReflogOnlyForward(lines)) {
2053
+ const logged = new Set(lines.map((l) => l.to));
2054
+ if (!/^0+$/.test(lines[0].from)) logged.add(lines[0].from);
2055
+ logged.delete(tip);
2056
+ return {
2057
+ offHistory: [],
2058
+ logged
2059
+ };
2060
+ }
2061
+ const reflog = await this.readReflogValues(repoPath, commonPath, ref);
2062
+ if (!reflog) return reflog;
2063
+ const { values, before } = reflog;
2064
+ if (!values.length || values[0] !== tip) return false;
2065
+ const logged = new Set(values);
2066
+ if (before != null) logged.add(before);
2067
+ logged.delete(tip);
2068
+ if (!logged.size) return {
2069
+ offHistory: [],
2070
+ logged
2071
+ };
2072
+ try {
2073
+ const result = await this.git.run({
2074
+ cwd: commonPath,
2075
+ errors: "ignore",
2076
+ stdin: `${[...logged, `^${tip}`].join("\n")}\n`
2077
+ }, "rev-list", `--max-count=65`, "--stdin");
2078
+ if (result.completion.status !== "exited" || result.exitCode !== 0) return void 0;
2079
+ const off = result.stdout.split("\n").filter((sha) => sha.length > 0);
2080
+ if (off.length > maxOffHistoryCommits) return false;
2081
+ return {
2082
+ offHistory: off,
2083
+ logged
2084
+ };
2085
+ } catch {
2086
+ return;
2087
+ }
2088
+ }
2089
+ /**
2090
+ * The tips of the `checkedOut` branches holding any of `commits`, from one `for-each-ref` in `commonPath`, which holds
2091
+ * every worktree's branches; `undefined` when git couldn't say
2092
+ */
2093
+ async readHeadsHolding(commonPath, checkedOut, commits) {
2094
+ try {
2095
+ const patterns = toRefPatterns(checkedOut) ?? ["refs/heads"];
2096
+ const result = await this.git.run({
2097
+ cwd: commonPath,
2098
+ errors: "ignore"
2099
+ }, "for-each-ref", "--format=%(refname)%09%(objectname)", ...commits.map((sha) => `--contains=${sha}`), ...patterns);
2100
+ if (result.completion.status !== "exited" || result.exitCode !== 0) return void 0;
2101
+ const holding = /* @__PURE__ */ new Set();
2102
+ for (const line of result.stdout.split("\n")) {
2103
+ if (!line) continue;
2104
+ const [ref, sha] = line.split(" ");
2105
+ if (!ref || !sha) return void 0;
2106
+ if (checkedOut.has(ref)) holding.add(sha);
2107
+ }
2108
+ return holding;
2109
+ } catch {
2110
+ return;
2111
+ }
2112
+ }
2113
+ /**
1658
2114
  * Whether the repository is shallow, by its common git directory's `shallow` file, which spawns nothing; `undefined`
1659
2115
  * when it can't be read
1660
2116
  */
@@ -1666,6 +2122,38 @@ var BranchesGitSubProvider = class {
1666
2122
  return;
1667
2123
  }
1668
2124
  }
2125
+ /**
2126
+ * Whether the repository has a grafts file, which rewrites the parents every walk sees, by its common git directory's
2127
+ * `info/grafts`, which spawns nothing; `undefined` when it can't be read
2128
+ */
2129
+ async hasGrafts(repoPath) {
2130
+ try {
2131
+ const gitDir = await this.provider.config.getGitDir(repoPath);
2132
+ return await this.context.fs.stat(joinUriPath(gitDir.commonUri ?? gitDir.uri, "info", "grafts")) != null;
2133
+ } catch {
2134
+ return;
2135
+ }
2136
+ }
2137
+ /**
2138
+ * Whether `records`, the cached ref list, now lists a ref a base read for `branch` that compared the created-from and
2139
+ * default candidates would compare too, but which isn't among `dependsOn`, the refs that read depended on, as it
2140
+ * leaves out one that was absent: the branch `createdFrom` names (as the branch's reflog gives it, see
2141
+ * {@link getListedBaseName}), unless it is the branch itself or its copy on a remote, or the `upstream` remote's
2142
+ * copy of a candidate `dependsOn` names (see {@link getUpstreamContender}), matched by its name's end alone
2143
+ */
2144
+ async hasAppearedCandidate(repoPath, branch, dependsOn, records, createdFrom) {
2145
+ const depended = new Set(dependsOn);
2146
+ if (createdFrom && createdFrom !== "HEAD" && !createdFrom.startsWith("-") && !await this.isSelfRef(repoPath, createdFrom, branch, void 0)) {
2147
+ if ((createdFrom.startsWith("refs/heads/") || createdFrom.startsWith("refs/remotes/") ? [createdFrom] : [`refs/heads/${createdFrom}`, `refs/remotes/${createdFrom}`]).some((n) => findRefRecord(records, n) != null && !depended.has(n))) return true;
2148
+ }
2149
+ const own = `refs/heads/${branch}`;
2150
+ for (const { name } of records) {
2151
+ if (!name.startsWith("refs/remotes/upstream/") || name.endsWith("/HEAD") || depended.has(name)) continue;
2152
+ const suffix = name.slice(21);
2153
+ if (dependsOn.some((r) => r !== own && r.endsWith(suffix))) return true;
2154
+ }
2155
+ return false;
2156
+ }
1669
2157
  /** Whether `ref` is a `refs/remotes/<remote>/HEAD` symref pointing at `target`, from the cached local symref */
1670
2158
  async isRemoteHeadOf(repoPath, ref, target, cancellation) {
1671
2159
  if (!ref.startsWith("refs/remotes/") || !ref.endsWith("/HEAD")) return false;
@@ -2309,7 +2797,7 @@ var BranchesGitSubProvider = class {
2309
2797
  /** Counts HEAD's commits past `target` for {@link getAheadOfBase} */
2310
2798
  async measureAheadOfBase(repoPath, target, tier, reads, cancellation) {
2311
2799
  const { dependsOn } = reads;
2312
- const [countsResult, refsResult] = await Promise.allSettled([this.countAgainstBase(repoPath, target.ref, cancellation), this.provider.refs.getRefs(repoPath, cancellation)]);
2800
+ const [countsResult, refsResult] = await Promise.allSettled([this.countAgainstBase(repoPath, target.ref, reads.from, cancellation), this.provider.refs.getRefs(repoPath, cancellation)]);
2313
2801
  if (cancellation?.aborted) throw new CancellationError();
2314
2802
  if (countsResult.status === "rejected") throw countsResult.reason;
2315
2803
  const counts = countsResult.value;
@@ -2351,7 +2839,7 @@ var BranchesGitSubProvider = class {
2351
2839
  counted: false
2352
2840
  };
2353
2841
  try {
2354
- const counts = await this.countAgainstBase(repoPath, forkPoint, cancellation);
2842
+ const counts = await this.countAgainstBase(repoPath, forkPoint, reads.from, cancellation);
2355
2843
  if (counts != null) return {
2356
2844
  forkPoint,
2357
2845
  ahead: counts.right,
@@ -2365,17 +2853,17 @@ var BranchesGitSubProvider = class {
2365
2853
  priority: reads.priority,
2366
2854
  pinnable: true
2367
2855
  };
2368
- const mergeBase = await this.readMergeBase(repoPath, "HEAD", ref, false, read, cancellation);
2856
+ const mergeBase = await this.readMergeBase(repoPath, reads.from, ref, false, read, cancellation);
2369
2857
  return {
2370
2858
  forkPoint: read.pinnable ? mergeBase : forkPoint,
2371
2859
  ahead,
2372
2860
  counted: false
2373
2861
  };
2374
2862
  }
2375
- /** {@link settleForkPoint} from HEAD, then {@link countPastForkPoint} */
2863
+ /** {@link settleForkPoint} from `reads.from`, then {@link countPastForkPoint} */
2376
2864
  async settleForkPointAndCount(repoPath, records, ref, tip, forkPoint, ahead, reads, cancellation) {
2377
2865
  const fromHead = {
2378
- from: "HEAD",
2866
+ from: reads.from,
2379
2867
  priority: reads.priority,
2380
2868
  pinnable: true
2381
2869
  };
@@ -2508,6 +2996,17 @@ var BranchesGitSubProvider = class {
2508
2996
  if (result === void 0 && this.baseReflogs.get(key)?.lines === lines) this.baseReflogs.delete(key);
2509
2997
  return result;
2510
2998
  }
2999
+ /**
3000
+ * {@link readBaseReflog} of `ref`, a local branch's full name, in place of git's reading of it; `undefined` when only
3001
+ * git can say. Git rejects a ref that doesn't exist, even when a reflog file is left for it, so the file is taken
3002
+ * only for a branch the cached ref list names.
3003
+ */
3004
+ async readListedBranchReflog(repoPath, ref, cancellation) {
3005
+ if (!ref.startsWith("refs/heads/")) return void 0;
3006
+ const lines = await this.readBaseReflog(repoPath, ref);
3007
+ if (lines == null) return void 0;
3008
+ return findRefRecord(await this.provider.refs.getRefs(repoPath, cancellation), ref) != null ? lines : void 0;
3009
+ }
2511
3010
  /** Counts the default branch's own commits past its upstream (see {@link getSelfUpstreamTarget}) for {@link getAheadOfBase} */
2512
3011
  async measureAheadOfSelfUpstream(repoPath, upstream, reads, cancellation) {
2513
3012
  const { dependsOn } = reads;
@@ -2517,7 +3016,7 @@ var BranchesGitSubProvider = class {
2517
3016
  reason: "self",
2518
3017
  dependsOn: [...dependsOn]
2519
3018
  };
2520
- const counts = await this.countAgainstBase(repoPath, upstream.ref, cancellation);
3019
+ const counts = await this.countAgainstBase(repoPath, upstream.ref, reads.from, cancellation);
2521
3020
  if (counts == null) return {
2522
3021
  base: void 0,
2523
3022
  reason: "unborn",
@@ -2551,11 +3050,12 @@ var BranchesGitSubProvider = class {
2551
3050
  };
2552
3051
  }
2553
3052
  /**
2554
- * HEAD's count against `ref` from their merge base: `left` only `ref` has, `right` only HEAD has. `undefined`
2555
- * before HEAD's first commit, when there is nothing to count; any other failure rejects with git's error.
3053
+ * `from`'s count (HEAD, or a commit) against `ref` from their merge base: `left` only `ref` has, `right` only `from`
3054
+ * has. `undefined` before HEAD's first commit, when there is nothing to count; any other failure rejects with git's
3055
+ * error.
2556
3056
  */
2557
- async countAgainstBase(repoPath, ref, cancellation) {
2558
- const range = createRevisionRange(ref, "HEAD", "...");
3057
+ async countAgainstBase(repoPath, ref, from, cancellation) {
3058
+ const range = createRevisionRange(ref, from, "...");
2559
3059
  let counts;
2560
3060
  try {
2561
3061
  counts = await this.provider.commits.getLeftRightCommitCount(repoPath, range, void 0, cancellation);
@@ -2568,7 +3068,7 @@ var BranchesGitSubProvider = class {
2568
3068
  return await this.getLeftRightCountUncached(repoPath, range, cancellation);
2569
3069
  } catch (ex) {
2570
3070
  if (isCancellationError(ex)) throw ex;
2571
- if (await this.isUnbornHead(repoPath, cancellation)) return void 0;
3071
+ if (from === "HEAD" && await this.isUnbornHead(repoPath, cancellation)) return void 0;
2572
3072
  throw ex;
2573
3073
  }
2574
3074
  }
@@ -2729,7 +3229,8 @@ var BranchesGitSubProvider = class {
2729
3229
  }
2730
3230
  /**
2731
3231
  * Whether `ref` names `selfName` itself (see {@link isSelfRef}) and sits at `reads.from`'s commit; tips are read
2732
- * only after the name matched. HEAD's commit is asked of git, a branch's read from the cached ref list
3232
+ * only after the name matched. HEAD's commit is asked of git, a branch's read from the cached ref list, and a commit
3233
+ * is itself
2733
3234
  */
2734
3235
  async isSelfAtTip(repoPath, ref, selfName, reads, cancellation) {
2735
3236
  if (!await this.isSelfRef(repoPath, ref, selfName, cancellation)) return false;
@@ -2738,7 +3239,7 @@ var BranchesGitSubProvider = class {
2738
3239
  return refSha != null && refSha === headSha;
2739
3240
  }
2740
3241
  const records = await this.provider.refs.getRefs(repoPath, cancellation);
2741
- const [refSha, fromSha] = await Promise.all([this.getRefTip(repoPath, records, ref, cancellation), this.getRefTip(repoPath, records, reads.from, cancellation)]);
3242
+ const [refSha, fromSha] = await Promise.all([this.getRefTip(repoPath, records, ref, cancellation), isSha(reads.from) ? reads.from : this.getRefTip(repoPath, records, reads.from, cancellation)]);
2742
3243
  return refSha != null && refSha === fromSha;
2743
3244
  }
2744
3245
  /** The remotes a default branch is read from, in order: `upstream`, `origin`, then the first remote */
@@ -2941,13 +3442,32 @@ var BranchesGitSubProvider = class {
2941
3442
  };
2942
3443
  }
2943
3444
  /**
2944
- * `<name>@{u}`, without asking git when the cached ref list shows `name` can't have one: a failed lookup isn't
2945
- * cached, so asking it of a remote-tracking ref (`origin/main`, the usual default) re-spawns on every read. The
2946
- * list's own upstream isn't used: a config-only change (`git branch -u`) doesn't refresh it.
3445
+ * `<name>@{u}`, without asking git when the cached ref list shows `name` can't have one, as a remote-tracking ref
3446
+ * (`origin/main`, the usual default) can't. A local branch the list names is asked in the main checkout, so the
3447
+ * repository's checkouts share one read, unless the config listing the base read took shows config that can differ
3448
+ * by checkout. The list's own upstream isn't the same answer: it names an upstream that is gone, which this reports
3449
+ * as none, and can differ for one outside `refs/remotes/` or a short name that is ambiguous.
2947
3450
  */
2948
3451
  async getUpstreamName(repoPath, name, options, cancellation) {
2949
- if (!mayHaveUpstream(await this.provider.refs.getRefs(repoPath, cancellation), name)) return void 0;
2950
- return this.provider.refs.getSymbolicReferenceName(repoPath, `${name}@{u}`, options, cancellation);
3452
+ const records = await this.provider.refs.getRefs(repoPath, cancellation);
3453
+ if (!mayHaveUpstream(records, name)) return void 0;
3454
+ const path = name !== "HEAD" && findRefRecord(records, `refs/heads/${name}`) != null && await this.isConfigSharedByCheckouts(repoPath) ? this.cache.getCommonPath(repoPath) : repoPath;
3455
+ return this.provider.refs.getSymbolicReferenceName(path, `${name}@{u}`, options, cancellation);
3456
+ }
3457
+ /**
3458
+ * Whether `repoPath`'s config is its repository's main checkout's, as the config listing already read for its base
3459
+ * shows it (see `mayConfigDifferByCheckout`). Never reads the listing: `false` when there is none to go by.
3460
+ */
3461
+ async isConfigSharedByCheckouts(repoPath) {
3462
+ if (this.cache.getCommonPath(repoPath) === repoPath) return true;
3463
+ const listing = this.cache.aheadOfBaseConfigKey.get(repoPath);
3464
+ if (listing == null) return false;
3465
+ try {
3466
+ const value = await listing;
3467
+ return value != null && !mayConfigDifferByCheckout(value);
3468
+ } catch {
3469
+ return false;
3470
+ }
2951
3471
  }
2952
3472
  /**
2953
3473
  * The base for a branch that is itself the default branch, with its tip: its own upstream, `upstream/<branch>`
@@ -3253,6 +3773,10 @@ __decorate([debug({
3253
3773
  quiet: true,
3254
3774
  exit: true
3255
3775
  })], BranchesGitSubProvider.prototype, "getAheadOfBaseAfterBaseMove", null);
3776
+ __decorate([debug({
3777
+ quiet: true,
3778
+ exit: true
3779
+ })], BranchesGitSubProvider.prototype, "getAheadOfBaseAfterCommit", null);
3256
3780
  __decorate([debug({
3257
3781
  quiet: true,
3258
3782
  exit: true
@@ -3393,6 +3917,13 @@ function mayHaveUpstream(records, name) {
3393
3917
  if (findRefTip(records, `refs/heads/${name}`) != null) return true;
3394
3918
  return findRefTip(records, name) == null;
3395
3919
  }
3920
+ /** `answer` with the commit it was measured from, when it is known (see `AheadOfBase.measuredFrom`) */
3921
+ function withMeasuredFrom(answer, measuredFrom) {
3922
+ return measuredFrom !== void 0 ? {
3923
+ ...answer,
3924
+ measuredFrom
3925
+ } : answer;
3926
+ }
3396
3927
  /** `answer` with the default branch its read resolved, when it consulted one (see `AheadOfBase.defaultBranch`) */
3397
3928
  function withDefaultBranch(answer, defaultBranch) {
3398
3929
  return defaultBranch !== void 0 ? {
@@ -3401,6 +3932,17 @@ function withDefaultBranch(answer, defaultBranch) {
3401
3932
  } : answer;
3402
3933
  }
3403
3934
  /**
3935
+ * `answer`, a full read's, with what `reads` adds to it: the default branch it resolved, and `provisional` when it rests
3936
+ * on a read that failed, the answers `getMergeTarget` doesn't cache
3937
+ */
3938
+ function withBaseReads(answer, reads) {
3939
+ const withDefault = withDefaultBranch(answer, reads.localDefault);
3940
+ return reads.pinnable ? withDefault : {
3941
+ ...withDefault,
3942
+ provisional: true
3943
+ };
3944
+ }
3945
+ /**
3404
3946
  * Adds the full ref names a `.git/refs` watcher would report for `name`. A short name can't be told tag from local
3405
3947
  * from remote without a spawn, so it adds every form, including the tag git resolves it to first; a spurious one
3406
3948
  * only costs a recompute.
@@ -3457,6 +3999,6 @@ function getListedTip(records, fullName) {
3457
3999
  return record != null ? record.peeledObjectname || record.objectname : void 0;
3458
4000
  }
3459
4001
  //#endregion
3460
- export { BranchesGitSubProvider, patchCheckClock };
4002
+ export { BranchesGitSubProvider, defaultBranchLookupClock, patchCheckClock };
3461
4003
 
3462
4004
  //# sourceMappingURL=branches.js.map