@gitkraken/core-gitlens 0.28.0 → 0.30.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 (120) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/dist/git/cache.d.ts +39 -1
  3. package/dist/git/cache.js +108 -7
  4. package/dist/git/cache.js.map +1 -1
  5. package/dist/git/providers/branches.d.ts +17 -12
  6. package/dist/git/providers/revision.d.ts +4 -0
  7. package/dist/git/watching/worktreeSummary.d.ts +16 -7
  8. package/dist/git/watching/worktreeSummary.js +44 -14
  9. package/dist/git/watching/worktreeSummary.js.map +1 -1
  10. package/dist/git-cli/cliGitProvider.js +3 -3
  11. package/dist/git-cli/cliGitProvider.js.map +1 -1
  12. package/dist/git-cli/exec/exec.d.ts +2 -2
  13. package/dist/git-cli/exec/exec.js +2 -2
  14. package/dist/git-cli/exec/gitDirResolver.d.ts +6 -1
  15. package/dist/git-cli/exec/gitDirResolver.js +9 -4
  16. package/dist/git-cli/exec/gitDirResolver.js.map +1 -1
  17. package/dist/git-cli/providers/branches.d.ts +91 -13
  18. package/dist/git-cli/providers/branches.js +673 -176
  19. package/dist/git-cli/providers/branches.js.map +1 -1
  20. package/dist/git-cli/providers/config.js +1 -1
  21. package/dist/git-cli/providers/config.js.map +1 -1
  22. package/dist/git-cli/providers/revision.d.ts +4 -0
  23. package/dist/git-cli/providers/revision.js +64 -3
  24. package/dist/git-cli/providers/revision.js.map +1 -1
  25. package/dist/ipc/ipcServer.d.ts +6 -1
  26. package/dist/ipc/ipcServer.js +15 -6
  27. package/dist/ipc/ipcServer.js.map +1 -1
  28. package/dist/plus/ai/errors.js +4 -4
  29. package/dist/plus/ai/errors.js.map +1 -1
  30. package/dist/plus/ai/models/model.d.ts +1 -1
  31. package/dist/plus/ai/models/model.js.map +1 -1
  32. package/dist/plus/ai/models/promptTemplates.d.ts +45 -2
  33. package/dist/plus/ai/models/results.d.ts +41 -0
  34. package/dist/plus/ai/models/results.js +14 -0
  35. package/dist/plus/ai/models/results.js.map +1 -0
  36. package/dist/plus/ai/prompts.d.ts +6 -0
  37. package/dist/plus/ai/prompts.js +255 -5
  38. package/dist/plus/ai/prompts.js.map +1 -1
  39. package/dist/plus/ai/providers/gitkrakenProvider.js +2 -2
  40. package/dist/plus/ai/providers/gitkrakenProvider.js.map +1 -1
  41. package/dist/plus/ai/providers/openAICompatibleProviderBase.js +1 -0
  42. package/dist/plus/ai/providers/openAICompatibleProviderBase.js.map +1 -1
  43. package/dist/plus/ai/utils/ai.utils.d.ts +4 -0
  44. package/dist/plus/ai/utils/ai.utils.js +8 -1
  45. package/dist/plus/ai/utils/ai.utils.js.map +1 -1
  46. package/dist/plus/ai/utils/results.utils.d.ts +15 -1
  47. package/dist/plus/ai/utils/results.utils.js +80 -4
  48. package/dist/plus/ai/utils/results.utils.js.map +1 -1
  49. package/dist/plus/integrations/authentication/integrationAuthenticationService.js +2 -0
  50. package/dist/plus/integrations/authentication/integrationAuthenticationService.js.map +1 -1
  51. package/dist/plus/integrations/authentication/models.d.ts +1 -1
  52. package/dist/plus/integrations/authentication/models.js +2 -0
  53. package/dist/plus/integrations/authentication/models.js.map +1 -1
  54. package/dist/plus/integrations/constants.d.ts +2 -1
  55. package/dist/plus/integrations/constants.js +12 -2
  56. package/dist/plus/integrations/constants.js.map +1 -1
  57. package/dist/plus/integrations/fieldPresence.js +17 -1
  58. package/dist/plus/integrations/fieldPresence.js.map +1 -1
  59. package/dist/plus/integrations/integrationService.d.ts +1 -1
  60. package/dist/plus/integrations/integrationService.js +8 -2
  61. package/dist/plus/integrations/integrationService.js.map +1 -1
  62. package/dist/plus/integrations/lite.js +5 -6
  63. package/dist/plus/integrations/lite.js.map +1 -1
  64. package/dist/plus/integrations/models/gitHostIntegration.d.ts +11 -1
  65. package/dist/plus/integrations/models/gitHostIntegration.js.map +1 -1
  66. package/dist/plus/integrations/providers/asana.d.ts +91 -0
  67. package/dist/plus/integrations/providers/asana.js +344 -0
  68. package/dist/plus/integrations/providers/asana.js.map +1 -0
  69. package/dist/plus/integrations/providers/azure/azure.js +3 -2
  70. package/dist/plus/integrations/providers/azure/azure.js.map +1 -1
  71. package/dist/plus/integrations/providers/azure/models.js +3 -2
  72. package/dist/plus/integrations/providers/azure/models.js.map +1 -1
  73. package/dist/plus/integrations/providers/azureDevOps.d.ts +7 -1
  74. package/dist/plus/integrations/providers/azureDevOps.js +9 -1
  75. package/dist/plus/integrations/providers/azureDevOps.js.map +1 -1
  76. package/dist/plus/integrations/providers/bitbucket-server/discovery.js +2 -1
  77. package/dist/plus/integrations/providers/bitbucket-server/discovery.js.map +1 -1
  78. package/dist/plus/integrations/providers/bitbucket-server/models.js.map +1 -1
  79. package/dist/plus/integrations/providers/github.d.ts +2 -2
  80. package/dist/plus/integrations/providers/github.js +2 -2
  81. package/dist/plus/integrations/providers/github.js.map +1 -1
  82. package/dist/plus/integrations/providers/issueSorts.d.ts +5 -0
  83. package/dist/plus/integrations/providers/issueSorts.js +6 -1
  84. package/dist/plus/integrations/providers/issueSorts.js.map +1 -1
  85. package/dist/plus/integrations/providers/jiraIssueByKey.js +2 -1
  86. package/dist/plus/integrations/providers/jiraIssueByKey.js.map +1 -1
  87. package/dist/plus/integrations/providers/models.d.ts +19 -3
  88. package/dist/plus/integrations/providers/models.js +12 -1
  89. package/dist/plus/integrations/providers/models.js.map +1 -1
  90. package/dist/plus/integrations/providers/providerApiClient.d.ts +0 -3
  91. package/dist/plus/integrations/providers/providerApiClient.js +1 -3
  92. package/dist/plus/integrations/providers/providerApiClient.js.map +1 -1
  93. package/dist/plus/integrations/providers/providersApi.d.ts +22 -1
  94. package/dist/plus/integrations/providers/providersApi.js +63 -12
  95. package/dist/plus/integrations/providers/providersApi.js.map +1 -1
  96. package/dist/plus/integrations/providers/utils.d.ts +1 -0
  97. package/dist/plus/integrations/providers/utils.js +8 -2
  98. package/dist/plus/integrations/providers/utils.js.map +1 -1
  99. package/dist/plus/integrations/reads/hierarchy.utils.d.ts +3 -3
  100. package/dist/plus/integrations/reads/hierarchy.utils.js +4 -4
  101. package/dist/plus/integrations/reads/hierarchy.utils.js.map +1 -1
  102. package/dist/plus/integrations/reads/resolveRepository.js +29 -21
  103. package/dist/plus/integrations/reads/resolveRepository.js.map +1 -1
  104. package/dist/plus/integrations/results.d.ts +18 -10
  105. package/dist/plus/integrations/results.js.map +1 -1
  106. package/dist/plus/integrations/utils/domain.utils.js +2 -1
  107. package/dist/plus/integrations/utils/domain.utils.js.map +1 -1
  108. package/dist/plus/integrations/utils/integration.utils.js +5 -13
  109. package/dist/plus/integrations/utils/integration.utils.js.map +1 -1
  110. package/dist/utils/diff.d.ts +19 -0
  111. package/dist/utils/diff.js +121 -3
  112. package/dist/utils/diff.js.map +1 -1
  113. package/dist/utils/env/node/exec.d.ts +0 -1
  114. package/dist/utils/env/node/exec.js +2 -14
  115. package/dist/utils/env/node/exec.js.map +1 -1
  116. package/dist/utils/path.d.ts +2 -0
  117. package/dist/utils/path.js +7 -1
  118. package/dist/utils/path.js.map +1 -1
  119. package/docs/integrations.md +72 -43
  120. package/package.json +2 -2
@@ -8,7 +8,7 @@ import { debug, trace } from "../../utils/decorators/log.js";
8
8
  import { getBranchId } from "../../utils/gitRefs.js";
