sailfork / t3code-github / packages/ shared/ src/ git.ts

import type {
  BranchNamingOptions,
  VcsRef,
  VcsStatusLocalResult,
  VcsStatusRemoteResult,
  VcsStatusResult,
  VcsStatusStreamEvent,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Result from "effect/Result";

export const WORKTREE_BRANCH_PREFIX = "t3";
const TEMP_WORKTREE_HEX_TOKEN = "[0-9a-f]{8}";
const TEMP_WORKTREE_UUID_V4_TOKEN =
  "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(
  `^(?:${WORKTREE_BRANCH_PREFIX}[-/]${TEMP_WORKTREE_HEX_TOKEN}|t3code(?:[-/]${TEMP_WORKTREE_HEX_TOKEN}|\\/${TEMP_WORKTREE_UUID_V4_TOKEN}))

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	packages/shared/src/git.ts at main · sailfork/t3code-github · Sailfork
	
		
, ); export function sanitizeBranchFragment(raw: string): string { const normalized = raw .normalize("NFKD") .replace(/[̀-ͯ]/g, "") .trim() .toLowerCase() .replace(/['"`]/g, "") .replace(/^[./\s_-]+|[./\s_-]+$/g, ""); const branchFragment = normalized .replace(/[^a-z0-9/_-]+/g, "-") .replace(/\/+/g, "/") .replace(/-+/g, "-") .replace(/^[./_-]+|[./_-]+$/g, "") .slice(0, 64) .replace(/[./_-]+$/g, ""); return branchFragment.length > 0 ? branchFragment : "update"; } export function formatGeneratedBranchName(raw: string, naming?: BranchNamingOptions): string { if (naming?.mode === "custom") return raw.trim(); const branch = sanitizeBranchFragment(raw); if (naming?.mode !== "static") return branch; const prefix = naming.prefix .split("/") .map((part) => part .replace(/[^a-zA-Z0-9_-]+/g, "-") .replace(/-+/g, "-") .replace(/^-+|-+$/g, ""), ) .filter(Boolean) .join("/"); return prefix ? `${prefix}/${branch}` : branch; } export function sanitizeFeatureBranchName(raw: string): string { const sanitized = sanitizeBranchFragment(raw); return sanitized.includes("/") ? sanitized : `feature/${sanitized}`; } const AUTO_FEATURE_BRANCH_FALLBACK = "feature/update"; export function resolveAutoFeatureBranchName( existingBranchNames: readonly string[], preferredBranch?: string, ): string { const preferred = preferredBranch?.trim(); const resolvedBase = sanitizeFeatureBranchName( preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK, ); const existingNames = existingBranchNames.map((refName) => refName.toLowerCase()); const existingRefs = new Set(existingNames); const parts = resolvedBase.split("/"); let resolved = ""; for (const [index, part] of parts.entries()) { const base = resolved ? `${resolved}/${part}` : part; let candidate = base; let suffix = 2; while ( existingRefs.has(candidate) || (index === parts.length - 1 && existingNames.some((refName) => refName.startsWith(`${candidate}/`))) ) { candidate = `${base}-${suffix}`; suffix += 1; } resolved = candidate; } return resolved; } export function deriveLocalBranchNameFromRemoteRef(branchName: string): string { const firstSeparatorIndex = branchName.indexOf("/"); if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) { return branchName; } return branchName.slice(firstSeparatorIndex + 1); } export function buildTemporaryWorktreeBranchName( randomHex: (byteLength: number) => string, ): string { const token = randomHex(4) .toLowerCase() .replace(/[^0-9a-f]/g, "") .slice(0, 8); return `${WORKTREE_BRANCH_PREFIX}/${token}`; } /** Flatten temporary t3/<hex> refs because an existing t3 branch blocks nested refs. */ export function flattenTemporaryWorktreeBranchName(refName: string): string { const normalized = refName.trim().toLowerCase(); const tokenStart = normalized.search(/[-/]/) + 1; const token = normalized.slice(tokenStart, tokenStart + 8); return `${WORKTREE_BRANCH_PREFIX}-${token}`; } export function isTemporaryWorktreeBranch(refName: string): boolean { return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase()); } function lowerCaseRemote(value: string): string { return value .trim() .replace(/\/+$/g, "") .replace(/\.git$/i, "") .toLowerCase(); } /** * The host and repository path a remote names, lower case and without a port, or null for a * remote that names no host, such as a local path. */ export function parseGitRemoteRepository( value: string, ): { readonly host: string; readonly path: string } | null { const normalized = lowerCaseRemote(value); if (/^(?:ssh|https?|git):\/\//i.test(normalized)) { try { const url = new URL(normalized); const repositorySegments = url.pathname.split("/").filter((segment) => segment.length > 0); if (url.hostname && repositorySegments.length > 1) { return { host: url.hostname, path: repositorySegments.join("/") }; } } catch { return null; } } // A userless one-letter prefix is a Windows drive, not an SCP host. const scpStyleHostAndPath = /^[a-z]:/i.test(normalized) ? null : /^(?:[a-zA-Z0-9._-]+@)?([^@:/\\\s]+):\/?([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized); const scpHost = scpStyleHostAndPath?.[1]; const scpPath = scpStyleHostAndPath?.[2]; return scpHost && scpPath ? { host: scpHost, path: scpPath } : null; } /** * `host/path` for a remote that names a host, otherwise the remote itself, lower case. A host that * spells repositories differently over SSH has its source control registry's * `repositoryKeyFromRemote` rewrite this, so persisted keys come from that, not from here. */ export function normalizeGitRemoteUrl(value: string): string { const repository = parseGitRemoteRepository(value); return repository === null ? lowerCaseRemote(value) : `${repository.host}/${repository.path}`; } function* gitConfigLines(configText: string) { let pending = ""; let quoted = false; for (const line of configText.split(/\r?\n/)) { let continued = false; if (line.endsWith("\\") || pending.length > 0) { for (const [token] of line.matchAll(/\\[\s\S]?|["#;]/g)) { if (token === '"') quoted = !quoted; else if (!quoted && (token === "#" || token === ";")) break; else if (token === "\\") continued = true; } } if (continued) { pending += line.slice(0, -1); continue; } if (!quoted) yield pending + line; pending = ""; quoted = false; } if (pending.length > 0 && !quoted) yield pending; } function parseGitConfigValue(raw: string): string { let out = ""; let quoted = false; for (let index = 0; index < raw.length; index += 1) { const char = raw[index]!; if (char === "\\" && index + 1 < raw.length) { out += raw[index + 1]; index += 1; continue; } if (char === '"') { quoted = !quoted; continue; } if (!quoted && (char === "#" || char === ";")) break; out += char; } return out.trim(); } function isTrueGitConfigValue(value: string): boolean { if (value === "true" || value === "yes" || value === "on") return true; const numeric = /^([+-]?)(0x[0-9a-f]+|0[0-7]*|[1-9][0-9]*)([kmg]?)$/.exec(value); if (numeric === null) return false; const digits = numeric[2]!; const magnitude = digits.startsWith("0x") ? Number.parseInt(digits.slice(2), 16) : Number.parseInt(digits, digits.startsWith("0") ? 8 : 10); const scale = numeric[3] === "k" ? 1024 : numeric[3] === "m" ? 1024 ** 2 : numeric[3] === "g" ? 1024 ** 3 : 1; const number = magnitude * scale * (numeric[1] === "-" ? -1 : 1); // Git's boolean parser accepts integers only within its signed 32-bit range. return number !== 0 && number >= -2147483648 && number <= 2147483647; } export function isBareGitConfig(configText: string): boolean { let inCore = false; let bare = false; for (const rawLine of gitConfigLines(configText)) { let line = rawLine.trim(); // Git accepts the first setting on the section header's own line. const header = /^\[\s*([^\]]*?)\s*\](.*)$/.exec(line); if (header !== null) { inCore = header[1]!.toLowerCase() === "core"; line = header[2]!.trim(); } if (!inCore) continue; const match = /^bare\s*(?:=(.*)|[#;].*)?$/i.exec(line); if (match === null) continue; const value = match[1] === undefined ? "true" : parseGitConfigValue(match[1]).toLowerCase(); bare = isTrueGitConfigValue(value); } return bare; } export function parseOriginUrlFromGitConfig(configText: string): string | null { let section: string | null = null; let originUrl: string | null = null; let firstRemoteUrl: string | null = null; const joined = configText.replace(/\\\r?\n[ \t]*/g, ""); for (const rawLine of joined.split(/\r?\n/)) { let line = rawLine.trim(); if (line.length === 0 || line.startsWith("#") || line.startsWith(";")) continue; // Git preserves case in quoted remote subsections but lowercases legacy dotted ones, // and accepts the first setting on the section header's own line. const header = /^\[\s*remote(?:\s+"([^"]+)"|\.([^\]\s]+))\s*\](.*)$/i.exec(line); if (header) { section = header[1] ?? header[2]?.toLowerCase() ?? null; line = header[3]!.trim(); } else if (line.startsWith("[")) { section = null; continue; } if (section === null) continue; const match = /^url\s*=\s*(.*)$/i.exec(line); if (!match) continue; const url = parseGitConfigValue(match[1] ?? ""); if (url.length === 0) continue; if (section === "origin") { originUrl ??= url; } else { firstRemoteUrl ??= url; } } return originUrl ?? firstRemoteUrl; } function deriveLocalBranchNameCandidatesFromRemoteRef( branchName: string, remoteName?: string, ): ReadonlyArray<string> { const candidates = new Set<string>(); const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName); if (firstSlashCandidate.length > 0) { candidates.add(firstSlashCandidate); } if (remoteName) { const remotePrefix = `${remoteName}/`; if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) { candidates.add(branchName.slice(remotePrefix.length)); } } return [...candidates]; } // Replace only Git-rejected whitespace; nonbreaking spaces are valid ref characters. export function sanitizeNewRefName(rawName: string): string { return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-"); } export function dedupeRemoteBranchesWithLocalMatches( refs: ReadonlyArray<VcsRef>, ): ReadonlyArray<VcsRef> { const localBranchNames = new Set( Arr.filterMap(refs, (refName) => refName.isRemote ? Result.failVoid : Result.succeed(refName.name), ), ); return refs.filter((refName) => { if (!refName.isRemote) { return true; } if (refName.remoteName !== "origin") { return true; } const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef( refName.name, refName.remoteName, ); return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate)); }); } const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = { hasUpstream: false, aheadCount: 0, behindCount: 0, aheadOfDefaultCount: 0, pr: null, }; export function mergeGitStatusParts( local: VcsStatusLocalResult, remote: VcsStatusRemoteResult | null, ): VcsStatusResult { return { ...local, ...(remote ?? EMPTY_GIT_STATUS_REMOTE), }; } function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult { return { hasUpstream: status.hasUpstream, aheadCount: status.aheadCount, behindCount: status.behindCount, ...(status.aheadOfDefaultCount === undefined ? {} : { aheadOfDefaultCount: status.aheadOfDefaultCount }), pr: status.pr, }; } function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult { return { isRepo: status.isRepo, ...(status.sourceControlProvider ? { sourceControlProvider: status.sourceControlProvider } : {}), hasPrimaryRemote: status.hasPrimaryRemote, isDefaultRef: status.isDefaultRef, refName: status.refName, hasWorkingTreeChanges: status.hasWorkingTreeChanges, workingTree: status.workingTree, ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}), }; } export function applyGitStatusStreamEvent( current: VcsStatusResult | null, event: VcsStatusStreamEvent, ): VcsStatusResult { switch (event._tag) { case "snapshot": return mergeGitStatusParts(event.local, event.remote); case "localUpdated": return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null); case "remoteUpdated": if (current === null) { return mergeGitStatusParts( { isRepo: true, hasPrimaryRemote: false, isDefaultRef: false, refName: null, hasWorkingTreeChanges: false, workingTree: { files: [], insertions: 0, deletions: 0 }, }, event.remote, ); } return mergeGitStatusParts(toLocalStatusPart(current), event.remote); } }
packages/shared/src/git.ts at main · sailfork/t3code-github · Sailfork
,\n);\n\nexport function sanitizeBranchFragment(raw: string): string {\n const normalized = raw\n .normalize(\"NFKD\")\n .replace(/[̀-ͯ]/g, \"\")\n .trim()\n .toLowerCase()\n .replace(/['\"`]/g, \"\")\n .replace(/^[./\\s_-]+|[./\\s_-]+$/g, \"\");\n\n const branchFragment = normalized\n .replace(/[^a-z0-9/_-]+/g, \"-\")\n .replace(/\\/+/g, \"/\")\n .replace(/-+/g, \"-\")\n .replace(/^[./_-]+|[./_-]+$/g, \"\")\n .slice(0, 64)\n .replace(/[./_-]+$/g, \"\");\n\n return branchFragment.length > 0 ? branchFragment : \"update\";\n}\n\nexport function formatGeneratedBranchName(raw: string, naming?: BranchNamingOptions): string {\n if (naming?.mode === \"custom\") return raw.trim();\n const branch = sanitizeBranchFragment(raw);\n if (naming?.mode !== \"static\") return branch;\n const prefix = naming.prefix\n .split(\"/\")\n .map((part) =>\n part\n .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-+|-+$/g, \"\"),\n )\n .filter(Boolean)\n .join(\"/\");\n return prefix ? `${prefix}/${branch}` : branch;\n}\n\nexport function sanitizeFeatureBranchName(raw: string): string {\n const sanitized = sanitizeBranchFragment(raw);\n return sanitized.includes(\"/\") ? sanitized : `feature/${sanitized}`;\n}\n\nconst AUTO_FEATURE_BRANCH_FALLBACK = \"feature/update\";\n\nexport function resolveAutoFeatureBranchName(\n existingBranchNames: readonly string[],\n preferredBranch?: string,\n): string {\n const preferred = preferredBranch?.trim();\n const resolvedBase = sanitizeFeatureBranchName(\n preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,\n );\n const existingNames = existingBranchNames.map((refName) => refName.toLowerCase());\n const existingRefs = new Set(existingNames);\n const parts = resolvedBase.split(\"/\");\n let resolved = \"\";\n\n for (const [index, part] of parts.entries()) {\n const base = resolved ? `${resolved}/${part}` : part;\n let candidate = base;\n let suffix = 2;\n while (\n existingRefs.has(candidate) ||\n (index === parts.length - 1 &&\n existingNames.some((refName) => refName.startsWith(`${candidate}/`)))\n ) {\n candidate = `${base}-${suffix}`;\n suffix += 1;\n }\n resolved = candidate;\n }\n\n return resolved;\n}\n\nexport function deriveLocalBranchNameFromRemoteRef(branchName: string): string {\n const firstSeparatorIndex = branchName.indexOf(\"/\");\n if (firstSeparatorIndex \u003c= 0 || firstSeparatorIndex === branchName.length - 1) {\n return branchName;\n }\n return branchName.slice(firstSeparatorIndex + 1);\n}\n\nexport function buildTemporaryWorktreeBranchName(\n randomHex: (byteLength: number) => string,\n): string {\n const token = randomHex(4)\n .toLowerCase()\n .replace(/[^0-9a-f]/g, \"\")\n .slice(0, 8);\n return `${WORKTREE_BRANCH_PREFIX}/${token}`;\n}\n\n/** Flatten temporary t3/\u003chex> refs because an existing t3 branch blocks nested refs. */\nexport function flattenTemporaryWorktreeBranchName(refName: string): string {\n const normalized = refName.trim().toLowerCase();\n const tokenStart = normalized.search(/[-/]/) + 1;\n const token = normalized.slice(tokenStart, tokenStart + 8);\n return `${WORKTREE_BRANCH_PREFIX}-${token}`;\n}\n\nexport function isTemporaryWorktreeBranch(refName: string): boolean {\n return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());\n}\n\nfunction lowerCaseRemote(value: string): string {\n return value\n .trim()\n .replace(/\\/+$/g, \"\")\n .replace(/\\.git$/i, \"\")\n .toLowerCase();\n}\n\n/**\n * The host and repository path a remote names, lower case and without a port, or null for a\n * remote that names no host, such as a local path.\n */\nexport function parseGitRemoteRepository(\n value: string,\n): { readonly host: string; readonly path: string } | null {\n const normalized = lowerCaseRemote(value);\n\n if (/^(?:ssh|https?|git):\\/\\//i.test(normalized)) {\n try {\n const url = new URL(normalized);\n const repositorySegments = url.pathname.split(\"/\").filter((segment) => segment.length > 0);\n if (url.hostname && repositorySegments.length > 1) {\n return { host: url.hostname, path: repositorySegments.join(\"/\") };\n }\n } catch {\n return null;\n }\n }\n\n // A userless one-letter prefix is a Windows drive, not an SCP host.\n const scpStyleHostAndPath = /^[a-z]:/i.test(normalized)\n ? null\n : /^(?:[a-zA-Z0-9._-]+@)?([^@:/\\\\\\s]+):\\/?([^/\\s]+(?:\\/[^/\\s]+)+)$/i.exec(normalized);\n const scpHost = scpStyleHostAndPath?.[1];\n const scpPath = scpStyleHostAndPath?.[2];\n return scpHost && scpPath ? { host: scpHost, path: scpPath } : null;\n}\n\n/**\n * `host/path` for a remote that names a host, otherwise the remote itself, lower case. A host that\n * spells repositories differently over SSH has its source control registry's\n * `repositoryKeyFromRemote` rewrite this, so persisted keys come from that, not from here.\n */\nexport function normalizeGitRemoteUrl(value: string): string {\n const repository = parseGitRemoteRepository(value);\n return repository === null ? lowerCaseRemote(value) : `${repository.host}/${repository.path}`;\n}\n\nfunction* gitConfigLines(configText: string) {\n let pending = \"\";\n let quoted = false;\n for (const line of configText.split(/\\r?\\n/)) {\n let continued = false;\n if (line.endsWith(\"\\\\\") || pending.length > 0) {\n for (const [token] of line.matchAll(/\\\\[\\s\\S]?|[\"#;]/g)) {\n if (token === '\"') quoted = !quoted;\n else if (!quoted && (token === \"#\" || token === \";\")) break;\n else if (token === \"\\\\\") continued = true;\n }\n }\n if (continued) {\n pending += line.slice(0, -1);\n continue;\n }\n if (!quoted) yield pending + line;\n pending = \"\";\n quoted = false;\n }\n if (pending.length > 0 && !quoted) yield pending;\n}\n\nfunction parseGitConfigValue(raw: string): string {\n let out = \"\";\n let quoted = false;\n for (let index = 0; index \u003c raw.length; index += 1) {\n const char = raw[index]!;\n if (char === \"\\\\\" && index + 1 \u003c raw.length) {\n out += raw[index + 1];\n index += 1;\n continue;\n }\n if (char === '\"') {\n quoted = !quoted;\n continue;\n }\n if (!quoted && (char === \"#\" || char === \";\")) break;\n out += char;\n }\n return out.trim();\n}\n\nfunction isTrueGitConfigValue(value: string): boolean {\n if (value === \"true\" || value === \"yes\" || value === \"on\") return true;\n const numeric = /^([+-]?)(0x[0-9a-f]+|0[0-7]*|[1-9][0-9]*)([kmg]?)$/.exec(value);\n if (numeric === null) return false;\n const digits = numeric[2]!;\n const magnitude = digits.startsWith(\"0x\")\n ? Number.parseInt(digits.slice(2), 16)\n : Number.parseInt(digits, digits.startsWith(\"0\") ? 8 : 10);\n const scale =\n numeric[3] === \"k\" ? 1024 : numeric[3] === \"m\" ? 1024 ** 2 : numeric[3] === \"g\" ? 1024 ** 3 : 1;\n const number = magnitude * scale * (numeric[1] === \"-\" ? -1 : 1);\n // Git's boolean parser accepts integers only within its signed 32-bit range.\n return number !== 0 && number >= -2147483648 && number \u003c= 2147483647;\n}\n\nexport function isBareGitConfig(configText: string): boolean {\n let inCore = false;\n let bare = false;\n for (const rawLine of gitConfigLines(configText)) {\n let line = rawLine.trim();\n // Git accepts the first setting on the section header's own line.\n const header = /^\\[\\s*([^\\]]*?)\\s*\\](.*)$/.exec(line);\n if (header !== null) {\n inCore = header[1]!.toLowerCase() === \"core\";\n line = header[2]!.trim();\n }\n if (!inCore) continue;\n const match = /^bare\\s*(?:=(.*)|[#;].*)?$/i.exec(line);\n if (match === null) continue;\n const value = match[1] === undefined ? \"true\" : parseGitConfigValue(match[1]).toLowerCase();\n bare = isTrueGitConfigValue(value);\n }\n return bare;\n}\n\nexport function parseOriginUrlFromGitConfig(configText: string): string | null {\n let section: string | null = null;\n let originUrl: string | null = null;\n let firstRemoteUrl: string | null = null;\n const joined = configText.replace(/\\\\\\r?\\n[ \\t]*/g, \"\");\n for (const rawLine of joined.split(/\\r?\\n/)) {\n let line = rawLine.trim();\n if (line.length === 0 || line.startsWith(\"#\") || line.startsWith(\";\")) continue;\n // Git preserves case in quoted remote subsections but lowercases legacy dotted ones,\n // and accepts the first setting on the section header's own line.\n const header = /^\\[\\s*remote(?:\\s+\"([^\"]+)\"|\\.([^\\]\\s]+))\\s*\\](.*)$/i.exec(line);\n if (header) {\n section = header[1] ?? header[2]?.toLowerCase() ?? null;\n line = header[3]!.trim();\n } else if (line.startsWith(\"[\")) {\n section = null;\n continue;\n }\n if (section === null) continue;\n const match = /^url\\s*=\\s*(.*)$/i.exec(line);\n if (!match) continue;\n const url = parseGitConfigValue(match[1] ?? \"\");\n if (url.length === 0) continue;\n if (section === \"origin\") {\n originUrl ??= url;\n } else {\n firstRemoteUrl ??= url;\n }\n }\n return originUrl ?? firstRemoteUrl;\n}\n\nfunction deriveLocalBranchNameCandidatesFromRemoteRef(\n branchName: string,\n remoteName?: string,\n): ReadonlyArray\u003cstring> {\n const candidates = new Set\u003cstring>();\n const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);\n if (firstSlashCandidate.length > 0) {\n candidates.add(firstSlashCandidate);\n }\n\n if (remoteName) {\n const remotePrefix = `${remoteName}/`;\n if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {\n candidates.add(branchName.slice(remotePrefix.length));\n }\n }\n\n return [...candidates];\n}\n\n// Replace only Git-rejected whitespace; nonbreaking spaces are valid ref characters.\nexport function sanitizeNewRefName(rawName: string): string {\n return rawName.trim().replace(/[ \\t\\n\\r\\f\\v]+/g, \"-\");\n}\n\nexport function dedupeRemoteBranchesWithLocalMatches(\n refs: ReadonlyArray\u003cVcsRef>,\n): ReadonlyArray\u003cVcsRef> {\n const localBranchNames = new Set(\n Arr.filterMap(refs, (refName) =>\n refName.isRemote ? Result.failVoid : Result.succeed(refName.name),\n ),\n );\n\n return refs.filter((refName) => {\n if (!refName.isRemote) {\n return true;\n }\n\n if (refName.remoteName !== \"origin\") {\n return true;\n }\n\n const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(\n refName.name,\n refName.remoteName,\n );\n return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));\n });\n}\n\nconst EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {\n hasUpstream: false,\n aheadCount: 0,\n behindCount: 0,\n aheadOfDefaultCount: 0,\n pr: null,\n};\n\nexport function mergeGitStatusParts(\n local: VcsStatusLocalResult,\n remote: VcsStatusRemoteResult | null,\n): VcsStatusResult {\n return {\n ...local,\n ...(remote ?? EMPTY_GIT_STATUS_REMOTE),\n };\n}\n\nfunction toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {\n return {\n hasUpstream: status.hasUpstream,\n aheadCount: status.aheadCount,\n behindCount: status.behindCount,\n ...(status.aheadOfDefaultCount === undefined\n ? {}\n : { aheadOfDefaultCount: status.aheadOfDefaultCount }),\n pr: status.pr,\n };\n}\n\nfunction toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {\n return {\n isRepo: status.isRepo,\n ...(status.sourceControlProvider\n ? { sourceControlProvider: status.sourceControlProvider }\n : {}),\n hasPrimaryRemote: status.hasPrimaryRemote,\n isDefaultRef: status.isDefaultRef,\n refName: status.refName,\n hasWorkingTreeChanges: status.hasWorkingTreeChanges,\n workingTree: status.workingTree,\n ...(status.branchChanges ? { branchChanges: status.branchChanges } : {}),\n };\n}\n\nexport function applyGitStatusStreamEvent(\n current: VcsStatusResult | null,\n event: VcsStatusStreamEvent,\n): VcsStatusResult {\n switch (event._tag) {\n case \"snapshot\":\n return mergeGitStatusParts(event.local, event.remote);\n case \"localUpdated\":\n return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);\n case \"remoteUpdated\":\n if (current === null) {\n return mergeGitStatusParts(\n {\n isRepo: true,\n hasPrimaryRemote: false,\n isDefaultRef: false,\n refName: null,\n hasWorkingTreeChanges: false,\n workingTree: { files: [], insertions: 0, deletions: 0 },\n },\n event.remote,\n );\n }\n return mergeGitStatusParts(toLocalStatusPart(current), event.remote);\n }\n}\n","preview":null,"history":null,"version":"e03bd125a4a2ca8516edc5a3e1c1635222b236e4"},"/_session?shell=1":null}