fix: support selecting child git repositories

This commit is contained in:
lx committed 2026-08-22 18:13:50 +08:00
1 parent 9a40164d1a
commit 78de79c9d6
7 files changed
+181 -73

No files matched your search

+1 -1
View File
@@ -33,7 +33,7 @@ export function DiffTab(props: { sessionId: string; cwd: string | undefined; dif
useEffect(() => { useEffect(() => {
let cancelled = false let cancelled = false
const scope: SessionScope = { sessionId, cwd } const scope: SessionScope = { sessionId, cwd, ...(diff.repoRoot !== undefined ? { repoRoot: diff.repoRoot } : {}) }
setLoading(true) setLoading(true)
setError(null) setError(null)
setData(null) setData(null)
+41 -19
View File
@@ -55,6 +55,13 @@ function baseName(path: string): string {
return at === -1 ? path : path.slice(at + 1) return at === -1 ? path : path.slice(at + 1)
} }
/** Resolve a repo-relative status path for the shared file/editor routes. */
function absolutePathOf(root: string | undefined, path: string): string {
if (root === undefined || path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path)) return path
const separator = root.includes('\\') ? '\\' : '/'
return `${root.replace(/[\\/]+$/u, '')}${separator}${path.replace(/[\\/]/gu, separator)}`
}
/** The ref names of one log row's decorations (`HEAD -> main` → `main`), deduped. */ /** The ref names of one log row's decorations (`HEAD -> main` → `main`), deduped. */
function refNames(refs: string): string[] { function refNames(refs: string): string[] {
return [...new Set( return [...new Set(
@@ -87,6 +94,7 @@ export function GitView(props: {
}) { }) {
const { scope, onOpenFile, onOpenDiff } = props const { scope, onOpenFile, onOpenDiff } = props
const [status, setStatus] = useState<GitStatusResult | null>(null) const [status, setStatus] = useState<GitStatusResult | null>(null)
const [repoRoot, setRepoRoot] = useState<string | undefined>(undefined)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [branchNames, setBranchNames] = useState<string[]>([]) const [branchNames, setBranchNames] = useState<string[]>([])
@@ -105,17 +113,20 @@ export function GitView(props: {
/** The pending destructive action awaiting confirmation. */ /** The pending destructive action awaiting confirmation. */
const [confirm, setConfirm] = useState<ConfirmState | null>(null) const [confirm, setConfirm] = useState<ConfirmState | null>(null)
const gitScope: SessionScope = repoRoot === undefined ? scope : { ...scope, repoRoot }
const refresh = useCallback(async (): Promise<void> => { const refresh = useCallback(async (): Promise<void> => {
setLoading(true) setLoading(true)
setError(null) setError(null)
try { try {
const [statusResult, branchResult, logResult] = await Promise.all([ const [statusResult, branchResult, logResult] = await Promise.all([
api.gitStatus(scope), api.gitStatus(gitScope),
api.gitBranch(scope).catch(() => ({ current: '', names: [] as string[] })), api.gitBranch(gitScope).catch(() => ({ current: '', names: [] as string[] })),
// The first history page only; the rest arrives via "load more". // The first history page only; the rest arrives via "load more".
api.gitLog(scope, LOG_BATCH, 0).catch(() => [] as GitLogEntry[]), api.gitLog(gitScope, LOG_BATCH, 0).catch(() => [] as GitLogEntry[]),
]) ])
setStatus(statusResult) setStatus(statusResult)
if (statusResult.root !== undefined && statusResult.root !== repoRoot) setRepoRoot(statusResult.root)
setBranchNames(branchResult.names) setBranchNames(branchResult.names)
setLogEntries(logResult) setLogEntries(logResult)
setLogEnded(logResult.length < LOG_BATCH) setLogEnded(logResult.length < LOG_BATCH)
@@ -124,7 +135,7 @@ export function GitView(props: {
} finally { } finally {
setLoading(false) setLoading(false)
} }
}, [scope.sessionId, scope.cwd]) }, [scope.sessionId, scope.cwd, repoRoot])
useEffect(() => { void refresh() }, [refresh]) useEffect(() => { void refresh() }, [refresh])
@@ -133,7 +144,7 @@ export function GitView(props: {
if (logLoadingMore || logEnded) return if (logLoadingMore || logEnded) return
setLogLoadingMore(true) setLogLoadingMore(true)
try { try {
const next = await api.gitLog(scope, LOG_BATCH, logEntries.length) const next = await api.gitLog(gitScope, LOG_BATCH, logEntries.length)
setLogEntries(entries => [...entries, ...next]) setLogEntries(entries => [...entries, ...next])
if (next.length < LOG_BATCH) setLogEnded(true) if (next.length < LOG_BATCH) setLogEnded(true)
} catch (reason) { } catch (reason) {
@@ -149,7 +160,7 @@ export function GitView(props: {
id: `diff:w:${staged ? 's' : 'u'}:${entry.path}`, id: `diff:w:${staged ? 's' : 'u'}:${entry.path}`,
type: 'diff', type: 'diff',
title: baseName(entry.path), title: baseName(entry.path),
diff: { kind: 'worktree', path: entry.path, staged, untracked: isUntracked(entry) }, diff: { kind: 'worktree', path: entry.path, staged, untracked: isUntracked(entry), repoRoot },
}) })
} }
@@ -159,15 +170,15 @@ export function GitView(props: {
id: `diff:c:${entry.hashFull}`, id: `diff:c:${entry.hashFull}`,
type: 'diff', type: 'diff',
title: `${entry.hash} ${entry.subject}`, title: `${entry.hash} ${entry.subject}`,
diff: { kind: 'commit', hash: entry.hash, hashFull: entry.hashFull, subject: entry.subject }, diff: { kind: 'commit', hash: entry.hash, hashFull: entry.hashFull, subject: entry.subject, repoRoot },
}) })
} }
const stageEntry = async (entry: GitStatusEntry, staged: boolean): Promise<void> => { const stageEntry = async (entry: GitStatusEntry, staged: boolean): Promise<void> => {
setBusy(true) setBusy(true)
try { try {
if (staged) await api.gitUnstage(scope, entry.path) if (staged) await api.gitUnstage(gitScope, entry.path)
else await api.gitStage(scope, entry.path) else await api.gitStage(gitScope, entry.path)
await refresh() await refresh()
} finally { } finally {
setBusy(false) setBusy(false)
@@ -177,8 +188,8 @@ export function GitView(props: {
const stageAll = async (staged: boolean): Promise<void> => { const stageAll = async (staged: boolean): Promise<void> => {
setBusy(true) setBusy(true)
try { try {
if (staged) await api.gitUnstage(scope) if (staged) await api.gitUnstage(gitScope)
else await api.gitStage(scope) else await api.gitStage(gitScope)
await refresh() await refresh()
} finally { } finally {
setBusy(false) setBusy(false)
@@ -191,7 +202,7 @@ export function GitView(props: {
setBusy(true) setBusy(true)
setCommitError(null) setCommitError(null)
try { try {
await api.gitCommit(scope, message) await api.gitCommit(gitScope, message)
setCommitMsg('') setCommitMsg('')
await refresh() await refresh()
} catch (reason) { } catch (reason) {
@@ -206,7 +217,7 @@ export function GitView(props: {
setBusy(true) setBusy(true)
setCommitError(null) setCommitError(null)
try { try {
await api.gitCheckout(scope, branch) await api.gitCheckout(gitScope, branch)
await refresh() await refresh()
} catch (reason) { } catch (reason) {
setCommitError(`${t('checkoutError')}: ${reason instanceof Error ? reason.message : String(reason)}`) setCommitError(`${t('checkoutError')}: ${reason instanceof Error ? reason.message : String(reason)}`)
@@ -281,6 +292,17 @@ export function GitView(props: {
return ( return (
<div className={css.git}> <div className={css.git}>
<div className={css.gitHeader}> <div className={css.gitHeader}>
{(status?.repositories?.length ?? 0) > 1 && (
<select
className={css.gitBranchSelect}
value={repoRoot ?? ''}
title={repoRoot}
onChange={(event) => { setRepoRoot(event.target.value) }}
disabled={busy}
>
{status!.repositories!.map(root => <option key={root} value={root}>{baseName(root)}</option>)}
</select>
)}
<select <select
className={css.gitBranchSelect} className={css.gitBranchSelect}
value={status?.branch ?? ''} value={status?.branch ?? ''}
@@ -422,7 +444,7 @@ export function GitView(props: {
if (target === null) return if (target === null) return
setFileMenu(null) setFileMenu(null)
if (id === 'open') { if (id === 'open') {
onOpenFile(target.entry.path) onOpenFile(absolutePathOf(repoRoot, target.entry.path))
return return
} }
if (id === 'stage') { if (id === 'stage') {
@@ -434,15 +456,15 @@ export function GitView(props: {
title: t('discardTitle'), title: t('discardTitle'),
description: t('discardDesc', { path: target.entry.path }), description: t('discardDesc', { path: target.entry.path }),
confirmLabel: t('discard'), confirmLabel: t('discard'),
onConfirm: () => api.gitDiscard(scope, target.entry.path), onConfirm: () => api.gitDiscard(gitScope, target.entry.path),
}) })
return return
} }
if (id === 'relative') { if (id === 'relative') {
copy(relativeTo(scope.cwd ?? '', target.entry.path)) copy(relativeTo(repoRoot ?? scope.cwd ?? '', target.entry.path))
return return
} }
if (id === 'absolute') copy(target.entry.path) if (id === 'absolute') copy(absolutePathOf(repoRoot, target.entry.path))
}} }}
portal portal
align="start" align="start"
@@ -488,7 +510,7 @@ export function GitView(props: {
title: t('revertTitle'), title: t('revertTitle'),
description: t('revertDesc', { subject: target.entry.subject }), description: t('revertDesc', { subject: target.entry.subject }),
confirmLabel: t('revertCommit'), confirmLabel: t('revertCommit'),
onConfirm: () => api.gitRevert(scope, target.entry.hashFull), onConfirm: () => api.gitRevert(gitScope, target.entry.hashFull),
}) })
return return
} }
@@ -497,7 +519,7 @@ export function GitView(props: {
title: t('cherryPickTitle'), title: t('cherryPickTitle'),
description: t('cherryPickDesc', { subject: target.entry.subject }), description: t('cherryPickDesc', { subject: target.entry.subject }),
confirmLabel: t('cherryPickCommit'), confirmLabel: t('cherryPickCommit'),
onConfirm: () => api.gitCherryPick(scope, target.entry.hashFull), onConfirm: () => api.gitCherryPick(gitScope, target.entry.hashFull),
}) })
} }
}} }}
+10 -1
View File
@@ -44,6 +44,8 @@ export interface GitStatusResult {
isRepo: boolean isRepo: boolean
branch?: string branch?: string
entries: GitStatusEntry[] entries: GitStatusEntry[]
root?: string
repositories?: string[]
} }
/** One git log row. */ /** One git log row. */
@@ -166,11 +168,18 @@ export interface SessionScope {
sessionId: string sessionId: string
/** The session's working directory from the client list summary (optional). */ /** The session's working directory from the client list summary (optional). */
cwd?: string cwd?: string
/** Selected Git repository when cwd is a workspace container. */
repoRoot?: string
} }
/** Fold a scope into a JSON payload ({cwd} only when present). */ /** Fold a scope into a JSON payload ({cwd} only when present). */
function scopePayload(scope: SessionScope, extra: Record<string, unknown>): Record<string, unknown> { function scopePayload(scope: SessionScope, extra: Record<string, unknown>): Record<string, unknown> {
return { sessionId: scope.sessionId, ...(scope.cwd !== undefined && scope.cwd !== '' ? { cwd: scope.cwd } : {}), ...extra } return {
sessionId: scope.sessionId,
...(scope.cwd !== undefined && scope.cwd !== '' ? { cwd: scope.cwd } : {}),
...(scope.repoRoot !== undefined && scope.repoRoot !== '' ? { repoRoot: scope.repoRoot } : {}),
...extra,
}
} }
/** The sidebar API surface (session scope threaded through every call). */ /** The sidebar API surface (session scope threaded through every call). */
+2 -2
View File
@@ -22,8 +22,8 @@ export type TabType = string
/** What a diff tab shows: a worktree/index change of one path, or one commit's full patch. */ /** What a diff tab shows: a worktree/index change of one path, or one commit's full patch. */
export type SidebarDiffRef = export type SidebarDiffRef =
| { kind: 'worktree'; path: string; staged: boolean; untracked?: boolean } | { kind: 'worktree'; path: string; staged: boolean; untracked?: boolean; repoRoot?: string }
| { kind: 'commit'; hash: string; hashFull: string; subject: string } | { kind: 'commit'; hash: string; hashFull: string; subject: string; repoRoot?: string }
/** One open tab. `path` carries the file (editor) or is absent (git/terminal); /** One open tab. `path` carries the file (editor) or is absent (git/terminal);
* `diff` carries the change a diff tab shows; `meta` (v0.12.0+) carries * `diff` carries the change a diff tab shows; `meta` (v0.12.0+) carries
+69 -32
View File
@@ -9,6 +9,8 @@
* Commits use the user's git global identity untouched (never sets * Commits use the user's git global identity untouched (never sets
* user.name/user.email). * user.name/user.email).
*/ */
import { readdir } from 'node:fs/promises'
import { join } from 'node:path'
import { spawn } from 'node:child_process' import { spawn } from 'node:child_process'
/** A parsed `git status --porcelain=v1 -z` entry. */ /** A parsed `git status --porcelain=v1 -z` entry. */
@@ -23,6 +25,9 @@ export interface GitStatusResult {
isRepo: boolean isRepo: boolean
branch?: string branch?: string
entries: GitStatusEntry[] entries: GitStatusEntry[]
/** Selected repository root, or the discovered roots when the cwd is a container. */
root?: string
repositories?: string[]
} }
/** One `git log` row. */ /** One `git log` row. */
@@ -132,11 +137,40 @@ export async function isGitRepo(cwd: string): Promise<boolean> {
} }
/** The repository top level containing `cwd` (`git rev-parse --show-toplevel`). */ /** The repository top level containing `cwd` (`git rev-parse --show-toplevel`). */
export async function repoRoot(cwd: string): Promise<string> { async function directRepoRoot(cwd: string): Promise<string> {
const out = await runGit(cwd, ['rev-parse', '--show-toplevel']) const out = await runGit(cwd, ['rev-parse', '--show-toplevel'])
return out.trim() return out.trim()
} }
/** Discover the current repository or direct child repositories. */
export async function repoRoots(cwd: string): Promise<string[]> {
try {
return [await directRepoRoot(cwd)]
} catch {
const entries = await readdir(cwd, { withFileTypes: true }).catch(() => [])
const roots: string[] = []
for (const entry of entries
.filter(entry => entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules')
.sort((left, right) => left.name.localeCompare(right.name))) {
try {
const root = await directRepoRoot(join(cwd, entry.name))
if (!roots.includes(root)) roots.push(root)
} catch {
// Ordinary child directory; keep discovering sibling repositories.
}
}
return roots
}
}
/** Resolve the selected repository, defaulting to the first discovered root. */
export async function repoRoot(cwd: string, selected?: string): Promise<string> {
const roots = await repoRoots(cwd)
if (roots.length === 0) throw new GitCommandError('not a git repository', 'not-repo', 'rev-parse')
if (selected !== undefined && roots.includes(selected)) return selected
return roots[0]!
}
/** The current branch name (`git rev-parse --abbrev-ref HEAD`; 'HEAD' when detached). */ /** The current branch name (`git rev-parse --abbrev-ref HEAD`; 'HEAD' when detached). */
export async function currentBranch(cwd: string): Promise<string> { export async function currentBranch(cwd: string): Promise<string> {
const out = await runGit(cwd, ['rev-parse', '--abbrev-ref', 'HEAD']) const out = await runGit(cwd, ['rev-parse', '--abbrev-ref', 'HEAD'])
@@ -144,57 +178,60 @@ export async function currentBranch(cwd: string): Promise<string> {
} }
/** Working-tree status (untracked included). */ /** Working-tree status (untracked included). */
export async function status(cwd: string): Promise<GitStatusResult> { export async function status(cwd: string, selected?: string): Promise<GitStatusResult> {
const repo = await isGitRepo(cwd) const repositories = await repoRoots(cwd)
if (!repo) return { isRepo: false, entries: [] } if (repositories.length === 0) return { isRepo: false, entries: [], repositories: [] }
const root = await repoRoot(cwd, selected)
const [branch, raw] = await Promise.all([ const [branch, raw] = await Promise.all([
currentBranch(cwd).catch(() => 'HEAD'), currentBranch(root).catch(() => 'HEAD'),
runGit(cwd, ['status', '--porcelain=v1', '-z', '--untracked-files=normal']), runGit(root, ['status', '--porcelain=v1', '-z', '--untracked-files=normal']),
]) ])
return { isRepo: true, branch, entries: parsePorcelainZ(raw) } return { isRepo: true, branch, entries: parsePorcelainZ(raw), root, repositories }
} }
/** Diff text of the worktree (unstaged) or the index (staged). */ /** Diff text of the worktree (unstaged) or the index (staged). */
export async function diff(cwd: string, path: string | undefined, staged: boolean): Promise<string> { export async function diff(cwd: string, path: string | undefined, staged: boolean, selected?: string): Promise<string> {
const root = await repoRoot(cwd, selected)
const args = ['diff', '--no-ext-diff', '--no-color', '-U3'] const args = ['diff', '--no-ext-diff', '--no-color', '-U3']
if (staged) args.push('--cached') if (staged) args.push('--cached')
if (path !== undefined) args.push('--', path) if (path !== undefined) args.push('--', path)
return runGit(cwd, args) return runGit(root, args)
} }
/** Stage paths (all when path is undefined). */ /** Stage paths (all when path is undefined). */
export async function stage(cwd: string, path: string | undefined): Promise<void> { export async function stage(cwd: string, path: string | undefined, selected?: string): Promise<void> {
await runGit(cwd, ['add', '-A', ...(path !== undefined ? ['--', path] : [])]) await runGit(await repoRoot(cwd, selected), ['add', '-A', ...(path !== undefined ? ['--', path] : [])])
} }
/** Unstage paths (all when path is undefined). */ /** Unstage paths (all when path is undefined). */
export async function unstage(cwd: string, path: string | undefined): Promise<void> { export async function unstage(cwd: string, path: string | undefined, selected?: string): Promise<void> {
await runGit(cwd, ['reset', '-q', ...(path !== undefined ? ['--', path] : [])]) await runGit(await repoRoot(cwd, selected), ['reset', '-q', ...(path !== undefined ? ['--', path] : [])])
} }
/** Commit the staged changes with a message (global identity untouched). */ /** Commit the staged changes with a message (global identity untouched). */
export async function commit(cwd: string, message: string): Promise<void> { export async function commit(cwd: string, message: string, selected?: string): Promise<void> {
await runGit(cwd, ['commit', '-m', message]) await runGit(await repoRoot(cwd, selected), ['commit', '-m', message])
} }
/** Branch names (current first). */ /** Branch names (current first). */
export async function branches(cwd: string): Promise<{ current: string; names: string[] }> { export async function branches(cwd: string, selected?: string): Promise<{ current: string; names: string[] }> {
const root = await repoRoot(cwd, selected)
const [current, raw] = await Promise.all([ const [current, raw] = await Promise.all([
currentBranch(cwd).catch(() => 'HEAD'), currentBranch(root).catch(() => 'HEAD'),
runGit(cwd, ['for-each-ref', '--format=%(refname:short)', 'refs/heads']), runGit(root, ['for-each-ref', '--format=%(refname:short)', 'refs/heads']),
]) ])
const names = raw.split('\n').filter(line => line !== '') const names = raw.split('\n').filter(line => line !== '')
return { current, names: names.includes(current) ? names : [current, ...names] } return { current, names: names.includes(current) ? names : [current, ...names] }
} }
/** Switch to an existing branch. */ /** Switch to an existing branch. */
export async function checkout(cwd: string, branch: string): Promise<void> { export async function checkout(cwd: string, branch: string, selected?: string): Promise<void> {
await runGit(cwd, ['checkout', branch]) await runGit(await repoRoot(cwd, selected), ['checkout', branch])
} }
/** Recent commit history (newest first), lazily pageable via skip/count. */ /** Recent commit history (newest first), lazily pageable via skip/count. */
export async function log(cwd: string, count = 30, skip = 0): Promise<GitLogEntry[]> { export async function log(cwd: string, count = 30, skip = 0, selected?: string): Promise<GitLogEntry[]> {
const raw = await runGit(cwd, [ const raw = await runGit(await repoRoot(cwd, selected), [
'log', '-n', String(count), '--skip', String(skip), '--decorate=short', 'log', '-n', String(count), '--skip', String(skip), '--decorate=short',
'--pretty=format:%h%x1f%s%x1f%an%x1f%ai%x1f%H%x1f%D', '--pretty=format:%h%x1f%s%x1f%an%x1f%ai%x1f%H%x1f%D',
]) ])
@@ -205,9 +242,9 @@ export async function log(cwd: string, count = 30, skip = 0): Promise<GitLogEntr
* Content of a file at a revision (`git show <rev>:<path>`), or null when the * Content of a file at a revision (`git show <rev>:<path>`), or null when the
* revision has no such path (a new/untracked file has no HEAD side). * revision has no such path (a new/untracked file has no HEAD side).
*/ */
export async function show(cwd: string, rev: string, path: string): Promise<string | null> { export async function show(cwd: string, rev: string, path: string, selected?: string): Promise<string | null> {
try { try {
return await runGit(cwd, ['show', `${rev}:${path}`]) return await runGit(await repoRoot(cwd, selected), ['show', `${rev}:${path}`])
} catch { } catch {
return null return null
} }
@@ -216,21 +253,21 @@ export async function show(cwd: string, rev: string, path: string): Promise<stri
/** Full patch text of one commit (`git show` with the commit header suppressed). /** Full patch text of one commit (`git show` with the commit header suppressed).
* Merge commits show their diff against the first parent (`-m --first-parent` * Merge commits show their diff against the first parent (`-m --first-parent`
* is a no-op for regular commits), so a history click always has content. */ * is a no-op for regular commits), so a history click always has content. */
export async function commitDiff(cwd: string, hash: string): Promise<string> { export async function commitDiff(cwd: string, hash: string, selected?: string): Promise<string> {
return runGit(cwd, ['show', '--no-ext-diff', '--no-color', '--format=', '-m', '--first-parent', hash]) return runGit(await repoRoot(cwd, selected), ['show', '--no-ext-diff', '--no-color', '--format=', '-m', '--first-parent', hash])
} }
/** Discard the worktree changes of one path (`git checkout -- <path>`; the index is untouched). */ /** Discard the worktree changes of one path (`git checkout -- <path>`; the index is untouched). */
export async function discard(cwd: string, path: string): Promise<void> { export async function discard(cwd: string, path: string, selected?: string): Promise<void> {
await runGit(cwd, ['checkout', '--', path]) await runGit(await repoRoot(cwd, selected), ['checkout', '--', path])
} }
/** Revert one commit onto the current branch with an auto-generated message. */ /** Revert one commit onto the current branch with an auto-generated message. */
export async function revert(cwd: string, hash: string): Promise<void> { export async function revert(cwd: string, hash: string, selected?: string): Promise<void> {
await runGit(cwd, ['revert', '--no-edit', hash]) await runGit(await repoRoot(cwd, selected), ['revert', '--no-edit', hash])
} }
/** Cherry-pick one commit onto the current branch. */ /** Cherry-pick one commit onto the current branch. */
export async function cherryPick(cwd: string, hash: string): Promise<void> { export async function cherryPick(cwd: string, hash: string, selected?: string): Promise<void> {
await runGit(cwd, ['cherry-pick', hash]) await runGit(await repoRoot(cwd, selected), ['cherry-pick', hash])
} }
+27 -17
View File
@@ -118,6 +118,13 @@ function sessionCwdOf(ctx: Context, sessionId: string, clientCwd?: string): stri
return process.cwd() return process.cwd()
} }
/** Optional repository selected by the Git panel when cwd is a container. */
function selectedRepoOf(payload: unknown): string | undefined {
const record = payload as { repoRoot?: unknown }
if (record.repoRoot === undefined) return undefined
return requireAbsolute(requireString(payload, 'repoRoot'))
}
/** /**
* Resolve a path that a git command reported — `git status`/`git diff` * Resolve a path that a git command reported — `git status`/`git diff`
* print paths RELATIVE TO THE REPO TOP LEVEL, which may sit above the * print paths RELATIVE TO THE REPO TOP LEVEL, which may sit above the
@@ -125,9 +132,9 @@ function sessionCwdOf(ctx: Context, sessionId: string, clientCwd?: string): stri
* paths pass through; relative ones join the repo root (falling back to the * paths pass through; relative ones join the repo root (falling back to the
* cwd when the root cannot be resolved, e.g. a bare directory). * cwd when the root cannot be resolved, e.g. a bare directory).
*/ */
async function resolveGitPath(cwd: string, raw: string): Promise<string> { async function resolveGitPath(cwd: string, raw: string, selected?: string): Promise<string> {
if (isAbsolute(raw)) return requireAbsolute(raw) if (isAbsolute(raw)) return requireAbsolute(raw)
const root = await git.repoRoot(cwd).catch(() => cwd) const root = await git.repoRoot(cwd, selected).catch(() => cwd)
return requireAbsolute(join(root, raw)) return requireAbsolute(join(root, raw))
} }
@@ -284,41 +291,42 @@ function buildApi(
}, },
'git.status': async (payload) => { 'git.status': async (payload) => {
const { cwd } = cwdOf(payload) const { cwd } = cwdOf(payload)
return git.status(cwd) return git.status(cwd, selectedRepoOf(payload))
}, },
'git.diff': async (payload) => { 'git.diff': async (payload) => {
const { cwd } = cwdOf(payload) const { cwd } = cwdOf(payload)
const record = payload as { path?: unknown; staged?: unknown } const record = payload as { path?: unknown; staged?: unknown }
const path = record.path === undefined ? undefined : await resolveGitPath(cwd, requireString(payload, 'path')) const repoRoot = selectedRepoOf(payload)
return { diff: await git.diff(cwd, path, record.staged === true) } const path = record.path === undefined ? undefined : await resolveGitPath(cwd, requireString(payload, 'path'), repoRoot)
return { diff: await git.diff(cwd, path, record.staged === true, repoRoot) }
}, },
'git.stage': async (payload) => { 'git.stage': async (payload) => {
const { cwd } = cwdOf(payload) const { cwd } = cwdOf(payload)
const record = payload as { path?: unknown } const record = payload as { path?: unknown }
const path = record.path === undefined ? undefined : requireString(payload, 'path') const path = record.path === undefined ? undefined : requireString(payload, 'path')
await git.stage(cwd, path) await git.stage(cwd, path, selectedRepoOf(payload))
return { ok: true } return { ok: true }
}, },
'git.unstage': async (payload) => { 'git.unstage': async (payload) => {
const { cwd } = cwdOf(payload) const { cwd } = cwdOf(payload)
const record = payload as { path?: unknown } const record = payload as { path?: unknown }
const path = record.path === undefined ? undefined : requireString(payload, 'path') const path = record.path === undefined ? undefined : requireString(payload, 'path')
await git.unstage(cwd, path) await git.unstage(cwd, path, selectedRepoOf(payload))
return { ok: true } return { ok: true }
}, },
'git.commit': async (payload) => { 'git.commit': async (payload) => {
const { cwd } = cwdOf(payload) const { cwd } = cwdOf(payload)
const message = requireString(payload, 'message') const message = requireString(payload, 'message')
await git.commit(cwd, message) await git.commit(cwd, message, selectedRepoOf(payload))
return { ok: true } return { ok: true }
}, },
'git.branch': async (payload) => { 'git.branch': async (payload) => {
const { cwd } = cwdOf(payload) const { cwd } = cwdOf(payload)
return git.branches(cwd) return git.branches(cwd, selectedRepoOf(payload))
}, },
'git.checkout': async (payload) => { 'git.checkout': async (payload) => {
const { cwd } = cwdOf(payload) const { cwd } = cwdOf(payload)
await git.checkout(cwd, requireString(payload, 'branch')) await git.checkout(cwd, requireString(payload, 'branch'), selectedRepoOf(payload))
return { ok: true } return { ok: true }
}, },
'git.log': async (payload) => { 'git.log': async (payload) => {
@@ -330,32 +338,34 @@ function buildApi(
const skip = typeof record.skip === 'number' && Number.isInteger(record.skip) && record.skip >= 0 const skip = typeof record.skip === 'number' && Number.isInteger(record.skip) && record.skip >= 0
? record.skip ? record.skip
: undefined : undefined
return git.log(cwd, count, skip) return git.log(cwd, count, skip, selectedRepoOf(payload))
}, },
'git.commit-diff': async (payload) => { 'git.commit-diff': async (payload) => {
const { cwd } = cwdOf(payload) const { cwd } = cwdOf(payload)
return { diff: await git.commitDiff(cwd, requireString(payload, 'hash')) } return { diff: await git.commitDiff(cwd, requireString(payload, 'hash'), selectedRepoOf(payload)) }
}, },
'git.discard': async (payload) => { 'git.discard': async (payload) => {
const { cwd } = cwdOf(payload) const { cwd } = cwdOf(payload)
await git.discard(cwd, await resolveGitPath(cwd, requireString(payload, 'path'))) const repoRoot = selectedRepoOf(payload)
await git.discard(cwd, await resolveGitPath(cwd, requireString(payload, 'path'), repoRoot), repoRoot)
return { ok: true } return { ok: true }
}, },
'git.revert': async (payload) => { 'git.revert': async (payload) => {
const { cwd } = cwdOf(payload) const { cwd } = cwdOf(payload)
await git.revert(cwd, requireString(payload, 'hash')) await git.revert(cwd, requireString(payload, 'hash'), selectedRepoOf(payload))
return { ok: true } return { ok: true }
}, },
'git.cherry-pick': async (payload) => { 'git.cherry-pick': async (payload) => {
const { cwd } = cwdOf(payload) const { cwd } = cwdOf(payload)
await git.cherryPick(cwd, requireString(payload, 'hash')) await git.cherryPick(cwd, requireString(payload, 'hash'), selectedRepoOf(payload))
return { ok: true } return { ok: true }
}, },
'git.show': async (payload) => { 'git.show': async (payload) => {
const { cwd } = cwdOf(payload) const { cwd } = cwdOf(payload)
const path = await resolveGitPath(cwd, requireString(payload, 'path')) const repoRoot = selectedRepoOf(payload)
const path = await resolveGitPath(cwd, requireString(payload, 'path'), repoRoot)
const rev = requireString(payload, 'rev') const rev = requireString(payload, 'rev')
return { content: await git.show(cwd, rev, path) } return { content: await git.show(cwd, rev, path, repoRoot) }
}, },
// Release a terminal immediately. The WebSocket close frame already does // Release a terminal immediately. The WebSocket close frame already does
// this while the socket is open; this route covers the tab-close that // this while the socket is open; this route covers the tab-close that
+31 -1
View File
@@ -1,8 +1,38 @@
import { execFile } from 'node:child_process'
import { mkdir, mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { promisify } from 'node:util'
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { parseUnifiedDiff } from '../src/client/DiffView.tsx' import { parseUnifiedDiff } from '../src/client/DiffView.tsx'
import { parseLogLines, parsePorcelainZ } from '../src/git.ts' import { parseLogLines, parsePorcelainZ, repoRoots, status } from '../src/git.ts'
const execFileAsync = promisify(execFile)
const normalizePath = (path: string): string => path.replaceAll('\\', '/')
describe('git parsing', () => { describe('git parsing', () => {
it('discovers and selects direct child repositories under a workspace directory', async () => {
const workspace = await mkdtemp(join(tmpdir(), 'dsh-better-sidebar-git-'))
const first = join(workspace, 'first-repo')
const second = join(workspace, 'second-repo')
try {
await Promise.all([mkdir(first), mkdir(second)])
await Promise.all([
execFileAsync('git', ['-C', first, 'init']),
execFileAsync('git', ['-C', second, 'init']),
])
await expect(repoRoots(workspace)).resolves.toEqual([normalizePath(first), normalizePath(second)])
await expect(status(workspace, normalizePath(second))).resolves.toMatchObject({
isRepo: true,
root: normalizePath(second),
repositories: [normalizePath(first), normalizePath(second)],
})
} finally {
await rm(workspace, { recursive: true, force: true })
}
})
it('parses porcelain -z entries including renames', () => { it('parses porcelain -z entries including renames', () => {
const output = ['M src/a.ts', ' M src/b.ts', '?? src/c.ts', 'R src/new.ts', 'src/old.ts', ''].join('\0') const output = ['M src/a.ts', ' M src/b.ts', '?? src/c.ts', 'R src/new.ts', 'src/old.ts', ''].join('\0')
const entries = parsePorcelainZ(output) const entries = parsePorcelainZ(output)