9
9
  import { joinUriPath } from "../../utils/uri.js";
10
10
  import { normalizePath } from "../../utils/path.js";
11
- import { createRevisionRange, shortenRevision } from "../../git/utils/revision.utils.js";
11
+ import { createRevisionRange, isSha, shortenRevision } from "../../git/utils/revision.utils.js";
12
12
  import { formatDetachedHeadName, getLocalBranchByUpstream, 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";
@@ -56,6 +56,109 @@ const branchActivityKeys = [
56
56
  * read costs less
57
57
  */
58
58
  const maxOffHistoryCommits = 64;
59
+ /**
60
+ * How far down a rewritten base's first-parent history its commits are compared by patch with the ones it lacks below
61
+ * the fork point. A rebased parent's replayed commits sit at its tip, but a base far ahead would otherwise cost a diff
62
+ * for each of thousands of commits; one replayed deeper reads as dropped, which shows the commit rather than hides it.
63
+ */
64
+ const maxPatchCheckDepth = 256;
65
+ /** The longest a rewritten base's patch comparison may run before the merge base is taken instead */
66
+ const patchCheckTimeout = 1e4;
67
+ /**
68
+ * How long a patch comparison that ran out of time isn't run again. Running out of time usually means the machine was
69
+ * busy rather than that the comparison can't finish, so it's tried again later rather than given up on for good
70
+ */
71
+ const unfinishedPatchCheckTtl = 6e5;
72
+ /** The clock an unfinished patch comparison's expiry is read from, exported for testing */
73
+ const patchCheckClock = { now: () => Date.now() };
74
+ /** `<old> <new> <identity> <time> <zone>\t<message>`, oldest first; `undefined` when a line isn't one */
75
+ function parseReflogLines(content) {
76
+ const lines = [];
77
+ for (const line of content.split("\n")) {
78
+ if (!line) continue;
79
+ const tab = line.indexOf(" ");
80
+ const first = line.indexOf(" ");
81
+ const second = first < 0 ? -1 : line.indexOf(" ", first + 1);
82
+ if (first !== 40 && first !== 64) return void 0;
83
+ if (second !== first * 2 + 1 || tab >= 0 && tab < second) return void 0;
84
+ lines.push({
85
+ from: line.slice(0, first),
86
+ to: line.slice(first + 1, second),
87
+ forward: tab >= 0 && isForwardReflogMessage(line.slice(tab + 1))
88
+ });
89
+ }
90
+ return lines;
91
+ }
92
+ /**
93
+ * Whether git wrote `message` only for a move to a descendant: a fetch, pull or merge that fast-forwarded, a merge
94
+ * made, or a commit on the ref. Anything else (a forced update, an update by push, a reset, a rebase, an amend) says
95
+ * nothing either way. The fetch, pull and merge notes are read only after their own verb, since the messages that
96
+ * carry a commit's subject (an amend's, a cherry-pick's) can end the same way.
97
+ */
98
+ function isForwardReflogMessage(message) {
99
+ return /^commit(?: \(merge\))?: /.test(message) || /^(?:fetch|pull|merge)\b.*: (?:fast-forward$|Merge made by )/i.test(message);
100
+ }
101
+ /**
102
+ * Whether `lines`, a ref's reflog at `tip`, show `forkPoint` in the tip's history: every move since the newest line
103
+ * moving off it shown forward, each from the value the one before moved to. So too when the reflog doesn't hold
104
+ * `forkPoint` at all: `--fork-point` answers only with the tip or a value the reflog holds (the oldest line's old value
105
+ * or any line's new one), so one it doesn't hold is the merge base. `false` when they can't show it: a move whose
106
+ * message doesn't, a reflog that doesn't end at `tip`, or one holding `forkPoint` with no line moving off it (a gap).
107
+ */
108
+ function isForkPointKeptByReflog(lines, forkPoint, tip) {
109
+ if (!lines.length) return true;
110
+ if (lines.at(-1).to !== tip) return false;
111
+ let held = lines[0].from === forkPoint;
112
+ let off = -1;
113
+ for (let i = 0; i < lines.length; i++) {
114
+ const { from, to } = lines[i];
115
+ if (to === forkPoint) held = true;
116
+ else if (from === forkPoint) off = i;
117
+ }
118
+ if (!held) return true;
119
+ if (off < 0) return false;
120
+ for (let i = off; i < lines.length; i++) {
121
+ const { from, to, forward } = lines[i];
122
+ if (!(i === off || from === lines[i - 1].to) || from !== to && !forward) return false;
123
+ }
124
+ return true;
125
+ }
126
+ /**
127
+ * Where HEAD forked from a base rewritten off `forkPoint`, from `rev-list --left-only --cherry-mark --parents` of
128
+ * `<forkPoint>...<tip>`: the commits `forkPoint` holds that the base lacks, each `=` when the base holds one of the same
129
+ * patch (it replayed it, as a rebase does) and `+` when not (HEAD's own). That's the newest commit on their line below
130
+ * which every one is `=`, so `forkPoint` when all are. `undefined`, for the merge base, when the oldest is `+`, there
131
+ * are none to read (a fork point git can't find reads as none too), or they aren't one line: a merge has no patch to
132
+ * compare, so it and what it joins are taken as HEAD's.
133
+ *
134
+ * Git takes any two empty commits as the same patch, so an empty commit the base dropped reads as replayed while the
135
+ * base's newest commits hold an unrelated empty one, and can be left out of HEAD's commits.
136
+ */
137
+ function getForkPointFromPatches(output, forkPoint) {
138
+ const commits = /* @__PURE__ */ new Map();
139
+ for (const line of output.split("\n")) {
140
+ if (!line) continue;
141
+ const mark = line[0];
142
+ const [sha, ...parents] = line.slice(1).split(" ");
143
+ if (mark !== "=" && mark !== "+" || !sha) return void 0;
144
+ commits.set(sha, {
145
+ equivalent: mark === "=",
146
+ parents
147
+ });
148
+ }
149
+ let settled = forkPoint;
150
+ let sha = forkPoint;
151
+ let walked = 0;
152
+ for (let commit = commits.get(sha); commit != null; commit = commits.get(sha)) {
153
+ const [parent] = commit.parents;
154
+ if (parent == null || commit.parents.length !== 1) return void 0;
155
+ walked++;
156
+ sha = parent;
157
+ if (!commit.equivalent) settled = parent;
158
+ }
159
+ if (walked === 0 || walked !== commits.size || settled === sha) return void 0;
160
+ return settled;
161
+ }
59
162
  /** Reads a `%(ahead-behind:<base>)` field, `<ahead> <behind>`; `undefined` when it isn't one */
60
163
  function parseAheadBehindField(field) {
61
164
  const [ahead, behind] = (field ?? "").split(" ").map((n) => parseInt(n, 10));
@@ -76,6 +179,22 @@ const storedMergeKeys = [
76
179
  "gk-target-base",
77
180
  "gk-merge-base"
78
181
  ];
182
+ /**
183
+ * `branch`, from the list shared by a repository's worktrees, as `repoPath` sees it. The copy holds the same metadata
184
+ * object, which `Cache.patchBranchMetadata` updates in place.
185
+ *
186
+ * A list read before a checkout gives the branch now current `worktree: false`. `keepUnlisted` keeps that, so a reader
187
+ * of the whole list (`findStaleBranches`) can tell the list is stale; otherwise the current branch names `repoPath`.
188
+ */
189
+ function mapSharedBranch(branch, repoPath, commonPath, isCurrent, defaultWorktreePath, keepUnlisted) {
190
+ if (!isCurrent && repoPath === commonPath) return branch;
191
+ let worktree = branch.worktree;
192
+ if (isCurrent && (worktree == null || worktree === false && !keepUnlisted)) worktree = {
193
+ path: repoPath,
194
+ isDefault: repoPath === defaultWorktreePath
195
+ };
196
+ return new GitBranch(repoPath, branch.refName, isCurrent, branch.date, branch.metadata, branch.sha, branch.upstream, worktree, false, false);
197
+ }
79
198
  var BranchesGitSubProvider = class {
80
199
  context;
81
200
  git;
@@ -101,6 +220,19 @@ var BranchesGitSubProvider = class {
101
220
  */
102
221
  aheadOfMovedBase = new LruMap(64);
103
222
  /**
223
+ * Each base's reflog file, parsed, by `<commonPath>\0<ref>` and stamped by its size and mtime, so every worktree
224
+ * measured against one base shares one read of it until it changes
225
+ */
226
+ baseReflogs = new LruMap(64);
227
+ /** Whether the repository at a common git directory keeps its refs and reflogs in reftables, by `<commonPath>` */
228
+ reftableRepositories = new LruMap(64);
229
+ /**
230
+ * When each patch comparison that ran out of time, by `<commonPath>\0<forkPoint>\0<tip>`, may run again (see
231
+ * {@link patchCheckClock}). The merge base it falls back to is the safe answer, so one that ran out of time isn't
232
+ * run again on every full read of the base while the machine is likely still as busy
233
+ */
234
+ unfinishedPatchChecks = new LruMap(256);
235
+ /**
104
236
  * When each `commonPath\0branch\0key` was last stamped by this process. Bounded: a dropped entry only costs a
105
237
  * read of the stored stamp, which still holds off a write under 5 minutes old
106
238
  */
@@ -133,20 +265,82 @@ var BranchesGitSubProvider = class {
133
265
  this.provider = provider;
134
266
  }
135
267
  async getBranch(repoPath, name, options, cancellation) {
268
+ const scope = getScopedLogger();
136
269
  if (options?.force) this.cache.evictCaches(repoPath, "branches");
137
- if (name != null) {
138
- const { values: [branch] } = await this.getBranches(repoPath, { filter: (b) => b.name === name }, cancellation);
270
+ if (name != null) return (await this.getBranchFromSharedList(repoPath, name, scope, cancellation)).branch;
271
+ return this.cache.branch.getOrCreate(repoPath, async (cacheable, signal) => {
272
+ const result = await this.getBranchFromSharedList(repoPath, void 0, scope, signal);
273
+ const branch = result.branch ?? await this.getCurrentBranch(repoPath, void 0, void 0, signal);
274
+ if (!result.kept && (branch == null || branch.date != null || branch.sha != null || branch.upstream != null)) cacheable.invalidate();
139
275
  return branch;
140
- }
141
- const branchPromise = this.cache.branch.getOrCreate(repoPath, async (_cacheable, signal) => {
142
- const { values: [branch] } = await this.getBranches(repoPath, { filter: (b) => b.current }, signal);
143
- return branch ?? this.getCurrentBranch(repoPath, void 0, void 0, signal);
144
276
  }, cancellation);
145
- if (branchPromise == null) {
146
- const { values: [branch] } = await this.getBranches(repoPath, { filter: (b) => b.current }, cancellation);
147
- return branch ?? this.getCurrentBranch(repoPath, void 0, void 0, cancellation);
277
+ }
278
+ /**
279
+ * What `getBranches(repoPath)` would answer for the named branch, or for the current one when `name` is omitted,
280
+ * without keeping that worktree's copy of the whole list, and whether the shared list it read is still kept
281
+ */
282
+ async getBranchFromSharedList(repoPath, name, scope, cancellation) {
283
+ if (repoPath == null) return {
284
+ branch: void 0,
285
+ kept: true
286
+ };
287
+ const commonPath = this.cache.getCommonPath(repoPath);
288
+ const shared = await this.cache.getSharedBranches(repoPath, (_commonPath, cacheable, signal) => this.getSharedBranchesCore(commonPath, void 0, scope, cacheable, signal), cancellation);
289
+ const kept = this.cache.isSharedBranchesKept(repoPath, shared);
290
+ const { values } = shared;
291
+ if (!values.length) return {
292
+ branch: void 0,
293
+ kept
294
+ };
295
+ const { currentRef, defaultWorktreePath, isDetached } = await this.getCurrentRefAndDefaultWorktreePath(repoPath, commonPath, cancellation);
296
+ const isCurrent = (b) => !b.remote && b.name === currentRef?.name && !isDetached;
297
+ if (name == null) {
298
+ const current = values.find(isCurrent);
299
+ if (current != null) return {
300
+ branch: mapSharedBranch(current, repoPath, commonPath, true, defaultWorktreePath, false),
301
+ kept
302
+ };
303
+ if (currentRef == null) return {
304
+ branch: void 0,
305
+ kept
306
+ };
307
+ const metadataMap = await this.getBranchMetadataMap(commonPath);
308
+ return {
309
+ branch: await this.getCurrentBranch(repoPath, metadataMap, this.context.config?.commits.ordering ?? void 0, cancellation),
310
+ kept
311
+ };
148
312
  }
149
- return branchPromise;
313
+ const special = isDetached || currentRef != null && !values.some(isCurrent) ? await this.getBranch(repoPath, void 0, void 0, cancellation) : void 0;
314
+ const replaced = special != null ? values.findIndex((b) => b.remote === special.remote && b.name === special.name) : -1;
315
+ if (replaced === -1 && special?.name === name) return {
316
+ branch: special,
317
+ kept
318
+ };
319
+ const index = values.findIndex((b, i) => (i === replaced ? special?.name : b.name) === name);
320
+ if (index === -1) return {
321
+ branch: void 0,
322
+ kept
323
+ };
324
+ if (index === replaced) return {
325
+ branch: special,
326
+ kept
327
+ };
328
+ const branch = values[index];
329
+ return {
330
+ branch: mapSharedBranch(branch, repoPath, commonPath, isCurrent(branch), defaultWorktreePath, false),
331
+ kept
332
+ };
333
+ }
334
+ /** The current ref of `repoPath` and the default worktree path of `commonPath`, rejecting if the caller aborted mid-read */
335
+ async getCurrentRefAndDefaultWorktreePath(repoPath, commonPath, cancellation) {
336
+ const [currentRefResult, defaultWorktreePathResult] = await Promise.allSettled([this.getCurrentBranchReferenceCore(repoPath, void 0, cancellation), this.provider.config.getDefaultWorktreePath?.(commonPath)]);
337
+ if (cancellation?.aborted) throw new CancellationError();
338
+ const currentRef = getSettledValue(currentRefResult);
339
+ return {
340
+ currentRef,
341
+ defaultWorktreePath: getSettledValue(defaultWorktreePathResult),
342
+ isDetached: currentRef != null && isDetachedHead(currentRef.name)
343
+ };
150
344
  }
151
345
  async getCurrentBranch(repoPath, metadataMap, ordering, cancellation) {
152
346
  const ref = await this.getCurrentBranchReferenceCore(repoPath, ordering, cancellation);
@@ -181,107 +375,107 @@ var BranchesGitSubProvider = class {
181
375
  isDefault: repoPath === defaultWorktreePath
182
376
  }, void 0, rebaseStatus != null);
183
377
  }
184
- async getBranches(repoPath, options, cancellation) {
185
- if (repoPath == null) return emptyPagedResult;
186
- const scope = getScopedLogger();
187
- const getCore = async (commonPath, cacheable, signal) => {
188
- signal ??= cancellation;
378
+ /** The branches of the repository at `commonPath`, as the list every one of its worktrees maps from */
379
+ async getSharedBranchesCore(commonPath, ordering, scope, cacheable, signal) {
380
+ try {
189
381
  try {
190
- try {
191
- var _usingCtx$1 = _usingCtx();
192
- const [recordsResult, supportedResult, defaultWorktreePathResult, metadataMapResult] = await Promise.allSettled([
193
- this.provider.refs.getRefs(commonPath, signal),
194
- this.git.supported("git:for-each-ref"),
195
- this.provider.config.getDefaultWorktreePath?.(commonPath),
196
- this.getBranchMetadataMap(commonPath)
197
- ]);
198
- const records = getSettledValue(recordsResult) ?? [];
199
- const supported = getSettledValue(supportedResult) ?? [];
200
- const metadataMap = getSettledValue(metadataMapResult) ?? /* @__PURE__ */ new Map();
201
- const defaultWorktreePath = getSettledValue(defaultWorktreePathResult);
202
- const worktreePathSupported = supported.includes("git:for-each-ref:worktreePath");
203
- if (!records.length) {
382
+ var _usingCtx$1 = _usingCtx();
383
+ const [recordsResult, supportedResult, defaultWorktreePathResult, metadataMapResult] = await Promise.allSettled([
384
+ this.provider.refs.getRefs(commonPath, signal),
385
+ this.git.supported("git:for-each-ref"),
386
+ this.provider.config.getDefaultWorktreePath?.(commonPath),
387
+ this.getBranchMetadataMap(commonPath)
388
+ ]);
389
+ const records = getSettledValue(recordsResult) ?? [];
390
+ const supported = getSettledValue(supportedResult) ?? [];
391
+ const metadataMap = getSettledValue(metadataMapResult) ?? /* @__PURE__ */ new Map();
392
+ const defaultWorktreePath = getSettledValue(defaultWorktreePathResult);
393
+ const worktreePathSupported = supported.includes("git:for-each-ref:worktreePath");
394
+ if (!records.length) {
395
+ cacheable?.invalidate();
396
+ const current = await this.getCurrentBranch(commonPath, metadataMap, ordering ?? this.context.config?.commits.ordering ?? void 0, signal);
397
+ return current != null ? { values: [current] } : emptyPagedResult;
398
+ }
399
+ const sw = _usingCtx$1.u(maybeStopWatch(scope, { log: {
400
+ onlyExit: true,
401
+ level: "debug"
402
+ } }));
403
+ const branches = [];
404
+ /** Each branch checked out in a worktree, with that worktree's path and the record the branch was read from */
405
+ const checkedOut = [];
406
+ let remoteNames;
407
+ const resolveUpstreamRemote = async (upstream) => {
408
+ if (!upstream.startsWith("refs/remotes/")) return void 0;
409
+ const { name } = parseRefName(upstream);
410
+ if (!name.includes("/", name.indexOf("/") + 1)) return void 0;
411
+ remoteNames ??= this.provider.remotes.getRemotes(commonPath, void 0, signal).then((remotes) => {
412
+ if (!remotes.length) cacheable?.invalidate();
413
+ return remotes.map((r) => r.name);
414
+ }, (ex) => {
415
+ if (isCancellationError(ex)) throw ex;
204
416
  cacheable?.invalidate();
205
- const current = await this.getCurrentBranch(commonPath, metadataMap, options?.ordering ?? this.context.config?.commits.ordering ?? void 0, signal);
206
- return current != null ? { values: [current] } : emptyPagedResult;
207
- }
208
- const sw = _usingCtx$1.u(maybeStopWatch(scope, { log: {
209
- onlyExit: true,
210
- level: "debug"
211
- } }));
212
- const branches = [];
213
- let remoteNames;
214
- const resolveUpstreamRemote = async (upstream) => {
215
- if (!upstream.startsWith("refs/remotes/")) return void 0;
216
- const { name } = parseRefName(upstream);
217
- if (!name.includes("/", name.indexOf("/") + 1)) return void 0;
218
- remoteNames ??= this.provider.remotes.getRemotes(commonPath, void 0, signal).then((remotes) => {
219
- if (!remotes.length) cacheable?.invalidate();
220
- return remotes.map((r) => r.name);
221
- }, (ex) => {
222
- if (isCancellationError(ex)) throw ex;
223
- cacheable?.invalidate();
224
- return [];
225
- });
226
- return splitRemoteBranchName(name, await remoteNames)?.[0];
227
- };
228
- for (const record of records) {
229
- const fullName = record.name;
230
- if (!fullName.startsWith("refs/heads/") && !fullName.startsWith("refs/remotes/")) continue;
231
- if (isRemoteHEAD(fullName)) continue;
232
- const upstream = parseUpstream(record.upstream, record.upstreamTracking, record.upstreamRemote ?? (!worktreePathSupported ? await resolveUpstreamRemote(record.upstream) : void 0), record.upstreamRemoteRef);
233
- const metadata = metadataMap.get(parseRefName(fullName).name);
234
- const worktreePath = record.worktreePath ? normalizePath(record.worktreePath) : void 0;
235
- branches.push(new GitBranch(commonPath, fullName, false, record.committerDate ? new Date(record.committerDate) : void 0, metadata, record.objectname, upstream, worktreePathSupported ? worktreePath ? {
236
- path: worktreePath,
237
- isDefault: worktreePath === defaultWorktreePath
238
- } : false : void 0));
239
- }
240
- sw?.stop({ suffix: ` parsed ${branches.length} branches` });
241
- for (const branch of branches) if (branch.worktree && branch.worktree.path) {
242
- const { name } = parseRefName(branch.refName);
243
- const reference = createReference(name, branch.worktree.path, {
244
- refType: "branch",
245
- name,
246
- id: getBranchId(branch.worktree.path, false, name),
247
- remote: false,
248
- upstream: branch.upstream?.name ? {
249
- name: branch.upstream.name,
250
- missing: branch.upstream.missing,
251
- remote: branch.upstream.remote,
252
- remoteBranch: branch.upstream.remoteBranch,
253
- local: branch.upstream.local
254
- } : void 0,
255
- sha: branch.sha
256
- });
257
- this.cache.setCurrentBranchReferenceIfAbsent(branch.worktree.path, reference);
258
- }
259
- return branches.length ? { values: branches } : emptyPagedResult;
260
- } catch (_) {
261
- _usingCtx$1.e = _;
262
- } finally {
263
- _usingCtx$1.d();
417
+ return [];
418
+ });
419
+ return splitRemoteBranchName(name, await remoteNames)?.[0];
420
+ };
421
+ for (const record of records) {
422
+ const fullName = record.name;
423
+ if (!fullName.startsWith("refs/heads/") && !fullName.startsWith("refs/remotes/")) continue;
424
+ if (isRemoteHEAD(fullName)) continue;
425
+ const upstream = parseUpstream(record.upstream, record.upstreamTracking, record.upstreamRemote ?? (!worktreePathSupported ? await resolveUpstreamRemote(record.upstream) : void 0), record.upstreamRemoteRef);
426
+ const metadata = metadataMap.get(parseRefName(fullName).name);
427
+ const worktreePath = record.worktreePath ? normalizePath(record.worktreePath) : void 0;
428
+ const branch = new GitBranch(commonPath, fullName, false, record.committerDate ? new Date(record.committerDate) : void 0, metadata, record.objectname, upstream, worktreePathSupported ? worktreePath ? {
429
+ path: worktreePath,
430
+ isDefault: worktreePath === defaultWorktreePath
431
+ } : false : void 0);
432
+ branches.push(branch);
433
+ if (worktreePathSupported && worktreePath) checkedOut.push([
434
+ worktreePath,
435
+ branch,
436
+ record
437
+ ]);
264
438
  }
265
- } catch (ex) {
266
- cacheable?.invalidate();
267
- if (isCancellationError(ex)) throw ex;
268
- return emptyPagedResult;
439
+ sw?.stop({ suffix: ` parsed ${branches.length} branches` });
440
+ for (const [path, branch, record] of checkedOut) {
441
+ const { name } = parseRefName(branch.refName);
442
+ const reference = createReference(name, path, {
443
+ refType: "branch",
444
+ name,
445
+ id: getBranchId(path, false, name),
446
+ remote: false,
447
+ upstream: branch.upstream?.name ? {
448
+ name: branch.upstream.name,
449
+ missing: branch.upstream.missing,
450
+ remote: branch.upstream.remote,
451
+ remoteBranch: branch.upstream.remoteBranch,
452
+ local: branch.upstream.local
453
+ } : void 0,
454
+ sha: branch.sha
455
+ });
456
+ this.cache.setCurrentBranchReferenceIfAbsent(path, reference, record);
457
+ }
458
+ return branches.length ? { values: branches } : emptyPagedResult;
459
+ } catch (_) {
460
+ _usingCtx$1.e = _;
461
+ } finally {
462
+ _usingCtx$1.d();
269
463
  }
270
- };
464
+ } catch (ex) {
465
+ cacheable?.invalidate();
466
+ if (isCancellationError(ex)) throw ex;
467
+ return emptyPagedResult;
468
+ }
469
+ }
470
+ async getBranches(repoPath, options, cancellation) {
471
+ if (repoPath == null) return emptyPagedResult;
472
+ const scope = getScopedLogger();
271
473
  const mapBranches = async (shared, targetRepoPath, commonPath, mapperSignal) => {
272
474
  if (!shared.values.length) return shared;
273
475
  mapperSignal ??= cancellation;
274
- const [currentRefResult, defaultWorktreePathResult] = await Promise.allSettled([this.getCurrentBranchReferenceCore(targetRepoPath, void 0, mapperSignal), this.provider.config.getDefaultWorktreePath?.(commonPath)]);
275
- const currentRef = getSettledValue(currentRefResult);
276
- const defaultWorktreePath = getSettledValue(defaultWorktreePathResult);
277
- const isDetached = currentRef != null && isDetachedHead(currentRef.name);
476
+ const { currentRef, defaultWorktreePath, isDetached } = await this.getCurrentRefAndDefaultWorktreePath(targetRepoPath, commonPath, mapperSignal);
278
477
  const branches = shared.values.map((b) => {
279
- const isCurrent = !b.remote && b.name === currentRef?.name && !isDetached;
280
- if (!isCurrent && targetRepoPath === commonPath) return b;
281
- return new GitBranch(targetRepoPath, b.refName, isCurrent, b.date, b.metadata, b.sha, b.upstream, isCurrent ? b.worktree ?? {
282
- path: targetRepoPath,
283
- isDefault: targetRepoPath === defaultWorktreePath
284
- } : b.worktree, false, false);
478
+ return mapSharedBranch(b, targetRepoPath, commonPath, !b.remote && b.name === currentRef?.name && !isDetached, defaultWorktreePath, true);
285
479
  });
286
480
  if (isDetached || currentRef != null && !branches.some((b) => b.current)) {
287
481
  const metadataMap = await this.getBranchMetadataMap(commonPath);
@@ -300,8 +494,8 @@ var BranchesGitSubProvider = class {
300
494
  let result;
301
495
  if (options?.paging?.cursor != null) {
302
496
  const commonPath = this.cache.getCommonPath(repoPath);
303
- result = await mapBranches(await getCore(commonPath), repoPath, commonPath);
304
- } else result = await this.cache.getBranches(repoPath, getCore, mapBranches, cancellation);
497
+ result = await mapBranches(await this.getSharedBranchesCore(commonPath, options.ordering, scope, void 0, cancellation), repoPath, commonPath);
498
+ } else result = await this.cache.getBranches(repoPath, (commonPath, cacheable, signal) => this.getSharedBranchesCore(commonPath, options?.ordering, scope, cacheable, signal ?? cancellation), mapBranches, cancellation);
305
499
  if (options?.filter != null) result = {
306
500
  ...result,
307
501
  values: result.values.filter(options.filter)
@@ -1318,7 +1512,7 @@ var BranchesGitSubProvider = class {
1318
1512
  dependsOn: [...dependsOn]
1319
1513
  }, reads.localDefault);
1320
1514
  const tier = resolved.tier;
1321
- return withDefaultBranch(await this.measureAheadOfBase(repoPath, resolved.target, tier, dependsOn, cancellation), reads.localDefault);
1515
+ return withDefaultBranch(await this.measureAheadOfBase(repoPath, resolved.target, tier, reads, cancellation), reads.localDefault);
1322
1516
  }
1323
1517
  async getAheadOfBaseAfterBaseMove(repoPath, branch, previous, moved, cancellation) {
1324
1518
  const { head, base } = previous;
@@ -1355,19 +1549,30 @@ var BranchesGitSubProvider = class {
1355
1549
  if (cancellation?.aborted) throw new CancellationError();
1356
1550
  if (!movedForward) return void 0;
1357
1551
  const { offHistory, logged } = movedForward;
1358
- const aheadOfNewTip = await this.getAheadOfMovedBase(repoPath, records, newTip, head);
1552
+ const forkPoint = base.forkPoint;
1553
+ const rewritten = forkPoint != null && logged.has(forkPoint) && offHistory.includes(forkPoint);
1554
+ const aheadOfNewTip = rewritten ? void 0 : await this.getAheadOfMovedBase(repoPath, records, newTip, head);
1359
1555
  if (cancellation?.aborted) throw new CancellationError();
1360
1556
  if (aheadOfNewTip != null && aheadOfNewTip !== base.ahead) return void 0;
1361
- const forkPoint = base.forkPoint;
1362
1557
  if (aheadOfNewTip == null || offHistory.length !== 0 || forkPoint != null && forkPoint !== oldTip && forkPoint !== newTip && !logged.has(forkPoint)) {
1363
1558
  const result = await this.git.run({
1364
1559
  cwd: repoPath,
1365
1560
  cancellation,
1366
1561
  errors: "ignore"
1367
- }, "rev-list", "--count", head, "--not", newTip, ...forkPoint != null ? [forkPoint] : [], ...offHistory, "--");
1562
+ }, "rev-list", `--max-count=${base.ahead + 1}`, head, "--not", newTip, ...offHistory, "--");
1368
1563
  if (cancellation?.aborted) throw new CancellationError();
1369
1564
  if (result.completion.status !== "exited" || result.exitCode !== 0) return void 0;
1370
- if (parseInt(result.stdout.trim(), 10) !== base.ahead) return void 0;
1565
+ const past = result.stdout.split("\n").filter((sha) => sha.length > 0);
1566
+ if (past.length !== base.ahead || forkPoint != null && past.includes(forkPoint)) return void 0;
1567
+ }
1568
+ if (rewritten) {
1569
+ const reads = {
1570
+ priority: void 0,
1571
+ pinnable: true
1572
+ };
1573
+ const settled = await this.settleForkPointAndCount(repoPath, records, base.ref, newTip, forkPoint, base.ahead, reads, cancellation);
1574
+ if (!reads.pinnable || !settled.counted || settled.forkPoint !== forkPoint) return void 0;
1575
+ if (settled.ahead !== base.ahead) return void 0;
1371
1576
  }
1372
1577
  return withDefaultBranch({
1373
1578
  base: {
@@ -1414,7 +1619,7 @@ var BranchesGitSubProvider = class {
1414
1619
  const commonPath = this.cache.getCommonPath(repoPath);
1415
1620
  const key = `${commonPath}\0${ref}`;
1416
1621
  const inputs = getBaseMoveReadInputs(records);
1417
- const reflog = await this.getReflogStamp(repoPath, ref) ?? inputs;
1622
+ const reflog = (await this.getReflogSource(repoPath, ref))?.stamp ?? inputs;
1418
1623
  const { replaced } = inputs;
1419
1624
  let slot = this.baseMovedForward.get(key);
1420
1625
  if (slot == null || slot.newTip !== newTip || slot.reflog !== reflog || slot.replaced !== replaced) {
@@ -1429,7 +1634,7 @@ var BranchesGitSubProvider = class {
1429
1634
  const { reads } = slot;
1430
1635
  let pending = reads.get(oldTip);
1431
1636
  if (pending == null) {
1432
- pending = this.readMovedForward(commonPath, ref, oldTip, newTip);
1637
+ pending = this.readMovedForward(repoPath, commonPath, ref, oldTip, newTip);
1433
1638
  reads.set(oldTip, pending);
1434
1639
  }
1435
1640
  const movedForward = await pending;
@@ -1437,18 +1642,42 @@ var BranchesGitSubProvider = class {
1437
1642
  return movedForward || void 0;
1438
1643
  }
1439
1644
  /**
1440
- * A stamp of `ref`'s reflog file in the common git directory, by its size and mtime; `undefined` when there's no
1441
- * file to stat (a reftable repository, or a ref without a reflog)
1645
+ * Where `ref`'s reflog is kept, with a stamp that changes whenever the reflog may have: its file in the common git
1646
+ * directory, by its size and mtime, or in a reftable repository, which keeps every reflog in the same tables, read
1647
+ * only from git, the table list's. `stamp` is `undefined` when there's no such file (a ref without a reflog); the
1648
+ * whole answer when that can't be told.
1442
1649
  */
1443
- async getReflogStamp(repoPath, ref) {
1650
+ async getReflogSource(repoPath, ref) {
1444
1651
  try {
1445
1652
  const gitDir = await this.provider.config.getGitDir(repoPath);
1446
- const stat = await this.context.fs.stat(joinUriPath(gitDir.commonUri ?? gitDir.uri, "logs", ref));
1447
- return stat != null ? `${stat.size}\0${stat.mtime}` : void 0;
1653
+ const commonUri = gitDir.commonUri ?? gitDir.uri;
1654
+ const reftable = await this.isReftableRepository(this.cache.getCommonPath(repoPath), commonUri);
1655
+ const uri = reftable ? joinUriPath(commonUri, "reftable", "tables.list") : joinUriPath(commonUri, "logs", ref);
1656
+ const stat = await this.context.fs.stat(uri);
1657
+ return {
1658
+ stamp: stat != null ? `${stat.size}\0${stat.mtime}` : void 0,
1659
+ reftable,
1660
+ uri
1661
+ };
1448
1662
  } catch {
1449
1663
  return;
1450
1664
  }
1451
1665
  }
1666
+ /** Whether the repository keeps its refs in reftables, which it does for good once it has the table list */
1667
+ isReftableRepository(commonPath, commonUri) {
1668
+ let detected = this.reftableRepositories.get(commonPath);
1669
+ if (detected == null) {
1670
+ detected = (async () => {
1671
+ try {
1672
+ return await this.context.fs.stat(joinUriPath(commonUri, "reftable", "tables.list")) != null;
1673
+ } catch {
1674
+ return false;
1675
+ }
1676
+ })();
1677
+ this.reftableRepositories.set(commonPath, detected);
1678
+ } else this.reftableRepositories.touch(commonPath);
1679
+ return detected;
1680
+ }
1452
1681
  /**
1453
1682
  * A stamp of the common git directory's `shallow` file, by its size and mtime; `null` when the repository isn't
1454
1683
  * shallow, `undefined` when that can't be read
@@ -1463,42 +1692,85 @@ var BranchesGitSubProvider = class {
1463
1692
  }
1464
1693
  }
1465
1694
  /**
1466
- * Reads {@link getMovedForward} from git, in `commonPath`, which holds the refs, their reflogs and the objects for
1467
- * every worktree. Not bound to one caller's cancellation, since every worktree the move reached rides this one
1468
- * read. `false` when the ref didn't move only forward, or reaches too much history off `newTip`'s to tell;
1469
- * `undefined` when git couldn't say.
1695
+ * The values `ref`'s reflog took, newest first, and the one it held before its oldest entry, which `--fork-point`
1696
+ * reads too and no entry lists once the entries before it expired; `null` when that entry created the ref. Read from
1697
+ * the reflog's file by {@link readBaseReflog} when that has it, else from git. `false` when git can't name the value
1698
+ * before (before 2.31), `undefined` when it couldn't say.
1470
1699
  */
1471
- async readMovedForward(commonPath, ref, oldTip, newTip) {
1472
- let since = /* @__PURE__ */ new Set([oldTip]);
1473
- let logged = /* @__PURE__ */ new Set([oldTip]);
1700
+ async readReflogValues(repoPath, commonPath, ref) {
1701
+ const lines = await this.readBaseReflog(repoPath, ref);
1702
+ if (lines != null) {
1703
+ const from = lines[0]?.from;
1704
+ return {
1705
+ values: lines.map((l) => l.to).reverse(),
1706
+ before: from == null || /^0+$/.test(from) ? null : from
1707
+ };
1708
+ }
1709
+ const read = await this.readReflogFromGit(commonPath, ref);
1710
+ if (!read) return read;
1711
+ return {
1712
+ values: read.entries.map((e) => e.sha),
1713
+ before: read.before
1714
+ };
1715
+ }
1716
+ /**
1717
+ * `ref`'s reflog entries, newest first, and the value it held before the oldest one (`null` when that entry created
1718
+ * the ref), by asking git in `commonPath`. `false` when git can't name the value before (before 2.31), `undefined`
1719
+ * when it couldn't say.
1720
+ */
1721
+ async readReflogFromGit(commonPath, ref) {
1474
1722
  try {
1475
1723
  const entries = await this.provider.refs.getReflogEntries(commonPath, ref);
1476
- if (entries.length) {
1477
- if (entries[0].sha !== newTip) return false;
1478
- const oldest = entries.findLastIndex((e) => e.sha === oldTip);
1479
- since = new Set(entries.slice(1, oldest < 0 ? void 0 : oldest + 1).map((e) => e.sha));
1480
- logged = new Set(entries.map((e) => e.sha));
1481
- if (oldest < 0) {
1482
- since.add(oldTip);
1483
- logged.add(oldTip);
1484
- }
1485
- const before = await this.git.run({
1486
- cwd: commonPath,
1487
- errors: "ignore"
1488
- }, "rev-parse", "--verify", `${ref}@{${entries.length}}`);
1489
- if (before.completion.status !== "exited") return void 0;
1490
- if (before.exitCode === 0) {
1491
- const sha = before.stdout.trim();
1492
- if (!sha) return void 0;
1493
- if (oldest < 0 && sha !== oldTip) return false;
1494
- logged.add(sha);
1495
- } else if (!before.stderr?.includes(" only has ")) return;
1496
- else if (oldest < 0 || !await this.git.supports("git:rev-parse:reflog-oldest-old-value")) return false;
1497
- logged.delete(newTip);
1724
+ if (!entries.length) return {
1725
+ entries,
1726
+ before: null
1727
+ };
1728
+ const before = await this.git.run({
1729
+ cwd: commonPath,
1730
+ errors: "ignore"
1731
+ }, "rev-parse", "--verify", `${ref}@{${entries.length}}`);
1732
+ if (before.completion.status !== "exited") return void 0;
1733
+ if (before.exitCode === 0) {
1734
+ const sha = before.stdout.trim();
1735
+ return sha ? {
1736
+ entries,
1737
+ before: sha
1738
+ } : void 0;
1498
1739
  }
1740
+ if (!before.stderr?.includes(" only has ")) return void 0;
1741
+ if (!await this.git.supports("git:rev-parse:reflog-oldest-old-value")) return false;
1742
+ return {
1743
+ entries,
1744
+ before: null
1745
+ };
1499
1746
  } catch {
1500
1747
  return;
1501
1748
  }
1749
+ }
1750
+ /**
1751
+ * Reads {@link getMovedForward}: the reflog by {@link readReflogValues}, then git, in `commonPath`, which holds the
1752
+ * refs, their reflogs and the objects for every worktree. Not bound to one caller's cancellation, since every
1753
+ * worktree the move reached rides this one read. `false` when the ref didn't move only forward, or reaches too much
1754
+ * history off `newTip`'s to tell; `undefined` when git couldn't say.
1755
+ */
1756
+ async readMovedForward(repoPath, commonPath, ref, oldTip, newTip) {
1757
+ let since = /* @__PURE__ */ new Set([oldTip]);
1758
+ let logged = /* @__PURE__ */ new Set([oldTip]);
1759
+ const reflog = await this.readReflogValues(repoPath, commonPath, ref);
1760
+ if (!reflog) return reflog;
1761
+ const { values, before } = reflog;
1762
+ if (values.length) {
1763
+ if (values[0] !== newTip) return false;
1764
+ const oldest = values.lastIndexOf(oldTip);
1765
+ since = new Set(values.slice(1, oldest < 0 ? void 0 : oldest + 1));
1766
+ logged = new Set(values);
1767
+ if (oldest < 0) {
1768
+ if (before !== oldTip) return false;
1769
+ since.add(oldTip);
1770
+ }
1771
+ if (before != null) logged.add(before);
1772
+ logged.delete(newTip);
1773
+ }
1502
1774
  try {
1503
1775
  const result = await this.git.run({
1504
1776
  cwd: commonPath,
@@ -1643,9 +1915,14 @@ var BranchesGitSubProvider = class {
1643
1915
  const upstream = resolved.upstream;
1644
1916
  if (upstream != null) {
1645
1917
  selfAtTip = upstream.sha === await this.getRefTip(repoPath, records, from, cancellation);
1918
+ let forkPoint = upstream.sha;
1919
+ if (!selfAtTip) {
1920
+ forkPoint = await this.getForkPoint(repoPath, upstream.ref, reads, cancellation);
1921
+ ({forkPoint} = await this.settleForkPoint(repoPath, records, upstream.ref, upstream.sha, forkPoint, reads, cancellation));
1922
+ }
1646
1923
  result = {
1647
1924
  ref: upstream.ref,
1648
- forkPoint: selfAtTip ? upstream.sha : await this.getForkPoint(repoPath, upstream.ref, reads, cancellation),
1925
+ forkPoint,
1649
1926
  tier: "upstream"
1650
1927
  };
1651
1928
  }
@@ -1941,7 +2218,8 @@ var BranchesGitSubProvider = class {
1941
2218
  /**
1942
2219
  * The base for a branch created from `createdFrom`: that branch, unless the default branch forked strictly nearer
1943
2220
  * HEAD, as it does once `createdFrom` merged into it and the branch was rebased onto it. A stacked branch's
1944
- * unmerged parent forked nearer, and stays its base. `undefined` when neither is usable.
2221
+ * unmerged parent forked nearer, and stays its base, also once the default was moved onto one of the branch's
2222
+ * commits and back, since both fork points are settled. `undefined` when neither is usable.
1945
2223
  */
1946
2224
  async getCreatedFromForkTarget(repoPath, branch, createdFrom, defaultBranch, reads, cancellation) {
1947
2225
  const { name } = createdFrom;
@@ -1961,7 +2239,8 @@ var BranchesGitSubProvider = class {
1961
2239
  };
1962
2240
  }
1963
2241
  /** Counts HEAD's commits past `target` for {@link getAheadOfBase} */
1964
- async measureAheadOfBase(repoPath, target, tier, dependsOn, cancellation) {
2242
+ async measureAheadOfBase(repoPath, target, tier, reads, cancellation) {
2243
+ const { dependsOn } = reads;
1965
2244
  const [countsResult, refsResult] = await Promise.allSettled([this.countAgainstBase(repoPath, target.ref, cancellation), this.provider.refs.getRefs(repoPath, cancellation)]);
1966
2245
  if (cancellation?.aborted) throw new CancellationError();
1967
2246
  if (countsResult.status === "rejected") throw countsResult.reason;
@@ -1971,17 +2250,196 @@ var BranchesGitSubProvider = class {
1971
2250
  reason: "unborn",
1972
2251
  dependsOn: [...dependsOn]
1973
2252
  };
2253
+ const sha = findRefTip(getSettledValue(refsResult, []), target.ref);
2254
+ const { forkPoint, ahead } = counts.left === 0 && sha != null ? {
2255
+ forkPoint: sha,
2256
+ ahead: counts.right
2257
+ } : await this.countPastForkPoint(repoPath, target.ref, {
2258
+ forkPoint: target.forkPoint,
2259
+ rewritten: target.rewritten ?? false
2260
+ }, counts.right, reads, cancellation);
1974
2261
  return {
1975
2262
  base: {
1976
2263
  ref: target.ref,
1977
- ahead: counts.right,
1978
- sha: findRefTip(getSettledValue(refsResult, []), target.ref),
1979
- forkPoint: target.forkPoint,
2264
+ ahead,
2265
+ sha,
2266
+ forkPoint,
1980
2267
  tier
1981
2268
  },
1982
2269
  dependsOn: [...dependsOn]
1983
2270
  };
1984
2271
  }
2272
+ /**
2273
+ * HEAD's count past `settled`, a fork point of `ref`, from `ahead`, its count past their merge base: that count,
2274
+ * unless `ref` was rewritten off the fork point, where it's counted past it, since that's what HEAD lists past it.
2275
+ * When that count can't be read, the merge base is taken, with `ahead`, and `reads.pinnable` cleared; the fork point
2276
+ * stays, with `ahead`, only when the merge base can't be read either.
2277
+ */
2278
+ async countPastForkPoint(repoPath, ref, settled, ahead, reads, cancellation) {
2279
+ const { forkPoint } = settled;
2280
+ if (!settled.rewritten || forkPoint == null) return {
2281
+ forkPoint,
2282
+ ahead,
2283
+ counted: false
2284
+ };
2285
+ try {
2286
+ const counts = await this.countAgainstBase(repoPath, forkPoint, cancellation);
2287
+ if (counts != null) return {
2288
+ forkPoint,
2289
+ ahead: counts.right,
2290
+ counted: true
2291
+ };
2292
+ } catch (ex) {
2293
+ if (isCancellationError(ex)) throw ex;
2294
+ }
2295
+ reads.pinnable = false;
2296
+ const read = {
2297
+ priority: reads.priority,
2298
+ pinnable: true
2299
+ };
2300
+ const mergeBase = await this.readMergeBase(repoPath, "HEAD", ref, false, read, cancellation);
2301
+ return {
2302
+ forkPoint: read.pinnable ? mergeBase : forkPoint,
2303
+ ahead,
2304
+ counted: false
2305
+ };
2306
+ }
2307
+ /** {@link settleForkPoint} from HEAD, then {@link countPastForkPoint} */
2308
+ async settleForkPointAndCount(repoPath, records, ref, tip, forkPoint, ahead, reads, cancellation) {
2309
+ const fromHead = {
2310
+ from: "HEAD",
2311
+ priority: reads.priority,
2312
+ pinnable: true
2313
+ };
2314
+ const settled = await this.settleForkPoint(repoPath, records, ref, tip, forkPoint, fromHead, cancellation);
2315
+ if (!fromHead.pinnable) reads.pinnable = false;
2316
+ return this.countPastForkPoint(repoPath, ref, settled, ahead, reads, cancellation);
2317
+ }
2318
+ /**
2319
+ * Where `reads.from` forked from `ref` (a base at `tip`), from `forkPoint`, git's reading of `ref`'s reflog. A fork
2320
+ * point the base left behind (rebased, moved back and on, reset and moved on in one fetch) is settled by patch: the
2321
+ * commits it holds that the base lacks are compared with the base's, and `reads.from` forked below the first one the
2322
+ * base has no copy of (`rewritten`), the merge base when that's the oldest. Only where that answer is known is the
2323
+ * comparison skipped: when the reflog's file shows every move since the fork point forward, which spawns nothing, or
2324
+ * one ancestry check finds the fork point in the tip's history (it stays), the tip in the fork point's (the tip,
2325
+ * which `reads.from` holds), or no history shared (the merge base). A read that fails clears `reads.pinnable` and
2326
+ * takes the merge base, which never hides a commit; `forkPoint` stays only when that read fails too.
2327
+ */
2328
+ async settleForkPoint(repoPath, records, ref, tip, forkPoint, reads, cancellation) {
2329
+ const kept = {
2330
+ forkPoint,
2331
+ rewritten: false
2332
+ };
2333
+ if (forkPoint == null || forkPoint === tip) return kept;
2334
+ if (isAmbiguousRefName(records, ref)) return kept;
2335
+ const mergeBaseOrKept = async () => {
2336
+ const read = {
2337
+ priority: reads.priority,
2338
+ pinnable: true
2339
+ };
2340
+ const mergeBase = await this.readMergeBase(repoPath, reads.from, ref, false, read, cancellation);
2341
+ if (read.pinnable) return {
2342
+ forkPoint: mergeBase,
2343
+ rewritten: false
2344
+ };
2345
+ reads.pinnable = false;
2346
+ return kept;
2347
+ };
2348
+ if (tip == null) return mergeBaseOrKept();
2349
+ const record = resolveRefRecord(records, ref);
2350
+ const lines = record != null && !record.name.endsWith("/HEAD") ? await this.readBaseReflog(repoPath, record.name) : void 0;
2351
+ if (cancellation?.aborted) throw new CancellationError();
2352
+ if (lines != null && isForkPointKeptByReflog(lines, forkPoint, tip)) return kept;
2353
+ const checks = {
2354
+ priority: reads.priority,
2355
+ pinnable: true
2356
+ };
2357
+ const mergeBase = await this.readMergeBase(repoPath, forkPoint, tip, false, checks, cancellation);
2358
+ if (!checks.pinnable) {
2359
+ reads.pinnable = false;
2360
+ return mergeBaseOrKept();
2361
+ }
2362
+ if (mergeBase === forkPoint) return kept;
2363
+ if (mergeBase === tip) return {
2364
+ forkPoint: tip,
2365
+ rewritten: false
2366
+ };
2367
+ if (mergeBase == null) return mergeBaseOrKept();
2368
+ const settled = await this.readRewrittenForkPoint(repoPath, forkPoint, tip, checks, cancellation);
2369
+ if (!checks.pinnable) reads.pinnable = false;
2370
+ return settled != null ? {
2371
+ forkPoint: settled,
2372
+ rewritten: true
2373
+ } : mergeBaseOrKept();
2374
+ }
2375
+ /**
2376
+ * Where HEAD forked from a base at `tip` rewritten off `forkPoint`, by comparing patches (see
2377
+ * {@link getForkPointFromPatches}) with the base's newest commits only; `undefined`, for the merge base, when that
2378
+ * leaves none, or when git can't say in time, which also clears `reads.pinnable`
2379
+ */
2380
+ async readRewrittenForkPoint(repoPath, forkPoint, tip, reads, cancellation) {
2381
+ const commonPath = this.cache.getCommonPath(repoPath);
2382
+ const unfinishedKey = `${commonPath}\0${forkPoint}\0${tip}`;
2383
+ const retryAt = this.unfinishedPatchChecks.get(unfinishedKey);
2384
+ if (retryAt != null) {
2385
+ if (patchCheckClock.now() < retryAt) {
2386
+ reads.pinnable = false;
2387
+ return;
2388
+ }
2389
+ this.unfinishedPatchChecks.delete(unfinishedKey);
2390
+ }
2391
+ try {
2392
+ const result = await this.git.run({
2393
+ cwd: repoPath,
2394
+ cancellation,
2395
+ errors: "ignore",
2396
+ timeout: patchCheckTimeout,
2397
+ caching: {
2398
+ cache: this.cache.gitResults,
2399
+ commonPath,
2400
+ options: { accessTTL: 3e5 }
2401
+ },
2402
+ ...reads.priority != null ? { priority: reads.priority } : void 0
2403
+ }, "rev-list", "--left-only", "--cherry-mark", "--parents", "--ignore-missing", `${forkPoint}...${tip}`, `^${tip}~${maxPatchCheckDepth}`, "--");
2404
+ if (cancellation?.aborted) throw new CancellationError();
2405
+ if (result.completion.status === "exited" && result.exitCode === 0) return getForkPointFromPatches(result.stdout, forkPoint);
2406
+ if (result.completion.status === "cancelled" && result.completion.reason === "timeout") this.unfinishedPatchChecks.set(unfinishedKey, patchCheckClock.now() + unfinishedPatchCheckTtl);
2407
+ } catch (ex) {
2408
+ if (isCancellationError(ex)) throw ex;
2409
+ }
2410
+ reads.pinnable = false;
2411
+ }
2412
+ /**
2413
+ * `ref`'s reflog (a full ref name), oldest line first, parsed from its file in the common git directory, which
2414
+ * spawns nothing; empty when there's no file, which leaves git no reflog to read either. `undefined` in a reftable
2415
+ * repository, which keeps reflogs out of files, or when the file can't be read or parsed.
2416
+ */
2417
+ async readBaseReflog(repoPath, ref) {
2418
+ const source = await this.getReflogSource(repoPath, ref);
2419
+ if (source == null || source.reftable) return void 0;
2420
+ const { stamp, uri } = source;
2421
+ if (stamp == null) return [];
2422
+ const key = `${this.cache.getCommonPath(repoPath)}\0${ref}`;
2423
+ let slot = this.baseReflogs.get(key);
2424
+ if (slot?.stamp !== stamp) {
2425
+ const read = async () => {
2426
+ try {
2427
+ return parseReflogLines(new TextDecoder().decode(await this.context.fs.readFile(uri)));
2428
+ } catch {
2429
+ return;
2430
+ }
2431
+ };
2432
+ slot = {
2433
+ stamp,
2434
+ lines: read()
2435
+ };
2436
+ this.baseReflogs.set(key, slot);
2437
+ } else this.baseReflogs.touch(key);
2438
+ const { lines } = slot;
2439
+ const result = await lines;
2440
+ if (result === void 0 && this.baseReflogs.get(key)?.lines === lines) this.baseReflogs.delete(key);
2441
+ return result;
2442
+ }
1985
2443
  /** Counts the default branch's own commits past its upstream (see {@link getSelfUpstreamTarget}) for {@link getAheadOfBase} */
1986
2444
  async measureAheadOfSelfUpstream(repoPath, upstream, reads, cancellation) {
1987
2445
  const { dependsOn } = reads;
@@ -2002,14 +2460,23 @@ var BranchesGitSubProvider = class {
2002
2460
  reason: "self",
2003
2461
  dependsOn: [...dependsOn]
2004
2462
  };
2005
- const forkPoint = counts.left === 0 ? upstream.sha : await this.getForkPoint(repoPath, upstream.ref, reads, cancellation);
2463
+ let settled = {
2464
+ forkPoint: upstream.sha,
2465
+ ahead: counts.right,
2466
+ counted: false
2467
+ };
2468
+ if (counts.left !== 0) {
2469
+ const [forkPoint, records] = await Promise.all([this.getForkPoint(repoPath, upstream.ref, reads, cancellation), tolerateRead(() => this.provider.refs.getRefs(repoPath, cancellation))]);
2470
+ if (cancellation?.aborted) throw new CancellationError();
2471
+ settled = await this.settleForkPointAndCount(repoPath, records ?? [], upstream.ref, upstream.sha, forkPoint, counts.right, reads, cancellation);
2472
+ }
2006
2473
  if (cancellation?.aborted) throw new CancellationError();
2007
2474
  return {
2008
2475
  base: {
2009
2476
  ref: upstream.ref,
2010
- ahead: counts.right,
2477
+ ahead: settled.ahead,
2011
2478
  sha: upstream.sha,
2012
- forkPoint,
2479
+ forkPoint: settled.forkPoint,
2013
2480
  tier: "upstream"
2014
2481
  },
2015
2482
  dependsOn: [...dependsOn]
@@ -2296,11 +2763,13 @@ var BranchesGitSubProvider = class {
2296
2763
  return this.getNearestForkTarget(repoPath, branch, candidate, reads, cancellation, { contender: await this.getUpstreamContender(repoPath, candidate, reads, cancellation) });
2297
2764
  }
2298
2765
  /**
2299
- * A candidate base as the ref `reads.from` is measured against: the candidate or its tracking ref, whichever forked
2300
- * nearer, so a stale local base defers to its upstream while one carrying unpushed work wins over it. A
2301
- * `contender` other than the tracking ref is taken only when it forked strictly nearer than both, so a tie keeps
2302
- * the candidate's own pick. A candidate none forks from is used as-is unless git confirms it names no ref: one the
2303
- * cached ref list names is kept, and so is one whose check fails. `undefined` when the candidate is unusable.
2766
+ * A candidate base as the ref `reads.from` is measured against, with its fork point settled (see
2767
+ * {@link settleForkPoint}): the candidate or its tracking ref, whichever forked nearer, so a stale local base defers
2768
+ * to its upstream while one carrying unpushed work wins over it. The candidate must fork past git's reading of its
2769
+ * tracking ref, so commits the tracking ref held and moved off don't make it nearer. A `contender` other than the
2770
+ * tracking ref is taken only when it forked strictly nearer than both, so a tie keeps the candidate's own pick. A
2771
+ * candidate none forks from is used as-is unless git confirms it names no ref: one the cached ref list names is
2772
+ * kept, and so is one whose check fails. `undefined` when the candidate is unusable.
2304
2773
  */
2305
2774
  async getNearestForkTarget(repoPath, branch, candidate, reads, cancellation, options) {
2306
2775
  if (!candidate || candidate.startsWith("-")) return void 0;
@@ -2338,30 +2807,57 @@ var BranchesGitSubProvider = class {
2338
2807
  getUpstreamFork(),
2339
2808
  getContenderMergeBase()
2340
2809
  ]);
2810
+ const refs = await this.provider.refs.getRefs(repoPath, cancellation);
2811
+ const settle = (ref, forkPoint) => this.settleForkPoint(repoPath, refs, ref, findRefTip(refs, ref), forkPoint, reads, cancellation);
2812
+ const isAtOrPast = async (forkPoint, other) => {
2813
+ if (forkPoint == null || other == null) return false;
2814
+ if (forkPoint === other) return true;
2815
+ return this.provider.commits.isAncestorOf(repoPath, forkPoint, other, cancellation);
2816
+ };
2341
2817
  let nearest;
2342
- for (const fork of [{
2818
+ if (candidateMergeBase != null && upstreamFork?.mergeBase != null) {
2819
+ const upstreamMergeBase = upstreamFork.mergeBase;
2820
+ if (!await isAtOrPast(candidateMergeBase, upstreamMergeBase)) {
2821
+ const candidateSettled = await settle(candidate, candidateMergeBase);
2822
+ const candidateForkPoint = candidateSettled.forkPoint;
2823
+ let behind = false;
2824
+ if (candidateForkPoint !== candidateMergeBase) {
2825
+ const mergeBase = candidateForkPoint == null || candidateForkPoint === upstreamMergeBase ? candidateForkPoint : await this.readMergeBase(repoPath, candidateForkPoint, upstreamMergeBase, false, reads, cancellation);
2826
+ behind = mergeBase == null || mergeBase === candidateForkPoint;
2827
+ }
2828
+ if (!behind) nearest = {
2829
+ ref: candidate,
2830
+ settled: candidateSettled
2831
+ };
2832
+ }
2833
+ nearest ??= {
2834
+ ref: upstreamFork.ref,
2835
+ settled: await settle(upstreamFork.ref, upstreamMergeBase)
2836
+ };
2837
+ } else if (candidateMergeBase != null) nearest = {
2343
2838
  ref: candidate,
2344
- mergeBase: candidateMergeBase
2345
- }, upstreamFork]) {
2346
- if (fork?.mergeBase == null) continue;
2347
- if (nearest == null || nearest.mergeBase === fork.mergeBase || await this.provider.commits.isAncestorOf(repoPath, nearest.mergeBase, fork.mergeBase, cancellation)) nearest = {
2348
- ref: fork.ref,
2349
- mergeBase: fork.mergeBase
2839
+ settled: await settle(candidate, candidateMergeBase)
2840
+ };
2841
+ else if (upstreamFork?.mergeBase != null) nearest = {
2842
+ ref: upstreamFork.ref,
2843
+ settled: await settle(upstreamFork.ref, upstreamFork.mergeBase)
2844
+ };
2845
+ if (contender != null && contender !== upstreamFork?.ref && contenderMergeBase != null && nearest?.settled.forkPoint != null && nearest.settled.forkPoint !== contenderMergeBase && await isAtOrPast(nearest.settled.forkPoint, contenderMergeBase)) {
2846
+ const contenderSettled = await settle(contender, contenderMergeBase);
2847
+ if (contenderSettled.forkPoint === contenderMergeBase || contenderSettled.forkPoint !== nearest.settled.forkPoint && await isAtOrPast(nearest.settled.forkPoint, contenderSettled.forkPoint)) nearest = {
2848
+ ref: contender,
2849
+ settled: contenderSettled
2350
2850
  };
2351
2851
  }
2352
- if (contender != null && contender !== upstreamFork?.ref && contenderMergeBase != null && nearest != null && nearest.mergeBase !== contenderMergeBase && await this.provider.commits.isAncestorOf(repoPath, nearest.mergeBase, contenderMergeBase, cancellation)) nearest = {
2353
- ref: contender,
2354
- mergeBase: contenderMergeBase
2355
- };
2356
2852
  if (nearest != null) {
2357
2853
  if (!candidateReads.pinnable) reads.pinnable = false;
2358
2854
  return {
2359
2855
  ref: nearest.ref,
2360
- forkPoint: nearest.mergeBase
2856
+ forkPoint: nearest.settled.forkPoint,
2857
+ rewritten: nearest.settled.rewritten
2361
2858
  };
2362
2859
  }
2363
- const records = await this.provider.refs.getRefs(repoPath, cancellation);
2364
- if (records.length && findRefTip(records, candidate) != null) {
2860
+ if (refs.length && findRefTip(refs, candidate) != null) {
2365
2861
  if (!candidateReads.pinnable) reads.pinnable = false;
2366
2862
  return {
2367
2863
  ref: candidate,
@@ -2444,6 +2940,7 @@ var BranchesGitSubProvider = class {
2444
2940
  expectedExitCodes: [1],
2445
2941
  caching: {
2446
2942
  cache: this.cache.gitResults,
2943
+ ...!forkPoint && isSha(ref1) && isSha(ref2) ? { commonPath: this.cache.getCommonPath(repoPath) } : void 0,
2447
2944
  options: { accessTTL: 3e5 }
2448
2945
  },
2449
2946
  ...reads.priority != null ? { priority: reads.priority } : void 0
@@ -2891,6 +3388,6 @@ function getListedTip(records, fullName) {
2891
3388
  return record != null ? record.peeledObjectname || record.objectname : void 0;
2892
3389
  }
2893
3390
  //#endregion
2894
- export { BranchesGitSubProvider };
3391
+ export { BranchesGitSubProvider, patchCheckClock };
2895
3392
 
2896
3393
  //# sourceMappingURL=branches.js.map