From ea770cc2e15b6d290b8be6cf03e54d12b773d7e4 Mon Sep 17 00:00:00 2001 From: Sidebar Test Date: Thu, 5 Nov 2026 18:52:27 +0800 Subject: [PATCH] feat(git): a labeled repository picker for multi-repo workspaces MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A container workspace that discovers several repositories rendered one chip per root above the Changes section; with location labels the row does not scale, and same-named checkouts were indistinguishable. The row is now a compact labeled select: the current root stays on screen, the full list is one click away, and options carry disambiguation labels (deeper roots show their relative parent) shared with the More -> Repository submenu. The picker shows the resolved status root — a server fallback renders as a disabled stand-in with its own short label instead of silently selecting the first option. Single-repo workspaces render no row; switching still goes through chooseRepo. --- CHANGELOG.md | 3 + CHANGELOG_EN.md | 3 + src/client/changes/GitLens.tsx | 65 +++++-- src/client/changes/changes.module.css | 47 +++-- src/client/changes/repo-labels.ts | 168 ++++++++++++++++++ tests/git-repo-labels.spec.ts | 247 ++++++++++++++++++++++++++ tests/git-repo-switcher.spec.tsx | 129 +++++++++----- 7 files changed, 577 insertions(+), 85 deletions(-) create mode 100644 src/client/changes/repo-labels.ts create mode 100644 tests/git-repo-labels.spec.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7aa7dbcb..a55f4ac4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -156,6 +156,9 @@ ### v0.30.1 +- 🌿 **Git 面板新增「仓库 ▾」下拉,同名仓库一眼可辨**:容器工作区发现多个仓库时,顶部显示紧凑的「仓库 [当前仓库 ▾]」下拉——当前选中的仓库始终可见,完整列表一键展开,仓库再多也只占一行。选项使用位置消歧标签:深层仓库显示 `名 (相对父路径)`(如 `knowhow (ob-harness/contexts)`),同名可辨,极端冲突用完整路径兜底;「更多操作 → 仓库」菜单共用同一份标签。若服务端把所选仓库回退到其他根,下拉会以禁用项如实显示实际根,不冒充候选。单仓库工作区不显示此行;切换仍走既有 `chooseRepo`,读数、写操作与提交图继续钉在选中的根上。 + - 🧪 测试:`tests/git-repo-labels.spec.ts`(32 例:路径方言、同名消歧、顺序与输入不变)与 `tests/git-repo-switcher.spec.tsx`(下拉选项与标签、菜单同标签、拼写折叠、服务端回退的禁用临时项、单仓不显示)。 + - 🎯 **设置页「侧边卡片」的导航图标不再叠成两个**:插件此前按"宿主设置导航还没有图标通道"的老假设,用 CSS 把兜底齿轮藏起来、再画自己的图标;宿主早已提供按 section id 寻址的 `settings.section.icon` 插槽,而且图标的 DOM 外面多了一层 span,老选择器失效后兜底 SVG 露了出来,与插件图标并排显示。现在改为**走宿主插槽**提供图标,删掉标记 + CSS 遮罩那一套(顺带去掉了一个监听整个 document 的 MutationObserver)。 - 🧪 测试:`tests/settings-nav-icon.spec.tsx` 钉住图标按宿主给的 `size` 缩放、只用 `currentColor`;真实宿主上用无头浏览器确认导航行只剩一个 `svg`、无残留标记。 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index 68935f26..ad24f047 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -152,6 +152,9 @@ ### v0.30.1 +- 🌿 **A labeled "Repository" dropdown for multi-repo workspaces, with same-named checkouts tellable apart**: when a container workspace discovers several repositories, the panel now shows a compact `Repository [current ▾]` select — the current root stays on screen and the full list is one click away, one line however many roots discovery finds. Options carry location labels: deeper repositories show `name (relative/parent)` (e.g. `knowhow (ob-harness/contexts)`), so same-named checkouts are distinguishable, and extreme collisions fall back to full paths; the ⋯ → Repository submenu shares the same list. If the server fell back from the requested root, the picker displays the actual root as a disabled stand-in instead of masquerading as a candidate. Single-repository workspaces render no row; switching still goes through the existing `chooseRepo`, so reads, mutations and the commit graph stay pinned to the chosen root. + - 🧪 `tests/git-repo-labels.spec.ts` (32 cases: path dialects, duplicate disambiguation, order and input immutability) and `tests/git-repo-switcher.spec.tsx` (picker options and labels, shared menu labels, spelling folding, the server-fallback disabled stand-in, single-repo absence). + - 🎯 **The "Side card" settings row no longer shows two icons**: the plugin still assumed the settings navigation had no icon channel, so it hid the fallback gear with CSS and painted its own glyph. The shell has long since exposed a `settings.section.icon` slot addressed by section id, and it now wraps the nav icon in a span — the stale `> svg:first-child` rule stopped hiding the fallback, so both glyphs rendered side by side. The row now contributes its icon **through the slot**, and the marker + CSS-mask apparatus is gone (along with a document-wide MutationObserver). - 🧪 `tests/settings-nav-icon.spec.tsx` pins the glyph to the slot-provided `size` and `currentColor`; a headless pass against a real host confirms one `svg` in the row and no leftover marker. diff --git a/src/client/changes/GitLens.tsx b/src/client/changes/GitLens.tsx index eeba9809..e03eca7f 100644 --- a/src/client/changes/GitLens.tsx +++ b/src/client/changes/GitLens.tsx @@ -24,6 +24,7 @@ import { resolveSidebarPath } from '../paths.ts' import { isZh, t } from '../locales.ts' import { GitGraphSection, type GraphDetailsSelection } from './GitGraphSection.tsx' import type { SidebarDiffRef } from '../state.ts' +import { buildRepositoryLabels } from './repo-labels.ts' import { ConfirmDialog, IconButton, Notice, StatusBadge, invalidateGitStatus, statusOfXY, useGitStatus, type GitFileStatus, type GitTone, type StatusTone, @@ -67,6 +68,19 @@ function errorMessage(reason: unknown): string { return reason instanceof Error ? reason.message : String(reason) } +/** Existing Host fact used only to disambiguate ambiguous path spellings (a + * leading `//` is either POSIX or Windows UNC). Read through the guarded + * face; never rendered and never requested. */ +function hostHomeOf(ctx: Context | undefined): string | undefined { + try { + const remote = ctx?.get('remote') as { $host?: { home?: unknown } } | undefined + return typeof remote?.$host?.home === 'string' ? remote.$host.home : undefined + } catch { + // A composition without the Remote service must not take the lens down. + return undefined + } +} + /** One checkout root in the form comparisons use: `git rev-parse` reports * forward slashes, React state may carry the shell's backslashes, Windows * folds case, and a trailing separator means the same directory. @@ -556,6 +570,25 @@ export function GitLens(props: GitLensProps) { if (lastStatus.current.key !== statusKey) lastStatus.current = { key: statusKey, value: null } if (status.snapshot !== null) lastStatus.current.value = status.snapshot const snapshot: GitStatusResult | null = status.snapshot ?? lastStatus.current.value + // Display-only labels for the picker and the ⋯ → Repository menu. The + // reference is the session's existing cwd (best effort — it can shift with + // the active worktree); `hostHome` only disambiguates `//` dialects and is + // never rendered. + const hostHome = hostHomeOf(ctx) + // A requested repoRoot can disappear from server discovery; the server then + // falls back. Show the RESOLVED status root, never the stale request or an + // arbitrary first option — matched by identity but keeping the option's + // original root, or a disabled stand-in with its own short label. + const actualRoot = snapshot?.root + const selectedCandidate = actualRoot === undefined ? undefined : repoChoices.find(root => sameRepoRoot(root, actualRoot)) + const unlistedRoot = actualRoot !== undefined && selectedCandidate === undefined ? actualRoot : undefined + const allRepositoryLabels = useMemo( + () => buildRepositoryLabels(unlistedRoot === undefined ? repoChoices : [...repoChoices, unlistedRoot], scope.cwd, hostHome), + [repoChoices, unlistedRoot, scope.cwd, hostHome], + ) + const repositoryLabels = unlistedRoot === undefined ? allRepositoryLabels : allRepositoryLabels.slice(0, -1) + const resolvedRepository = selectedCandidate ?? actualRoot + const resolvedRepositoryLabel = unlistedRoot === undefined ? undefined : allRepositoryLabels.at(-1)?.label useEffect(() => { const repositories = snapshot?.repositories if (repositories !== undefined && repositories.length > 1) setRepoChoices(repositories) @@ -1101,24 +1134,24 @@ export function GitLens(props: GitLensProps) { {snapshot?.truncated === true && {t('statusTruncated')}} {/* A container workspace can hold several independent repositories, and - every view below is pinned to ONE of them — without this row the + every view below is pinned to ONE of them — without this picker the panel silently shows the first root, so nothing on screen says the - others exist. The switcher is not a second source of truth: + others exist. The picker is not a second source of truth: `repoChoices` comes from the status snapshot, `chooseRepo` re-pins - the scope (reads, writes, graph) to the clicked root. */} + the scope (reads, writes, graph) to the picked root. A labeled + select keeps the current root on screen and the rest one click away + however many repositories discovery finds. */} {isRepo && repoChoices.length > 1 && ( -
- {repoChoices.map(root => { - const isActive = sameRepoRoot(root, repoRoot ?? snapshot?.root) - return ( - - ) - })} -
+ )} {isRepo && ( @@ -1149,7 +1182,7 @@ export function GitLens(props: GitLensProps) { { id: 'pull', label: t('pull'), disabled: busy || suggesting || snapshot?.detached === true }, { id: 'push', label: t('push'), disabled: busy || suggesting || snapshot?.detached === true }, ...(repoChoices.length > 1 ? [{ id: 'repos', label: t('gitRepository'), - submenu: repoChoices.map(root => ({ id: `repo:${root}`, label: baseName(root), disabled: busy || suggesting })), + submenu: repositoryLabels.map(({ root, label }) => ({ id: `repo:${root}`, label, disabled: busy || suggesting })), }] : []), ...(worktrees.length > 1 ? [{ id: 'worktrees', label: t('worktree'), submenu: worktrees.map(entry => ({ id: `worktree:${entry.path}`, diff --git a/src/client/changes/changes.module.css b/src/client/changes/changes.module.css index 6795f9b5..8292a27d 100644 --- a/src/client/changes/changes.module.css +++ b/src/client/changes/changes.module.css @@ -59,46 +59,39 @@ @media (hover: none) { .scmActions { opacity: 1; } } /* Child repositories of a workspace container: every view in this panel is - pinned to ONE root, so the switcher is the only surface that says the others - exist. One band above the sections, one chip per discovered root; it scrolls - sideways rather than wrapping so a deep root list cannot push the changes - away from the top of the pane. */ -.repoSwitcher { + pinned to ONE root, so the picker is the only surface that names the current + one and lists the others one click away. A labeled select scales to any + number of discovered roots in a single compact band — a chip per root does + not, once location labels distinguish same-named checkouts. */ +.repoPick { flex: none; display: flex; align-items: center; - gap: 4px; + gap: 6px; min-width: 0; padding: 0 6px 2px; - overflow-x: auto; - overflow-y: hidden; - scrollbar-width: none; + color: var(--dsw-alias-label-secondary); + font: var(--dsw-font-xxxs-11); + cursor: pointer; } -.repoSwitcher::-webkit-scrollbar { display: none; } -.repoChip { - flex: none; - max-width: 160px; - min-height: 22px; - padding: 2px 8px; +.repoPickLabel { flex: none; white-space: nowrap; } +.repoPickSelect { + flex: 1; + min-width: 0; + max-width: 100%; + height: 22px; + padding: 0 4px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 3px; background: transparent; - color: var(--dsw-alias-label-secondary); + color: var(--dsw-alias-label-primary); font: var(--dsw-font-xxxs-11); - text-align: left; - white-space: nowrap; - overflow: hidden; text-overflow: ellipsis; cursor: pointer; } -.repoChip:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); } -.repoChip[data-active='true'] { - border-color: var(--dsw-alias-border-l2); - background: var(--dsw-alias-interactive-bg-hover-accent); - color: var(--dsw-alias-label-primary); -} -.repoChip:disabled { opacity: 0.45; cursor: default; } -.repoChip:focus-visible { outline: 2px solid var(--dsw-alias-interactive-bg-hover-accent); outline-offset: -2px; } +.repoPickSelect:hover:not(:disabled) { border-color: var(--dsw-alias-border-l2); background: var(--dsw-alias-interactive-bg-hover); } +.repoPickSelect:disabled { opacity: 0.45; cursor: default; } +.repoPickSelect:focus-visible { outline: 2px solid var(--dsw-alias-interactive-bg-hover-accent); outline-offset: -2px; } /* Docked by the flex column above (a sibling of `.gitScroll`), plus sticky so it also survives the case where the host tab body itself scrolls the whole diff --git a/src/client/changes/repo-labels.ts b/src/client/changes/repo-labels.ts new file mode 100644 index 00000000..94c3d939 --- /dev/null +++ b/src/client/changes/repo-labels.ts @@ -0,0 +1,168 @@ +/** Display-only labels for discovered checkout roots. No filesystem or browser-platform access. */ +export interface RepositoryLabel { + readonly root: string + readonly label: string +} + +type PathKind = 'posix' | 'drive' | 'unc' | 'relative' +interface ParsedPath { + kind: PathKind + anchor: string + parts: string[] + separator: '/' | '\\' + name: string + absolute: string + hasParentSegment: boolean +} + +/** Interpret each path in its own host dialect, never in the browser's dialect. */ +function parsePath(raw: string, preferPosixDoubleSlash = false): ParsedPath { + // Windows may hand out namespaced drive or UNC paths. Remove only the + // namespace for comparison/display; the original root remains untouched. + const spelling = preferPosixDoubleSlash && raw.startsWith('/') ? raw + : /^[\\/]{2}\?[\\/]UNC[\\/]/i.test(raw) + ? raw.replace(/^[\\/]{2}\?[\\/]UNC[\\/]/i, '\\\\') + : raw.replace(/^[\\/]{2}\?[\\/](?=[a-zA-Z]:[\\/])/, '') + let kind: PathKind = 'relative' + let anchor = '' + let rest = spelling + let separator: '/' | '\\' = '/' + const drive = /^([a-zA-Z]:)[\\/]+/.exec(spelling) + const unc = /^[\\/]{2}([^\\/]+)[\\/]+([^\\/]+)(?:[\\/]+|$)/.exec(spelling) + if (drive) { + kind = 'drive' + anchor = drive[1]! + rest = spelling.slice(drive[0].length) + separator = '\\' + } else if (unc && !(preferPosixDoubleSlash && spelling.startsWith('/'))) { + kind = 'unc' + anchor = `\\\\${unc[1]!}\\${unc[2]!}` + rest = spelling.slice(unc[0].length) + separator = '\\' + } else if (spelling.startsWith('/')) { + kind = 'posix' + anchor = '/' + rest = spelling.replace(/^\/+/, '') + } + const split = kind === 'posix' || kind === 'relative' ? /\/+/ : /[\\/]+/ + const parts: string[] = [] + for (const part of rest.split(split)) { + if (part && part !== '.') parts.push(part) + } + // Resolving '..' lexically can be wrong across a symlink. With no filesystem + // access, preserve it for display and decline to infer containment. + const hasParentSegment = parts.includes('..') + const name = parts[parts.length - 1] + ?? (kind === 'posix' ? '/' : kind === 'drive' ? `${anchor}\\` : kind === 'unc' ? anchor.split('\\').at(-1)! : raw) + const suffix = parts.join(separator) + const absolute = kind === 'posix' ? `/${suffix}` + : kind === 'drive' ? `${anchor}\\${suffix}` + : kind === 'unc' ? `${anchor}${suffix ? `\\${suffix}` : ''}` + : suffix || raw + return { kind, anchor, parts, separator, name, absolute, hasParentSegment } +} + +/** Check full path components and drive/share identity; POSIX paths stay case-sensitive. */ +function relativeParts(path: ParsedPath, base: ParsedPath | undefined): string[] | undefined { + if (!base || base.kind === 'relative' || path.kind !== base.kind || base.hasParentSegment || path.hasParentSegment) return undefined + const windows = path.kind === 'drive' || path.kind === 'unc' + const same = (left: string, right: string) => windows ? left.toLowerCase() === right.toLowerCase() : left === right + if (!same(path.anchor, base.anchor) || path.parts.length < base.parts.length) return undefined + if (!base.parts.every((part, i) => same(part, path.parts[i]!))) return undefined + return path.parts.slice(base.parts.length) +} + +interface LabelCandidate { + root: string + parsed: ParsedPath + parents: string[] + context: string | undefined + nextDepth: number + phase: 0 | 1 | 2 + label: string +} + +/** Build a longer label only when a collision actually needs it. */ +function advanceLabel(candidate: LabelCandidate): boolean { + const { parsed, parents } = candidate + if (candidate.nextDepth <= parents.length) { + const part = parents[parents.length - candidate.nextDepth]! + candidate.context = candidate.context === undefined ? part : `${part}${parsed.separator}${candidate.context}` + candidate.nextDepth += 1 + candidate.label = `${parsed.name} (${candidate.context})` + return true + } + if (candidate.phase === 0) { + candidate.phase = 1 + candidate.label = `${parsed.name} (${parsed.absolute})` + return true + } + if (candidate.phase === 1) { + candidate.phase = 2 + candidate.label = candidate.root + return true + } + return false +} + +/** + * Build labels once for the complete list. Short names cover the base, its + * direct children and an unknown base; deeper paths expose their full relative + * parent. Roots outside a known base show short parent context. Collisions + * expand context up to absolute/raw paths, never numbers. Exact duplicate roots + * share a label and keep their original rows. + */ +export function buildRepositoryLabels( + roots: readonly string[], + displayCwd: string | undefined, + hostHome?: string, +): readonly RepositoryLabel[] { + // The host's existing home is only a dialect hint; it is never appended to a label. + // A forward-slash UNC home is itself ambiguous, so do not claim a dialect. + const homePosix = hostHome !== undefined && hostHome.startsWith('/') && !hostHome.startsWith('//') && !hostHome.startsWith('/\\') + const homeWindows = hostHome !== undefined && (/^[a-zA-Z]:[\\/]/.test(hostHome) || /^\\[\\/]/.test(hostHome)) + // Without a host hint, a // base is ambiguous. Preserve its spelling and + // use case-sensitive comparison rather than silently asserting UNC semantics. + const ambiguousBase = !homePosix && !homeWindows + && (displayCwd?.startsWith('//') === true || displayCwd?.startsWith('/\\') === true) + const base = displayCwd === undefined ? undefined : parsePath(displayCwd, homePosix || ambiguousBase) + const preferPosix = homePosix || (!homeWindows && (base === undefined || base.kind === 'relative' || base.kind === 'posix')) + const distinct = new Map() + for (const root of roots) { + if (distinct.has(root)) continue + const parsed = parsePath(root, preferPosix) + const relative = relativeParts(parsed, base) + const relativeParent = relative && relative.length > 1 ? relative.slice(0, -1) : [] + const parents = parsed.parts.slice(0, -1) + const outsideKnownBase = base !== undefined && base.kind !== 'relative' && !base.hasParentSegment + && parsed.kind !== 'relative' && !parsed.hasParentSegment && relative === undefined + const shortParent = !outsideKnownBase ? undefined : parents.at(-1) + ?? (parsed.kind === 'unc' && parsed.parts.length === 0 + ? `\\\\${parsed.anchor.split('\\')[2]}` + : parsed.parts.length === 0 ? undefined : parsed.kind === 'posix' ? '/' : `${parsed.anchor}\\`) + const context = relativeParent.length > 0 ? relativeParent.join(parsed.separator) : shortParent + const label = context === undefined ? parsed.name : `${parsed.name} (${context})` + const usedDepth = relativeParent.length || (shortParent !== undefined && parents.length > 0 ? 1 : 0) + distinct.set(root, { root, parsed, parents, context, nextDepth: Math.max(1, usedDepth + 1), phase: 0, label }) + } + + // Resolve collisions globally, including a literal directory named like a + // generated label. Every candidate ends in its distinct raw root, so the + // process terminates without a synthetic numeric identifier. + for (;;) { + const byLabel = new Map() + for (const candidate of distinct.values()) { + const group = byLabel.get(candidate.label) + if (group) group.push(candidate) + else byLabel.set(candidate.label, [candidate]) + } + const collisions = [...byLabel.values()].filter(group => group.length > 1) + if (collisions.length === 0) break + for (const group of collisions) { + let advanced = false + for (const candidate of group) advanced = advanceLabel(candidate) || advanced + if (!advanced) throw new Error('repository labels could not be disambiguated') + } + } + return roots.map(root => ({ root, label: distinct.get(root)!.label })) +} diff --git a/tests/git-repo-labels.spec.ts b/tests/git-repo-labels.spec.ts new file mode 100644 index 00000000..76a4a024 --- /dev/null +++ b/tests/git-repo-labels.spec.ts @@ -0,0 +1,247 @@ +/** Repository labels are display-only: preserve input roots/order, and identify context without IO. */ +import { describe, expect, it } from 'vitest' +import { buildRepositoryLabels } from '../src/client/changes/repo-labels.ts' + +const labels = (roots: readonly string[], cwd?: string) => buildRepositoryLabels(roots, cwd).map(row => row.label) + +describe('buildRepositoryLabels', () => { + it('keeps the display base and immediate child names short', () => { + const roots = ['/workspace', '/workspace/dsh-m', '/workspace/ob-harness'] + expect(buildRepositoryLabels(roots, '/workspace')).toEqual([ + { root: '/workspace', label: 'workspace' }, + { root: '/workspace/dsh-m', label: 'dsh-m' }, + { root: '/workspace/ob-harness', label: 'ob-harness' }, + ]) + }) + + it('always shows the full relative parent for deeper roots, even without name conflicts', () => { + expect(labels(['/workspace/ob-harness/contexts/baseline', '/workspace/one/two/repo'], '/workspace')) + .toEqual(['baseline (ob-harness/contexts)', 'repo (one/two)']) + }) + + it('preserves directory names with spaces, Unicode and punctuation', () => { + expect(labels(['/workspace/proj a/子目录/a[b]'], '/workspace')).toEqual(['a[b] (proj a/子目录)']) + }) + + it('treats a POSIX root as base without losing the root or direct child', () => { + expect(labels(['/', '/workspace', '/workspace/a'], '/')).toEqual(['/', 'workspace', 'a (workspace)']) + }) + + it('treats double-leading slashes as POSIX when the known base is POSIX', () => { + const roots = ['//work/project/repo'] + expect(buildRepositoryLabels(roots, '/work')).toEqual([{ root: roots[0], label: 'repo (project)' }]) + }) + + it('treats a Windows-looking namespace as POSIX on a POSIX host', () => { + const roots = ['//?/C:/work/repo', '//?/UNC/work/repo'] + expect(buildRepositoryLabels(roots, '/', '/home/example').map(row => row.label)) + .toEqual(['repo (?/C:/work)', 'repo (?/UNC/work)']) + }) + + it('uses the existing host home to disambiguate double-slash POSIX and UNC bases', () => { + const posixRoots = ['//work/project/a/b/repo', '/work/project/a/b/other'] + expect(buildRepositoryLabels(posixRoots, '//work/project', '/home/example').map(row => row.label)) + .toEqual(['repo (a/b)', 'other (a/b)']) + const windowsRoots = ['//server/share/work/a/b/repo'] + expect(buildRepositoryLabels(windowsRoots, '//server/share/work', 'C:\\Users\\example').map(row => row.label)) + .toEqual(['repo (a\\b)']) + // With no host hint, the two spellings are indistinguishable; preserve + // forward-slash spelling rather than pretending the host is Windows. + expect(buildRepositoryLabels(windowsRoots, '//server/share/work').map(row => row.label)) + .toEqual(['repo (a/b)']) + expect(buildRepositoryLabels(posixRoots, '//work/project').map(row => row.label)) + .toEqual(['repo (a/b)', 'other (a/b)']) + // Unknown host semantics must not infer case-insensitive containment. + expect(buildRepositoryLabels(['//SERVER/share/work/a/b/repo'], '//server/share/work').map(row => row.label)) + .toEqual(['repo (b)']) + }) + + it('preserves slash spelling when host and display base are unknown', () => { + const roots = ['//srv/share/A/same/repo', '//srv/share/B/same/repo'] + const expected = ['repo (A/same)', 'repo (B/same)'] + expect(labels(roots, undefined)).toEqual(expected) + expect(labels(roots, 'relative')).toEqual(expected) + }) + + it('uses segment boundaries rather than a textual prefix', () => { + expect(labels(['/work/repo', '/workspace/other', '/work-other/third'], '/work')) + .toEqual(['repo', 'other (workspace)', 'third (work-other)']) + }) + + it('does not infer containment through unresolved parent segments', () => { + expect(labels(['/workspace/link/../parent/repo'], '/workspace')).toEqual(['repo']) + expect(labels(['/workspace/parent/repo'], '/workspace/link/..')).toEqual(['repo']) + }) + + it('does not case-fold POSIX containment or POSIX distinct names', () => { + expect(labels(['/work/Team/repo', '/Work/Team/other', '/work/foo', '/work/Foo'], '/work')) + .toEqual(['repo (Team)', 'other (Team)', 'foo', 'Foo']) + }) + + it('shows short parent context outside a known base, but short names when the base is unavailable', () => { + const roots = ['/a/pkg', '/b/pkg', '/outside/unique'] + expect(labels(roots, undefined)).toEqual(['pkg (a)', 'pkg (b)', 'unique']) + expect(labels(roots, '/workspace')).toEqual(['pkg (a)', 'pkg (b)', 'unique (outside)']) + expect(labels(roots, 'relative')).toEqual(['pkg (a)', 'pkg (b)', 'unique']) + }) + + it('expands parent context sufficiently when immediate parents match', () => { + const roots = ['/one/common/repo', '/two/common/repo'] + expect(labels(roots)).toEqual(['repo (one/common)', 'repo (two/common)']) + }) + + it('resolves a base item and direct child with the same basename without numeric suffixes', () => { + const roots = ['/workspace', '/workspace/workspace'] + const result = labels(roots, '/workspace') + expect(new Set(result).size).toBe(2) + expect(result.every(label => !/\[\d+\]$/.test(label))).toBe(true) + expect(result).toEqual(labels(roots, '/workspace')) + }) + + it('resolves collision between a generated label and a real directory name globally', () => { + const roots = ['/x/a', '/y/a', '/z/a (x)'] + const result = labels(roots) + expect(new Set(result).size).toBe(3) + expect(result).toEqual(labels(roots)) + expect(result.every(label => !/\[\d+\]$/.test(label))).toBe(true) + }) + + it('falls back to complete paths when names and ancestor suffixes collide', () => { + const roots = ['/x/shared/repo', '/y/shared/repo'] + const result = labels(roots, undefined) + expect(result).toEqual(['repo (x/shared)', 'repo (y/shared)']) + expect(new Set(result).size).toBe(2) + }) + + it('uses absolute paths as a final fallback without losing distinct raw spellings', () => { + const roots = ['/a/repo', '/a/repo/'] + const result = labels(roots) + expect(new Set(result).size).toBe(2) + expect(result.join('\n')).toContain('/a/repo') + expect(result).toEqual(labels(roots)) + }) + + it('supports case-insensitive Windows drive containment using Windows separators', () => { + const roots = ['C:\\Work', 'c:\\work\\app', 'C:\\work\\project\\nested\\repo'] + expect(labels(roots, 'C:\\WORK\\')).toEqual(['Work', 'app', 'repo (project\\nested)']) + }) + + it('recognises Windows paths written with forward slashes and uses the host dialect', () => { + expect(labels(['C:/Work/project/nested/repo'], 'c:/work')).toEqual(['repo (project\\nested)']) + }) + + it('matches Windows extended-length drive and UNC paths to ordinary bases', () => { + expect(labels(['\\\\?\\C:\\work\\project\\nested\\repo'], 'C:\\work')) + .toEqual(['repo (project\\nested)']) + expect(labels(['\\\\?\\UNC\\srv\\share\\work\\project\\nested\\repo'], '\\\\srv\\share\\work')) + .toEqual(['repo (project\\nested)']) + expect(labels(['//?/C:/work/project/nested/repo'], 'C:\\work')) + .toEqual(['repo (project\\nested)']) + expect(labels(['//?/UNC/srv/share/work/project/nested/repo'], '\\\\srv\\share\\work')) + .toEqual(['repo (project\\nested)']) + }) + + it('recognises mixed UNC separators on a Windows host without misreading POSIX names', () => { + const roots = ['\\/server/share/work/a/repo', '/\\server/share/work/b/nested/other'] + const rows = buildRepositoryLabels(roots, '\\\\server\\share\\work', 'C:\\Users\\example') + expect(rows.map(row => row.root)).toEqual(roots) + expect(rows.map(row => row.label)).toEqual(['repo (a)', 'other (b\\nested)']) + expect(buildRepositoryLabels(['/\\server/share/work/a/repo'], '/', '/home/example').map(row => row.label)) + .toEqual(['repo (\\server/share/work/a)']) + const ambiguous = ['/\\server/share/work/a/b/repo'] + expect(buildRepositoryLabels(ambiguous, '/\\server/share/work').map(row => row.label)) + .toEqual(['repo (a/b)']) + expect(buildRepositoryLabels(ambiguous, '/\\server/share/work', 'C:\\Users\\example').map(row => row.label)) + .toEqual(['repo (a\\b)']) + const duplicates = ['//server/share/A/same/repo', '//server/share/B/same/repo'] + expect(buildRepositoryLabels(duplicates, undefined, '\\/server/share/user').map(row => row.label)) + .toEqual(['repo (A\\same)', 'repo (B\\same)']) + }) + + it('does not treat a different Windows drive as inside the base', () => { + expect(labels(['D:\\work\\project\\repo'], 'C:\\work')).toEqual(['repo (project)']) + }) + + it('shows a root-level parent for an outside repository', () => { + expect(labels(['/repo'], '/workspace')).toEqual(['repo (/)']) + expect(labels(['D:\\repo'], 'C:\\work')).toEqual(['repo (D:\\)']) + expect(labels(['\\\\server\\other'], '\\\\server\\share')).toEqual(['other (\\\\server)']) + }) + + it('uses drive-qualified absolute paths when parent contexts cannot distinguish drives', () => { + expect(labels(['C:\\repo', 'D:\\repo'])).toEqual(['repo (C:\\repo)', 'repo (D:\\repo)']) + expect(labels(['C:\\', 'C:\\work', 'C:\\work\\repo'], 'C:\\')) + .toEqual(['C:\\', 'work', 'repo (work)']) + }) + + it('distinguishes raw Windows path spellings when their normalized identity is equal', () => { + const roots = ['C:\\work\\repo', 'c:/work/repo/'] + const rows = buildRepositoryLabels(roots, 'C:\\work') + expect(rows.map(row => row.root)).toEqual(roots) + expect(new Set(rows.map(row => row.label)).size).toBe(2) + expect(rows.map(row => row.label)).toEqual(labels(roots, 'C:\\work')) + }) + + it('supports UNC shares and case-insensitive Windows containment', () => { + const roots = ['\\\\server\\Share', '\\\\SERVER\\share\\org\\repo', '\\\\server\\other\\org\\other'] + expect(labels(roots, '\\\\SERVER\\SHARE\\')).toEqual(['Share', 'repo (org)', 'other (org)']) + }) + + it('treats backslashes inside POSIX path components literally', () => { + expect(labels(['/workspace/project\\name/sub/repo'], '/workspace')).toEqual(['repo (project\\name/sub)']) + }) + + it('handles trailing separators while leaving each selected root untouched', () => { + const roots = ['/workspace/', '/workspace/nested/repo/', 'C:\\work\\project\\'] + const rows = buildRepositoryLabels(roots, '/workspace/') + expect(rows.map(row => row.root)).toEqual(roots) + expect(rows.map(row => row.label)).toEqual(['workspace', 'repo (nested)', 'project (work)']) + }) + + it('does not invent distinct identities for duplicate identical input roots', () => { + const root = '/workspace/app' + expect(buildRepositoryLabels([root, root], '/workspace')).toEqual([ + { root, label: 'app' }, { root, label: 'app' }, + ]) + }) + + it('distinguishes 200 colliding basenames with an unknown base', () => { + const roots = Object.freeze(Array.from({ length: 200 }, (_, i) => `/outside/project-${i}/shared/repo`)) + const result = buildRepositoryLabels(roots, undefined) + expect(result.map(row => row.root)).toEqual([...roots]) + expect(new Set(result.map(row => row.label)).size).toBe(200) + expect(result[0]?.label).toBe('repo (project-0/shared)') + expect(result[199]?.label).toBe('repo (project-199/shared)') + }) + + it('does not build ancestor suffixes for unique names', () => { + const base = '/' + Array.from({ length: 200 }, (_, i) => `d${i}`).join('/') + const roots = Array.from({ length: 100 }, (_, i) => `${base}/repo-${i}`) + const originalJoin = Array.prototype.join + let calls = 0 + Array.prototype.join = function (separator?: string) { + calls++ + return originalJoin.call(this, separator) + } + let rows: ReturnType + try { + rows = buildRepositoryLabels(roots, base) + } finally { + Array.prototype.join = originalJoin + } + expect(rows).toHaveLength(100) + expect(calls).toBeLessThan(500) + }) + + it('constructs 200 labels in input order without mutating frozen input', () => { + const roots = Object.freeze(Array.from({ length: 200 }, (_, i) => `/workspace/project-${i}/contexts/repo`)) + const before = [...roots] + const result = buildRepositoryLabels(roots, '/workspace') + expect(result).toHaveLength(200) + expect(result.map(row => row.root)).toEqual(before) + expect(new Set(result.map(row => row.label)).size).toBe(200) + expect(result[0]?.label).toBe('repo (project-0/contexts)') + expect(result[199]?.label).toBe('repo (project-199/contexts)') + expect(roots).toEqual(before) + }) +}) diff --git a/tests/git-repo-switcher.spec.tsx b/tests/git-repo-switcher.spec.tsx index cf6e5b29..f4cb380c 100644 --- a/tests/git-repo-switcher.spec.tsx +++ b/tests/git-repo-switcher.spec.tsx @@ -1,20 +1,26 @@ /** - * Multi-repository switcher in the Git lens (a workspace CONTAINER, i.e. a + * Multi-repository picker in the Git lens (a workspace CONTAINER, i.e. a * project directory that is not itself a repository but holds several). * * Contract: * - `git.status` reports `repositories` (every discovered root). When it holds - * more than one, the lens renders one chip per root above the Changes - * section: label = `baseName(root)`, `[data-scm-repo]` = the absolute root. - * - Exactly one chip is marked `[data-active="true"]`: the root the panel is - * currently pinned to (`repoRoot`, or the resolved `status.root` before the - * user picks one). Both spellings of one checkout are the same root — - * forward/back slashes, a trailing separator and Windows case all fold. - * - Clicking another chip re-pins the scope through the same `chooseRepo` the - * ⋯ → 仓库 submenu uses, so the next status read carries that root and the - * switcher survives the following read (a selected child still reports the - * full `repositories` list). - * - A single-repository workspace renders NO switcher: the row must not steal + * more than one, the lens renders a labeled