@gitkraken/core-gitlens 0.29.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.
@@ -54,15 +54,19 @@ function parseCommonDir(content) {
54
54
  * uid: Windows has none, so there a folder git would refuse is still read), or a repository above it whose working
55
55
  * tree might track it as a submodule. The caller rules out the environment (see {@link isGitDirMovedByEnv}).
56
56
  * Never rejects.
57
+ *
58
+ * Sibling checkouts ask the same question of the same folders, so `superprojects`, when given, holds the answers by
59
+ * parent folder. A stale one can't change the git dirs: "no" can only miss a superproject created since, and "maybe"
60
+ * only asks git.
57
61
  */
58
- async function readGitDirs(repoPath) {
62
+ async function readGitDirs(repoPath, superprojects) {
59
63
  try {
60
- return await readGitDirsCore(repoPath);
64
+ return await readGitDirsCore(repoPath, superprojects);
61
65
  } catch {
62
66
  return;
63
67
  }
64
68
  }
65
- async function readGitDirsCore(repoPath) {
69
+ async function readGitDirsCore(repoPath, superprojects) {
66
70
  if (!isAbsolute(repoPath)) return void 0;
67
71
  const realRepoPath = await realpath(repoPath);
68
72
  const dotGit = join(repoPath, ".git");
@@ -98,7 +102,8 @@ async function readGitDirsCore(repoPath) {
98
102
  (await stat(gitDir)).uid
99
103
  ].some((o) => o !== uid)) return void 0;
100
104
  }
101
- if (await mayHaveSuperproject(realRepoPath)) return void 0;
105
+ const parentFolder = dirname(realRepoPath);
106
+ if (await (superprojects != null && parentFolder !== realRepoPath ? superprojects.getOrCreate(parentFolder, () => mayHaveSuperproject(realRepoPath)) : mayHaveSuperproject(realRepoPath))) return void 0;
102
107
  return {
103
108
  gitDir,
104
109
  commonGitDir
@@ -1 +1 @@
1
- {"version":3,"file":"gitDirResolver.js","names":[],"sources":["../../../../git-cli/src/exec/gitDirResolver.ts"],"sourcesContent":["import type { Stats } from 'node:fs';\nimport { lstat, readFile, realpath, stat } from 'node:fs/promises';\nimport { dirname, isAbsolute, join } from 'node:path';\nimport * as nodeProcess from 'node:process';\nimport { normalizePath } from '@gitlens/utils/path.js';\n\n/** Environment variables that change which repository, git dir or working tree git finds from a `cwd` */\nconst locationEnvKeys = [\n\t'GIT_DIR',\n\t'GIT_COMMON_DIR',\n\t'GIT_WORK_TREE',\n\t'GIT_CEILING_DIRECTORIES',\n\t'GIT_DISCOVERY_ACROSS_FILESYSTEM',\n];\n/** `-c` overrides, passed through the environment, that move or remove the working tree */\nconst locationConfigRegex = /core\\.(?:worktree|bare)|include/i;\n\nconst gitFilePrefix = 'gitdir: ';\nconst trailingNewlinesRegex = /[\\r\\n]+$/;\nconst newlineRegex = /[\\r\\n]/;\nconst headRegex = /^(?:ref:\\s*refs\\/|[0-9a-f]{40}(?:[0-9a-f]{24})?\\s*$)/;\n// git reads a key, or another section header, on the rest of a section header's line too (`[core] bare = true`)\nconst worktreeKeyRegex = /^(?:[ \\t]*\\[[^\\]\\r\\n]*\\])?[ \\t]*worktree[ \\t]*=/im;\nconst includeSectionRegex = /^(?:[ \\t]*\\[[^\\]\\r\\n]*\\])?[ \\t]*\\[[ \\t]*include/im;\nconst bareKeyRegex = /^(?:[ \\t]*\\[[^\\]\\r\\n]*\\])?[ \\t]*bare[ \\t]*(?:=[ \\t]*(.*?))?[ \\t\\r]*$/gim;\nconst boolTrueRegex = /^(?:true|yes|on|1)$/i;\nconst boolFalseRegex = /^(?:false|no|off|0)$/i;\n\n/**\n * Whether git run with `env` might find another git dir or working tree than {@link readGitDirs} reads: one set\n * through the environment, or through `-c` overrides passed in it\n */\nexport function isGitDirMovedByEnv(env: Readonly<Record<string, string | undefined>>): boolean {\n\tif (locationEnvKeys.some(k => env[k] != null)) return true;\n\tif (env.GIT_CONFIG_PARAMETERS != null && locationConfigRegex.test(env.GIT_CONFIG_PARAMETERS)) return true;\n\tif (env.GIT_CONFIG_COUNT == null) return false;\n\n\tconst count = Number(env.GIT_CONFIG_COUNT);\n\tif (!Number.isInteger(count)) return true;\n\n\tfor (let i = 0; i < count; i++) {\n\t\tif (locationConfigRegex.test(env[`GIT_CONFIG_KEY_${i}`] ?? '')) return true;\n\t}\n\treturn false;\n}\n\n/** The path a `.git` file names, as written (absolute, or relative to the file's folder); `undefined` when git would reject it */\nexport function parseGitFile(content: string): string | undefined {\n\tif (!content.startsWith(gitFilePrefix)) return undefined;\n\n\tconst path = content.slice(gitFilePrefix.length).replace(trailingNewlinesRegex, '');\n\treturn path && !newlineRegex.test(path) ? path : undefined;\n}\n\n/** The path a linked worktree's `commondir` file names, as written (absolute, or relative to its git dir) */\nexport function parseCommonDir(content: string): string | undefined {\n\treturn content.replace(trailingNewlinesRegex, '') || undefined;\n}\n\n/**\n * The git dir and common git dir `git rev-parse --git-dir --git-common-dir` reports from the working tree `repoPath`,\n * read without running git, and only when that working tree has no superproject. `undefined` whenever the layout is\n * one git might answer differently for: no `.git` at `repoPath` (a subfolder, a bare repository), a git dir a `.git`\n * file names without a `commondir` (a submodule, `--separate-git-dir`), a `core.bare`, `core.worktree` or `include`\n * in its config, a folder owned by another user (git's `safe.directory` check, made only where the process has a\n * uid: Windows has none, so there a folder git would refuse is still read), or a repository above it whose working\n * tree might track it as a submodule. The caller rules out the environment (see {@link isGitDirMovedByEnv}).\n * Never rejects.\n */\nexport async function readGitDirs(repoPath: string): Promise<{ gitDir: string; commonGitDir: string } | undefined> {\n\ttry {\n\t\treturn await readGitDirsCore(repoPath);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nasync function readGitDirsCore(repoPath: string): Promise<{ gitDir: string; commonGitDir: string } | undefined> {\n\tif (!isAbsolute(repoPath)) return undefined;\n\n\t// git searches from the physical `cwd`, so a relative path in a `.git` file resolves against it\n\tconst realRepoPath = await realpath(repoPath);\n\tconst dotGit = join(repoPath, '.git');\n\tconst dotGitStats = await stat(dotGit);\n\n\tlet gitDir: string;\n\tlet commonGitDir: string;\n\tlet linked: boolean;\n\tif (dotGitStats.isDirectory()) {\n\t\tif ((await statIfExists(join(dotGit, 'commondir'))) != null) return undefined;\n\n\t\t// rev-parse prints `.git` relative to the `cwd`, which is how the caller's path reaches it\n\t\tgitDir = commonGitDir = dotGit;\n\t\tlinked = false;\n\t} else if (dotGitStats.isFile()) {\n\t\tconst target = parseGitFile(await readFile(dotGit, 'utf8'));\n\t\tif (target == null) return undefined;\n\n\t\tgitDir = await realpath(isAbsolute(target) ? target : `${realRepoPath}/${target}`);\n\t\tconst common = parseCommonDir(await readFile(join(gitDir, 'commondir'), 'utf8'));\n\t\tif (common == null) return undefined;\n\n\t\tcommonGitDir = await realpath(isAbsolute(common) ? common : `${gitDir}/${common}`);\n\t\t// A submodule's git dir, which its linked worktrees share, is under its superproject's `modules` folder\n\t\tif (normalizePath(gitDir).includes('/modules/') || normalizePath(commonGitDir).includes('/modules/')) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tlinked = true;\n\t} else {\n\t\treturn undefined;\n\t}\n\n\t// What makes a folder a git dir to git; without it, git keeps searching the folders above\n\tif (!headRegex.test(await readFile(join(gitDir, 'HEAD'), 'utf8'))) return undefined;\n\tif (!(await stat(join(commonGitDir, 'objects'))).isDirectory()) return undefined;\n\tif (!(await stat(join(commonGitDir, 'refs'))).isDirectory()) return undefined;\n\n\t// A linked worktree ignores a `core.bare` in the shared config (a bare repository's worktrees), not in its own\n\tif (!isPlainConfig(await readFile(join(commonGitDir, 'config'), 'utf8'), !linked)) return undefined;\n\n\tconst worktreeConfig = await readFileIfExists(join(gitDir, 'config.worktree'));\n\tif (worktreeConfig != null && !isPlainConfig(worktreeConfig, true)) return undefined;\n\n\tconst uid = nodeProcess.geteuid?.();\n\tif (uid != null) {\n\t\tconst owners = [(await stat(repoPath)).uid, (await lstat(dotGit)).uid, (await stat(gitDir)).uid];\n\t\tif (owners.some(o => o !== uid)) return undefined;\n\t}\n\n\tif (await mayHaveSuperproject(realRepoPath)) return undefined;\n\n\treturn { gitDir: gitDir, commonGitDir: commonGitDir };\n}\n\n/**\n * Whether a repository above `realRepoPath` could list it as a submodule. `rev-parse --show-superproject-working-tree`\n * asks the repository git finds from the parent folder; only a bare one, having no index, can't list it. Rejects when\n * a folder above can't be read.\n */\nasync function mayHaveSuperproject(realRepoPath: string): Promise<boolean> {\n\tlet folder = realRepoPath;\n\tfor (;;) {\n\t\tconst parent = dirname(folder);\n\t\tif (parent === folder) return false;\n\n\t\tfolder = parent;\n\n\t\tconst dotGit = join(folder, '.git');\n\t\tconst dotGitStats = await statIfExists(dotGit);\n\t\tif (dotGitStats?.isFile()) {\n\t\t\tconst target = parseGitFile(await readFile(dotGit, 'utf8'));\n\t\t\tif (target == null) return true;\n\n\t\t\tconst gitDir = isAbsolute(target) ? target : `${folder}/${target}`;\n\t\t\tif ((await statIfExists(join(gitDir, 'commondir'))) != null) return true;\n\n\t\t\treturn !isBareConfig(await readFile(join(gitDir, 'config'), 'utf8'));\n\t\t}\n\n\t\t// git passes over a `.git` folder, or a folder, that isn't a git dir\n\t\tif (dotGitStats?.isDirectory() && (await isGitDirectory(dotGit))) {\n\t\t\treturn !isBareConfig(await readFile(join(dotGit, 'config'), 'utf8'));\n\t\t}\n\t\tif (await isGitDirectory(folder)) return !isBareConfig(await readFile(join(folder, 'config'), 'utf8'));\n\t}\n}\n\n/** Whether a folder is a git dir: a valid `HEAD`, and the `objects` and `refs` folders (or a `commondir` to them) */\nasync function isGitDirectory(path: string): Promise<boolean> {\n\tconst head = await readFileIfExists(join(path, 'HEAD'));\n\tif (head == null || !headRegex.test(head)) return false;\n\tif ((await statIfExists(join(path, 'commondir'))) != null) return true;\n\n\treturn (\n\t\t(await statIfExists(join(path, 'objects')))?.isDirectory() === true &&\n\t\t(await statIfExists(join(path, 'refs')))?.isDirectory() === true\n\t);\n}\n\n/** Whether a config sets nothing that moves the working tree; `checkBare` also rules out a `core.bare` not plainly false */\nfunction isPlainConfig(config: string, checkBare: boolean): boolean {\n\tif (worktreeKeyRegex.test(config) || includeSectionRegex.test(config)) return false;\n\tif (!checkBare) return true;\n\n\tconst bare = getBare(config);\n\treturn bare == null || bare === false;\n}\n\n/** Whether a config is plainly a bare repository's, with no working tree set anywhere */\nfunction isBareConfig(config: string): boolean {\n\treturn !worktreeKeyRegex.test(config) && !includeSectionRegex.test(config) && getBare(config) === true;\n}\n\n/** The last `bare` value in a config: `undefined` when unset, `'unknown'` when not a plain boolean */\nfunction getBare(config: string): boolean | 'unknown' | undefined {\n\tlet bare: boolean | 'unknown' | undefined;\n\tfor (const match of config.matchAll(bareKeyRegex)) {\n\t\tconst value = match[1];\n\t\tif (value == null || boolTrueRegex.test(value)) {\n\t\t\tbare = true;\n\t\t} else if (boolFalseRegex.test(value)) {\n\t\t\tbare = false;\n\t\t} else {\n\t\t\tbare = 'unknown';\n\t\t}\n\t}\n\treturn bare;\n}\n\nasync function statIfExists(path: string): Promise<Stats | undefined> {\n\ttry {\n\t\treturn await stat(path);\n\t} catch (ex) {\n\t\tconst code = (ex as NodeJS.ErrnoException).code;\n\t\tif (code === 'ENOENT' || code === 'ENOTDIR') return undefined;\n\n\t\tthrow ex;\n\t}\n}\n\nasync function readFileIfExists(path: string): Promise<string | undefined> {\n\ttry {\n\t\treturn await readFile(path, 'utf8');\n\t} catch (ex) {\n\t\tconst code = (ex as NodeJS.ErrnoException).code;\n\t\tif (code === 'ENOENT' || code === 'ENOTDIR') return undefined;\n\n\t\tthrow ex;\n\t}\n}\n"],"mappings":";;;;;;AAOA,MAAM,kBAAkB;CACvB;CACA;CACA;CACA;CACA;AACD;;AAEA,MAAM,sBAAsB;AAE5B,MAAM,gBAAgB;AACtB,MAAM,wBAAwB;AAC9B,MAAM,eAAe;AACrB,MAAM,YAAY;AAElB,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;;;;;AAMvB,SAAgB,mBAAmB,KAA4D;CAC9F,IAAI,gBAAgB,MAAK,MAAK,IAAI,MAAM,IAAI,GAAG,OAAO;CACtD,IAAI,IAAI,yBAAyB,QAAQ,oBAAoB,KAAK,IAAI,qBAAqB,GAAG,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Q,MAAM;CAC3B,OAAO,QAAQ,QAAQ,SAAS;AACjC;;AAGA,SAAS,aAAa,QAAyB;CAC9C,OAAO,CAAC,iBAAiB,KAAK,MAAM,KAAK,CAAC,oBAAoB,KAAK,MAAM,KAAK,QAAQ,MAAM,MAAM;AACnG;;AAGA,SAAS,QAAQ,QAAiD;CACjE,IAAI;CACJ,KAAK,MAAM,SAAS,OAAO,SAAS,YAAY,GAAG;EAClD,MAAM,QAAQ,MAAM;EACpB,IAAI,SAAS,QAAQ,cAAc,KAAK,KAAK,GAC5C,OAAO;OACD,IAAI,eAAe,KAAK,KAAK,GACnC,OAAO;OAEP,OAAO;CAET;CACA,OAAO;AACR;AAEA,eAAe,aAAa,MAA0C;CACrE,IAAI;EACH,OAAO,MAAM,KAAK,IAAI;CACvB,SAAS,IAAI;EACZ,MAAM,OAAQ,GAA6B;EAC3C,IAAI,SAAS,YAAY,SAAS,WAAW,OAAO,KAAA;EAEpD,MAAM;CACP;AACD;AAEA,eAAe,iBAAiB,MAA2C;CAC1E,IAAI;EACH,OAAO,MAAM,SAAS,MAAM,MAAM;CACnC,SAAS,IAAI;EACZ,MAAM,OAAQ,GAA6B;EAC3C,IAAI,SAAS,YAAY,SAAS,WAAW,OAAO,KAAA;EAEpD,MAAM;CACP;AACD"}
1
+ {"version":3,"file":"gitDirResolver.js","names":[],"sources":["../../../../git-cli/src/exec/gitDirResolver.ts"],"sourcesContent":["import type { Stats } from 'node:fs';\nimport { lstat, readFile, realpath, stat } from 'node:fs/promises';\nimport { dirname, isAbsolute, join } from 'node:path';\nimport * as nodeProcess from 'node:process';\nimport { normalizePath } from '@gitlens/utils/path.js';\nimport type { PromiseCache } from '@gitlens/utils/promiseCache.js';\n\n/** Environment variables that change which repository, git dir or working tree git finds from a `cwd` */\nconst locationEnvKeys = [\n\t'GIT_DIR',\n\t'GIT_COMMON_DIR',\n\t'GIT_WORK_TREE',\n\t'GIT_CEILING_DIRECTORIES',\n\t'GIT_DISCOVERY_ACROSS_FILESYSTEM',\n];\n/** `-c` overrides, passed through the environment, that move or remove the working tree */\nconst locationConfigRegex = /core\\.(?:worktree|bare)|include/i;\n\nconst gitFilePrefix = 'gitdir: ';\nconst trailingNewlinesRegex = /[\\r\\n]+$/;\nconst newlineRegex = /[\\r\\n]/;\nconst headRegex = /^(?:ref:\\s*refs\\/|[0-9a-f]{40}(?:[0-9a-f]{24})?\\s*$)/;\n// git reads a key, or another section header, on the rest of a section header's line too (`[core] bare = true`)\nconst worktreeKeyRegex = /^(?:[ \\t]*\\[[^\\]\\r\\n]*\\])?[ \\t]*worktree[ \\t]*=/im;\nconst includeSectionRegex = /^(?:[ \\t]*\\[[^\\]\\r\\n]*\\])?[ \\t]*\\[[ \\t]*include/im;\nconst bareKeyRegex = /^(?:[ \\t]*\\[[^\\]\\r\\n]*\\])?[ \\t]*bare[ \\t]*(?:=[ \\t]*(.*?))?[ \\t\\r]*$/gim;\nconst boolTrueRegex = /^(?:true|yes|on|1)$/i;\nconst boolFalseRegex = /^(?:false|no|off|0)$/i;\n\n/**\n * Whether git run with `env` might find another git dir or working tree than {@link readGitDirs} reads: one set\n * through the environment, or through `-c` overrides passed in it\n */\nexport function isGitDirMovedByEnv(env: Readonly<Record<string, string | undefined>>): boolean {\n\tif (locationEnvKeys.some(k => env[k] != null)) return true;\n\tif (env.GIT_CONFIG_PARAMETERS != null && locationConfigRegex.test(env.GIT_CONFIG_PARAMETERS)) return true;\n\tif (env.GIT_CONFIG_COUNT == null) return false;\n\n\tconst count = Number(env.GIT_CONFIG_COUNT);\n\tif (!Number.isInteger(count)) return true;\n\n\tfor (let i = 0; i < count; i++) {\n\t\tif (locationConfigRegex.test(env[`GIT_CONFIG_KEY_${i}`] ?? '')) return true;\n\t}\n\treturn false;\n}\n\n/** The path a `.git` file names, as written (absolute, or relative to the file's folder); `undefined` when git would reject it */\nexport function parseGitFile(content: string): string | undefined {\n\tif (!content.startsWith(gitFilePrefix)) return undefined;\n\n\tconst path = content.slice(gitFilePrefix.length).replace(trailingNewlinesRegex, '');\n\treturn path && !newlineRegex.test(path) ? path : undefined;\n}\n\n/** The path a linked worktree's `commondir` file names, as written (absolute, or relative to its git dir) */\nexport function parseCommonDir(content: string): string | undefined {\n\treturn content.replace(trailingNewlinesRegex, '') || undefined;\n}\n\n/**\n * The git dir and common git dir `git rev-parse --git-dir --git-common-dir` reports from the working tree `repoPath`,\n * read without running git, and only when that working tree has no superproject. `undefined` whenever the layout is\n * one git might answer differently for: no `.git` at `repoPath` (a subfolder, a bare repository), a git dir a `.git`\n * file names without a `commondir` (a submodule, `--separate-git-dir`), a `core.bare`, `core.worktree` or `include`\n * in its config, a folder owned by another user (git's `safe.directory` check, made only where the process has a\n * uid: Windows has none, so there a folder git would refuse is still read), or a repository above it whose working\n * tree might track it as a submodule. The caller rules out the environment (see {@link isGitDirMovedByEnv}).\n * Never rejects.\n *\n * Sibling checkouts ask the same question of the same folders, so `superprojects`, when given, holds the answers by\n * parent folder. A stale one can't change the git dirs: \"no\" can only miss a superproject created since, and \"maybe\"\n * only asks git.\n */\nexport async function readGitDirs(\n\trepoPath: string,\n\tsuperprojects?: PromiseCache<string, boolean>,\n): Promise<{ gitDir: string; commonGitDir: string } | undefined> {\n\ttry {\n\t\treturn await readGitDirsCore(repoPath, superprojects);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nasync function readGitDirsCore(\n\trepoPath: string,\n\tsuperprojects: PromiseCache<string, boolean> | undefined,\n): Promise<{ gitDir: string; commonGitDir: string } | undefined> {\n\tif (!isAbsolute(repoPath)) return undefined;\n\n\t// git searches from the physical `cwd`, so a relative path in a `.git` file resolves against it\n\tconst realRepoPath = await realpath(repoPath);\n\tconst dotGit = join(repoPath, '.git');\n\tconst dotGitStats = await stat(dotGit);\n\n\tlet gitDir: string;\n\tlet commonGitDir: string;\n\tlet linked: boolean;\n\tif (dotGitStats.isDirectory()) {\n\t\tif ((await statIfExists(join(dotGit, 'commondir'))) != null) return undefined;\n\n\t\t// rev-parse prints `.git` relative to the `cwd`, which is how the caller's path reaches it\n\t\tgitDir = commonGitDir = dotGit;\n\t\tlinked = false;\n\t} else if (dotGitStats.isFile()) {\n\t\tconst target = parseGitFile(await readFile(dotGit, 'utf8'));\n\t\tif (target == null) return undefined;\n\n\t\tgitDir = await realpath(isAbsolute(target) ? target : `${realRepoPath}/${target}`);\n\t\tconst common = parseCommonDir(await readFile(join(gitDir, 'commondir'), 'utf8'));\n\t\tif (common == null) return undefined;\n\n\t\tcommonGitDir = await realpath(isAbsolute(common) ? common : `${gitDir}/${common}`);\n\t\t// A submodule's git dir, which its linked worktrees share, is under its superproject's `modules` folder\n\t\tif (normalizePath(gitDir).includes('/modules/') || normalizePath(commonGitDir).includes('/modules/')) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tlinked = true;\n\t} else {\n\t\treturn undefined;\n\t}\n\n\t// What makes a folder a git dir to git; without it, git keeps searching the folders above\n\tif (!headRegex.test(await readFile(join(gitDir, 'HEAD'), 'utf8'))) return undefined;\n\tif (!(await stat(join(commonGitDir, 'objects'))).isDirectory()) return undefined;\n\tif (!(await stat(join(commonGitDir, 'refs'))).isDirectory()) return undefined;\n\n\t// A linked worktree ignores a `core.bare` in the shared config (a bare repository's worktrees), not in its own\n\tif (!isPlainConfig(await readFile(join(commonGitDir, 'config'), 'utf8'), !linked)) return undefined;\n\n\tconst worktreeConfig = await readFileIfExists(join(gitDir, 'config.worktree'));\n\tif (worktreeConfig != null && !isPlainConfig(worktreeConfig, true)) return undefined;\n\n\tconst uid = nodeProcess.geteuid?.();\n\tif (uid != null) {\n\t\tconst owners = [(await stat(repoPath)).uid, (await lstat(dotGit)).uid, (await stat(gitDir)).uid];\n\t\tif (owners.some(o => o !== uid)) return undefined;\n\t}\n\n\t// A checkout at a filesystem root is its own parent folder, but asks about the folders above it, where a\n\t// checkout below it asks about the root too\n\tconst parentFolder = dirname(realRepoPath);\n\tconst mayHave =\n\t\tsuperprojects != null && parentFolder !== realRepoPath\n\t\t\t? superprojects.getOrCreate(parentFolder, () => mayHaveSuperproject(realRepoPath))\n\t\t\t: mayHaveSuperproject(realRepoPath);\n\tif (await mayHave) return undefined;\n\n\treturn { gitDir: gitDir, commonGitDir: commonGitDir };\n}\n\n/**\n * Whether a repository above `realRepoPath` could list it as a submodule. `rev-parse --show-superproject-working-tree`\n * asks the repository git finds from the parent folder; only a bare one, having no index, can't list it. Rejects when\n * a folder above can't be read.\n */\nasync function mayHaveSuperproject(realRepoPath: string): Promise<boolean> {\n\tlet folder = realRepoPath;\n\tfor (;;) {\n\t\tconst parent = dirname(folder);\n\t\tif (parent === folder) return false;\n\n\t\tfolder = parent;\n\n\t\tconst dotGit = join(folder, '.git');\n\t\tconst dotGitStats = await statIfExists(dotGit);\n\t\tif (dotGitStats?.isFile()) {\n\t\t\tconst target = parseGitFile(await readFile(dotGit, 'utf8'));\n\t\t\tif (target == null) return true;\n\n\t\t\tconst gitDir = isAbsolute(target) ? target : `${folder}/${target}`;\n\t\t\tif ((await statIfExists(join(gitDir, 'commondir'))) != null) return true;\n\n\t\t\treturn !isBareConfig(await readFile(join(gitDir, 'config'), 'utf8'));\n\t\t}\n\n\t\t// git passes over a `.git` folder, or a folder, that isn't a git dir\n\t\tif (dotGitStats?.isDirectory() && (await isGitDirectory(dotGit))) {\n\t\t\treturn !isBareConfig(await readFile(join(dotGit, 'config'), 'utf8'));\n\t\t}\n\t\tif (await isGitDirectory(folder)) return !isBareConfig(await readFile(join(folder, 'config'), 'utf8'));\n\t}\n}\n\n/** Whether a folder is a git dir: a valid `HEAD`, and the `objects` and `refs` folders (or a `commondir` to them) */\nasync function isGitDirectory(path: string): Promise<boolean> {\n\tconst head = await readFileIfExists(join(path, 'HEAD'));\n\tif (head == null || !headRegex.test(head)) return false;\n\tif ((await statIfExists(join(path, 'commondir'))) != null) return true;\n\n\treturn (\n\t\t(await statIfExists(join(path, 'objects')))?.isDirectory() === true &&\n\t\t(await statIfExists(join(path, 'refs')))?.isDirectory() === true\n\t);\n}\n\n/** Whether a config sets nothing that moves the working tree; `checkBare` also rules out a `core.bare` not plainly false */\nfunction isPlainConfig(config: string, checkBare: boolean): boolean {\n\tif (worktreeKeyRegex.test(config) || includeSectionRegex.test(config)) return false;\n\tif (!checkBare) return true;\n\n\tconst bare = getBare(config);\n\treturn bare == null || bare === false;\n}\n\n/** Whether a config is plainly a bare repository's, with no working tree set anywhere */\nfunction isBareConfig(config: string): boolean {\n\treturn !worktreeKeyRegex.test(config) && !includeSectionRegex.test(config) && getBare(config) === true;\n}\n\n/** The last `bare` value in a config: `undefined` when unset, `'unknown'` when not a plain boolean */\nfunction getBare(config: string): boolean | 'unknown' | undefined {\n\tlet bare: boolean | 'unknown' | undefined;\n\tfor (const match of config.matchAll(bareKeyRegex)) {\n\t\tconst value = match[1];\n\t\tif (value == null || boolTrueRegex.test(value)) {\n\t\t\tbare = true;\n\t\t} else if (boolFalseRegex.test(value)) {\n\t\t\tbare = false;\n\t\t} else {\n\t\t\tbare = 'unknown';\n\t\t}\n\t}\n\treturn bare;\n}\n\nasync function statIfExists(path: string): Promise<Stats | undefined> {\n\ttry {\n\t\treturn await stat(path);\n\t} catch (ex) {\n\t\tconst code = (ex as NodeJS.ErrnoException).code;\n\t\tif (code === 'ENOENT' || code === 'ENOTDIR') return undefined;\n\n\t\tthrow ex;\n\t}\n}\n\nasync function readFileIfExists(path: string): Promise<string | undefined> {\n\ttry {\n\t\treturn await readFile(path, 'utf8');\n\t} catch (ex) {\n\t\tconst code = (ex as NodeJS.ErrnoException).code;\n\t\tif (code === 'ENOENT' || code === 'ENOTDIR') return undefined;\n\n\t\tthrow ex;\n\t}\n}\n"],"mappings":";;;;;;AAQA,MAAM,kBAAkB;CACvB;CACA;CACA;CACA;CACA;AACD;;AAEA,MAAM,sBAAsB;AAE5B,MAAM,gBAAgB;AACtB,MAAM,wBAAwB;AAC9B,MAAM,eAAe;AACrB,MAAM,YAAY;AAElB,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,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AAM,WAAW,CAAC,KAAM,MAAM,OAAO;CAElE,QACE,MAAM,aAAa,KAAK,MAAM,SAAS,CAAC,EAAA,EAAI,YAAY,MAAM,SAC9D,MAAM,aAAa,KAAK,MAAM,MAAM,CAAC,EAAA,EAAI,YAAY,MAAM;AAE9D;;AAGA,SAAS,cAAc,QAAgB,WAA6B;CACnE,IAAI,iBAAiB,KAAK,MAAM,KAAK,oBAAoB,KAAK,MAAM,GAAG,OAAO;CAC9E,IAAI,CAAC,WAAW,OAAO;CAEvB,MAAM,OAAO,QAAQ,MAAM;CAC3B,OAAO,QAAQ,QAAQ,SAAS;AACjC;;AAGA,SAAS,aAAa,QAAyB;CAC9C,OAAO,CAAC,iBAAiB,KAAK,MAAM,KAAK,CAAC,oBAAoB,KAAK,MAAM,KAAK,QAAQ,MAAM,MAAM;AACnG;;AAGA,SAAS,QAAQ,QAAiD;CACjE,IAAI;CACJ,KAAK,MAAM,SAAS,OAAO,SAAS,YAAY,GAAG;EAClD,MAAM,QAAQ,MAAM;EACpB,IAAI,SAAS,QAAQ,cAAc,KAAK,KAAK,GAC5C,OAAO;OACD,IAAI,eAAe,KAAK,KAAK,GACnC,OAAO;OAEP,OAAO;CAET;CACA,OAAO;AACR;AAEA,eAAe,aAAa,MAA0C;CACrE,IAAI;EACH,OAAO,MAAM,KAAK,IAAI;CACvB,SAAS,IAAI;EACZ,MAAM,OAAQ,GAA6B;EAC3C,IAAI,SAAS,YAAY,SAAS,WAAW,OAAO,KAAA;EAEpD,MAAM;CACP;AACD;AAEA,eAAe,iBAAiB,MAA2C;CAC1E,IAAI;EACH,OAAO,MAAM,SAAS,MAAM,MAAM;CACnC,SAAS,IAAI;EACZ,MAAM,OAAQ,GAA6B;EAC3C,IAAI,SAAS,YAAY,SAAS,WAAW,OAAO,KAAA;EAEpD,MAAM;CACP;AACD"}
@@ -81,7 +81,16 @@ export declare class BranchesGitSubProvider implements GitBranchesSubProvider {
81
81
  getBranch(repoPath: string, name?: string, options?: {
82
82
  force?: boolean;
83
83
  }, cancellation?: AbortSignal): Promise<GitBranch | undefined>;
84
+ /**
85
+ * What `getBranches(repoPath)` would answer for the named branch, or for the current one when `name` is omitted,
86
+ * without keeping that worktree's copy of the whole list, and whether the shared list it read is still kept
87
+ */
88
+ private getBranchFromSharedList;
89
+ /** The current ref of `repoPath` and the default worktree path of `commonPath`, rejecting if the caller aborted mid-read */
90
+ private getCurrentRefAndDefaultWorktreePath;
84
91
  private getCurrentBranch;
92
+ /** The branches of the repository at `commonPath`, as the list every one of its worktrees maps from */
93
+ private getSharedBranchesCore;
85
94
  getBranches(repoPath: string, options?: {
86
95
  filter?: (b: GitBranch) => boolean;
87
96
  ordering?: 'date' | 'author-date' | 'topo' | null;
@@ -179,6 +179,22 @@ const storedMergeKeys = [
179
179
  "gk-target-base",
180
180
  "gk-merge-base"
181
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
+ }
182
198
  var BranchesGitSubProvider = class {
183
199
  context;
184
200
  git;
@@ -249,20 +265,82 @@ var BranchesGitSubProvider = class {
249
265
  this.provider = provider;
250
266
  }
251
267
  async getBranch(repoPath, name, options, cancellation) {
268
+ const scope = getScopedLogger();
252
269
  if (options?.force) this.cache.evictCaches(repoPath, "branches");
253
- if (name != null) {
254
- 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();
255
275
  return branch;
256
- }
257
- const branchPromise = this.cache.branch.getOrCreate(repoPath, async (_cacheable, signal) => {
258
- const { values: [branch] } = await this.getBranches(repoPath, { filter: (b) => b.current }, signal);
259
- return branch ?? this.getCurrentBranch(repoPath, void 0, void 0, signal);
260
276
  }, cancellation);
261
- if (branchPromise == null) {
262
- const { values: [branch] } = await this.getBranches(repoPath, { filter: (b) => b.current }, cancellation);
263
- 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
+ };
264
312
  }
265
- 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
+ };
266
344
  }
267
345
  async getCurrentBranch(repoPath, metadataMap, ordering, cancellation) {
268
346
  const ref = await this.getCurrentBranchReferenceCore(repoPath, ordering, cancellation);
@@ -297,107 +375,107 @@ var BranchesGitSubProvider = class {
297
375
  isDefault: repoPath === defaultWorktreePath
298
376
  }, void 0, rebaseStatus != null);
299
377
  }
300
- async getBranches(repoPath, options, cancellation) {
301
- if (repoPath == null) return emptyPagedResult;
302
- const scope = getScopedLogger();
303
- const getCore = async (commonPath, cacheable, signal) => {
304
- 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 {
305
381
  try {
306
- try {
307
- var _usingCtx$1 = _usingCtx();
308
- const [recordsResult, supportedResult, defaultWorktreePathResult, metadataMapResult] = await Promise.allSettled([
309
- this.provider.refs.getRefs(commonPath, signal),
310
- this.git.supported("git:for-each-ref"),
311
- this.provider.config.getDefaultWorktreePath?.(commonPath),
312
- this.getBranchMetadataMap(commonPath)
313
- ]);
314
- const records = getSettledValue(recordsResult) ?? [];
315
- const supported = getSettledValue(supportedResult) ?? [];
316
- const metadataMap = getSettledValue(metadataMapResult) ?? /* @__PURE__ */ new Map();
317
- const defaultWorktreePath = getSettledValue(defaultWorktreePathResult);
318
- const worktreePathSupported = supported.includes("git:for-each-ref:worktreePath");
319
- 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;
320
416
  cacheable?.invalidate();
321
- const current = await this.getCurrentBranch(commonPath, metadataMap, options?.ordering ?? this.context.config?.commits.ordering ?? void 0, signal);
322
- return current != null ? { values: [current] } : emptyPagedResult;
323
- }
324
- const sw = _usingCtx$1.u(maybeStopWatch(scope, { log: {
325
- onlyExit: true,
326
- level: "debug"
327
- } }));
328
- const branches = [];
329
- let remoteNames;
330
- const resolveUpstreamRemote = async (upstream) => {
331
- if (!upstream.startsWith("refs/remotes/")) return void 0;
332
- const { name } = parseRefName(upstream);
333
- if (!name.includes("/", name.indexOf("/") + 1)) return void 0;
334
- remoteNames ??= this.provider.remotes.getRemotes(commonPath, void 0, signal).then((remotes) => {
335
- if (!remotes.length) cacheable?.invalidate();
336
- return remotes.map((r) => r.name);
337
- }, (ex) => {
338
- if (isCancellationError(ex)) throw ex;
339
- cacheable?.invalidate();
340
- return [];
341
- });
342
- return splitRemoteBranchName(name, await remoteNames)?.[0];
343
- };
344
- for (const record of records) {
345
- const fullName = record.name;
346
- if (!fullName.startsWith("refs/heads/") && !fullName.startsWith("refs/remotes/")) continue;
347
- if (isRemoteHEAD(fullName)) continue;
348
- const upstream = parseUpstream(record.upstream, record.upstreamTracking, record.upstreamRemote ?? (!worktreePathSupported ? await resolveUpstreamRemote(record.upstream) : void 0), record.upstreamRemoteRef);
349
- const metadata = metadataMap.get(parseRefName(fullName).name);
350
- const worktreePath = record.worktreePath ? normalizePath(record.worktreePath) : void 0;
351
- branches.push(new GitBranch(commonPath, fullName, false, record.committerDate ? new Date(record.committerDate) : void 0, metadata, record.objectname, upstream, worktreePathSupported ? worktreePath ? {
352
- path: worktreePath,
353
- isDefault: worktreePath === defaultWorktreePath
354
- } : false : void 0));
355
- }
356
- sw?.stop({ suffix: ` parsed ${branches.length} branches` });
357
- for (const branch of branches) if (branch.worktree && branch.worktree.path) {
358
- const { name } = parseRefName(branch.refName);
359
- const reference = createReference(name, branch.worktree.path, {
360
- refType: "branch",
361
- name,
362
- id: getBranchId(branch.worktree.path, false, name),
363
- remote: false,
364
- upstream: branch.upstream?.name ? {
365
- name: branch.upstream.name,
366
- missing: branch.upstream.missing,
367
- remote: branch.upstream.remote,
368
- remoteBranch: branch.upstream.remoteBranch,
369
- local: branch.upstream.local
370
- } : void 0,
371
- sha: branch.sha
372
- });
373
- this.cache.setCurrentBranchReferenceIfAbsent(branch.worktree.path, reference);
374
- }
375
- return branches.length ? { values: branches } : emptyPagedResult;
376
- } catch (_) {
377
- _usingCtx$1.e = _;
378
- } finally {
379
- _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
+ ]);
380
438
  }
381
- } catch (ex) {
382
- cacheable?.invalidate();
383
- if (isCancellationError(ex)) throw ex;
384
- 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();
385
463
  }
386
- };
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();
387
473
  const mapBranches = async (shared, targetRepoPath, commonPath, mapperSignal) => {
388
474
  if (!shared.values.length) return shared;
389
475
  mapperSignal ??= cancellation;
390
- const [currentRefResult, defaultWorktreePathResult] = await Promise.allSettled([this.getCurrentBranchReferenceCore(targetRepoPath, void 0, mapperSignal), this.provider.config.getDefaultWorktreePath?.(commonPath)]);
391
- const currentRef = getSettledValue(currentRefResult);
392
- const defaultWorktreePath = getSettledValue(defaultWorktreePathResult);
393
- const isDetached = currentRef != null && isDetachedHead(currentRef.name);
476
+ const { currentRef, defaultWorktreePath, isDetached } = await this.getCurrentRefAndDefaultWorktreePath(targetRepoPath, commonPath, mapperSignal);
394
477
  const branches = shared.values.map((b) => {
395
- const isCurrent = !b.remote && b.name === currentRef?.name && !isDetached;
396
- if (!isCurrent && targetRepoPath === commonPath) return b;
397
- return new GitBranch(targetRepoPath, b.refName, isCurrent, b.date, b.metadata, b.sha, b.upstream, isCurrent ? b.worktree ?? {
398
- path: targetRepoPath,
399
- isDefault: targetRepoPath === defaultWorktreePath
400
- } : b.worktree, false, false);
478
+ return mapSharedBranch(b, targetRepoPath, commonPath, !b.remote && b.name === currentRef?.name && !isDetached, defaultWorktreePath, true);
401
479
  });
402
480
  if (isDetached || currentRef != null && !branches.some((b) => b.current)) {
403
481
  const metadataMap = await this.getBranchMetadataMap(commonPath);
@@ -416,8 +494,8 @@ var BranchesGitSubProvider = class {
416
494
  let result;
417
495
  if (options?.paging?.cursor != null) {
418
496
  const commonPath = this.cache.getCommonPath(repoPath);
419
- result = await mapBranches(await getCore(commonPath), repoPath, commonPath);
420
- } 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);
421
499
  if (options?.filter != null) result = {
422
500
  ...result,
423
501
  values: result.values.filter(options.filter)