feat(git): a labeled repository picker for multi-repo workspaces

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.
This commit is contained in:
Sidebar Test authored and Menghuan1918 committed 2026-11-16 00:33:58 +08:00
1 parent 7c374293c7
commit ea770cc2e1
7 files changed
+577 -85

No files matched your search

+3
View File
@@ -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`、无残留标记。
+3
View File
@@ -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.
+49 -16
View File
@@ -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 && <Notice kind="warn">{t('statusTruncated')}</Notice>}
{/* 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 && (
<div className={css.repoSwitcher} data-scm-repos role="group" aria-label={t('gitRepository')}>
{repoChoices.map(root => {
const isActive = sameRepoRoot(root, repoRoot ?? snapshot?.root)
return (
<button key={root} type="button" className={css.repoChip} data-scm-repo={root}
data-active={isActive ? 'true' : undefined} aria-pressed={isActive} title={root}
disabled={busy || suggesting} onClick={() => { chooseRepo(root) }}>
{baseName(root)}
</button>
)
})}
</div>
<label className={css.repoPick} data-scm-repos>
<span className={css.repoPickLabel}>{t('gitRepository')}</span>
<select className={css.repoPickSelect} aria-label={t('gitRepository')}
value={resolvedRepository ?? ''} disabled={busy || suggesting}
onChange={event => { chooseRepo(event.target.value) }}>
{resolvedRepository !== undefined && !repositoryLabels.some(item => item.root === resolvedRepository) &&
<option value={resolvedRepository} disabled>{resolvedRepositoryLabel ?? t('gitRepository')}</option>}
{repositoryLabels.map(item => <option key={item.root} value={item.root}>{item.label}</option>)}
</select>
</label>
)}
{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}`,
+20 -27
View File
@@ -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
+168
View File
@@ -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<string, LabelCandidate>()
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<string, LabelCandidate[]>()
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 }))
}
+247
View File
@@ -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<typeof buildRepositoryLabels>
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)
})
})
+87 -42
View File
@@ -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 <select> ("Repository") above
* the Changes section: each option pairs the display-only disambiguation
* label (`buildRepositoryLabels(roots, scope.cwd, hostHome)` — deeper roots
* carry their relative parent, so same-named checkouts stay tellable apart)
* with its absolute root as the value. The ⋯ → Repository submenu shares the
* same label list.
* - The picker's value is the RESOLVED status root, and both spellings of one
* checkout fold (forward/back slashes, trailing separator, Windows case).
* When that root is no longer among the retained choices (the server fell
* back), it renders as a DISABLED stand-in option with its own short label —
* the stale request or the first option is never silently presented as the
* selection.
* - Changing the picker re-pins the scope through the same `chooseRepo` the
* submenu uses, so the next status read carries that root and the picker
* survives the following read (a selected child still reports the full
* `repositories` list).
* - A single-repository workspace renders NO picker: the row must not steal
* vertical space from the ordinary case.
*/
// @vitest-environment jsdom
@@ -22,6 +28,7 @@ import { act } from 'react-dom/test-utils'
import { afterEach, expect, it, vi } from 'vitest'
import { api, type GitStatusResult, type SessionScope } from '../src/client/api.ts'
import { GitLens } from '../src/client/changes/GitLens.tsx'
import { t } from '../src/client/locales.ts'
import { renderRoot, setupReactAct } from './test-utils.ts'
setupReactAct()
@@ -30,22 +37,28 @@ afterEach(() => { vi.restoreAllMocks() })
const CWD = 'C:/work'
const ADMIN = 'C:/work-admin'
const DOCS = 'C:/work-docs'
const DEEP_A = 'C:/work/pack/alpha'
const DEEP_B = 'C:/work/pack/beta'
const flush = async (): Promise<void> => { await act(async () => { await Promise.resolve() }) }
const click = async (button: HTMLButtonElement): Promise<void> => { await act(async () => { button.click() }) }
const chips = (container: HTMLElement): HTMLButtonElement[] =>
[...container.querySelectorAll<HTMLButtonElement>('[data-scm-repo]')]
const picker = (container: HTMLElement): HTMLSelectElement => {
const node = container.querySelector<HTMLSelectElement>(`[data-scm-repos] select[aria-label="${t('gitRepository')}"]`)
if (node === null) throw new Error('repository picker missing')
return node
}
const options = (node: HTMLSelectElement): HTMLOptionElement[] => [...node.options].filter(option => !option.disabled)
/** One container-workspace snapshot: the resolved root plus every discovered root. */
const snapshot = (root: string, repositories: string[]): GitStatusResult =>
({ isRepo: true, branch: 'main', root, entries: [], repositories })
/** Mount the lens over a mocked host; `scopes` records every status request. */
async function mount(options: { sessionId: string; repositories?: string[] }) {
async function mount(options: { sessionId: string; repositories?: string[]; resolvedRoot?: (scope: SessionScope) => string }) {
const scopes: SessionScope[] = []
const repositories = options.repositories ?? [CWD, ADMIN, DOCS]
const resolvedRoot = options.resolvedRoot ?? (scope => scope.repoRoot ?? CWD)
vi.spyOn(api, 'gitStatus').mockImplementation(async scope => {
scopes.push(scope)
return snapshot(scope.repoRoot ?? CWD, repositories)
return snapshot(resolvedRoot(scope), repositories)
})
vi.spyOn(api, 'gitWorktrees').mockResolvedValue([{ path: CWD, branch: 'main', current: true, changes: 0 }])
vi.spyOn(api, 'gitBranch').mockResolvedValue({ current: 'main', names: ['main'] })
@@ -62,44 +75,76 @@ async function mount(options: { sessionId: string; repositories?: string[] }) {
return { ...view, scopes }
}
it('lists every discovered repository and re-pins the scope to the clicked chip', async () => {
it('lists every discovered repository and re-pins the scope through the picker', async () => {
const view = await mount({ sessionId: 'scm-repos-multi' })
const { container } = view
const row = container.querySelector('[data-scm-repos]')!
expect(row).not.toBeNull()
const node = picker(view.container)
expect(options(node).map(option => option.value)).toEqual([CWD, ADMIN, DOCS])
// Siblings outside the session cwd's directory carry their parent context;
// the base itself stays short.
expect(options(node).map(option => option.textContent)).toEqual(['work', 'work-admin (C:\\)', 'work-docs (C:\\)'])
expect(node.value).toBe(CWD)
const buttons = chips(container)
expect(buttons.map(button => button.dataset.scmRepo)).toEqual([CWD, ADMIN, DOCS])
expect(buttons.map(button => button.textContent)).toEqual(['work', 'work-admin', 'work-docs'])
expect(buttons.map(button => button.getAttribute('data-active'))).toEqual(['true', null, null])
expect(buttons[0]!.getAttribute('aria-pressed')).toBe('true')
await click(buttons[1]!)
await act(async () => { node.value = ADMIN; node.dispatchEvent(new Event('change', { bubbles: true })) })
await flush()
await flush()
// The click went through `chooseRepo`: the next status read targets that root...
// The change went through `chooseRepo`: the next status read targets that root...
expect(view.scopes.at(-1)?.repoRoot).toBe(ADMIN)
// ...and the switcher survived the following snapshot, still listing all roots.
const after = chips(container)
expect(after.map(button => button.dataset.scmRepo)).toEqual([CWD, ADMIN, DOCS])
expect(after.map(button => button.getAttribute('data-active'))).toEqual([null, 'true', null])
// ...and the picker survives the following snapshot, still listing all roots.
expect(picker(view.container).value).toBe(ADMIN)
expect(options(picker(view.container)).map(option => option.value)).toEqual([CWD, ADMIN, DOCS])
})
it('folds separator, trailing slash and case when marking the current checkout', async () => {
// The status snapshot reports the git spelling (`C:/work`); the root rendered
// into a chip may arrive as `C:\WORK\`. Both name the same checkout, so
// exactly one chip is active — a naive string compare would mark none.
it('folds separator, trailing slash and case when naming the current checkout', async () => {
// The status snapshot reports the git spelling (`C:/work`); the retained
// option may be `C:\WORK\`. Both name the same checkout, so the picker
// selects the original spelling instead of falling to the first option.
const view = await mount({ sessionId: 'scm-repos-spelling', repositories: ['C:\\WORK\\', ADMIN] })
const buttons = chips(view.container)
expect(buttons.map(button => button.dataset.scmRepo)).toEqual(['C:\\WORK\\', ADMIN])
expect(buttons.map(button => button.getAttribute('data-active'))).toEqual(['true', null])
expect(picker(view.container).value).toBe('C:\\WORK\\')
})
it('renders no switcher for a single-repository workspace', async () => {
it('renders no picker for a single-repository workspace', async () => {
const view = await mount({ sessionId: 'scm-repos-single', repositories: [CWD] })
expect(view.container.querySelector('[data-scm-repos]')).toBeNull()
expect(chips(view.container)).toEqual([])
// The ordinary panel is intact: the Changes section is still there.
expect(view.container.querySelector('[data-scm-section="changes"]')).not.toBeNull()
})
it('labels deeper repositories with their relative parent and shares the list with the menu', async () => {
const view = await mount({ sessionId: 'scm-repos-labels', repositories: [CWD, DEEP_A, DEEP_B] })
expect(options(picker(view.container)).map(option => option.textContent))
.toEqual(['work', 'alpha (pack)', 'beta (pack)'])
// The ⋯ → Repository submenu reads the same label list.
act(() => { view.container.querySelector<HTMLButtonElement>(`button[aria-label="${t('gitMoreActions')}"]`)!.click() })
const parent = [...document.querySelectorAll<HTMLButtonElement>('button[role="menuitem"]')]
.find(button => button.textContent?.trim() === t('gitRepository'))
expect(parent).not.toBeUndefined()
act(() => { parent!.click() })
const items = [...document.querySelectorAll<HTMLButtonElement>('[role="menu"] [role="menu"] button[role="menuitem"]')]
expect(items.map(item => item.textContent)).toEqual(['work', 'alpha (pack)', 'beta (pack)'])
})
it('shows the server-fallback root as a disabled stand-in, never as a silent first option', async () => {
// Picking ADMIN while the server resolves it to a checkout outside the
// retained list: the picker must name THAT root (short label, disabled), not
// quietly select the first option or keep the stale request.
const FALLBACK = '/elsewhere/checkout'
const view = await mount({
sessionId: 'scm-repos-fallback',
resolvedRoot: scope => scope.repoRoot === ADMIN ? FALLBACK : (scope.repoRoot ?? CWD),
})
await act(async () => {
const node = picker(view.container)
node.value = ADMIN
node.dispatchEvent(new Event('change', { bubbles: true }))
})
await flush()
await flush()
// A scope change resets the status slot, so the picker remounts; re-query.
const node = picker(view.container)
expect(node.value).toBe(FALLBACK)
const standIn = node.selectedOptions[0]!
expect(standIn.disabled).toBe(true)
expect(standIn.textContent).toBe('checkout (elsewhere)')
expect(options(node).map(option => option.value)).toEqual([CWD, ADMIN, DOCS])
})