feat(git): replace Git interior with SCM changes and parent graph
This commit is contained in:
1 parent
fc09a72f3f
commit
f0ce77b401
30 files changed
+1238
-412
No files matched your search
@@ -79,7 +79,15 @@ export interface GitStatusEntry {
|
||||
/** Git status snapshot. */
|
||||
export interface GitStatusResult {
|
||||
isRepo: boolean
|
||||
/** Absent when HEAD is detached; unborn branches keep their real name. */
|
||||
branch?: string
|
||||
/** Native tracking ref (e.g. origin/main); never inferred from a remote. */
|
||||
upstream?: string
|
||||
/** Present only when Git can compare HEAD with the tracking ref. */
|
||||
ahead?: number
|
||||
behind?: number
|
||||
detached?: boolean
|
||||
operation?: 'merge' | 'rebase'
|
||||
entries: GitStatusEntry[]
|
||||
/** True when the host capped `entries` (huge untracked set); the panel
|
||||
* shows a truncation notice instead of freezing (#369). */
|
||||
@@ -138,6 +146,8 @@ export interface GitLogEntry {
|
||||
hash: string
|
||||
/** Full 40-char hash (advanced operations). */
|
||||
hashFull: string
|
||||
/** Full parent hashes in Git's order; root commits have none. */
|
||||
parents: string[]
|
||||
subject: string
|
||||
author: string
|
||||
/** ISO 8601 author date (`%ai`). */
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Native SVG parent-frontier graph. Reference inspected: microsoft/vscode
|
||||
* 76f9f309edc0682f4ef9465be8d12af754b87236 (MIT),
|
||||
* src/vs/workbench/contrib/scm/browser/scmHistory.ts. Independently implemented;
|
||||
* no upstream implementation copied. Full parent hashes, not ref decorations,
|
||||
* determine every edge, including parents beyond the loaded history page.
|
||||
*/
|
||||
import { useMemo, type MouseEvent, type ReactNode } from 'react'
|
||||
import type { GitLogEntry } from '../api.ts'
|
||||
import css from './changes.module.css'
|
||||
|
||||
const HEIGHT = 22
|
||||
const STEP = 11
|
||||
const COLORS = [
|
||||
'var(--dsw-alias-brand-primary)',
|
||||
'var(--dsw-alias-state-success-primary)',
|
||||
'var(--dsw-alias-state-warn-primary)',
|
||||
'var(--dsw-alias-state-business-primary)',
|
||||
]
|
||||
|
||||
type Lane = { hash: string; child: string; color: string }
|
||||
type GraphPath = { d: string; child: string; parent: string; color: string }
|
||||
type GraphRow = { lane: number; color: string; input: Lane[]; output: Lane[]; paths: GraphPath[] }
|
||||
|
||||
function curve(from: number, fromY: number, to: number, toY: number): string {
|
||||
const x1 = (from + 1) * STEP
|
||||
const x2 = (to + 1) * STEP
|
||||
if (from === to) return `M ${x1} ${fromY} L ${x2} ${toY}`
|
||||
const middle = (fromY + toY) / 2
|
||||
return `M ${x1} ${fromY} C ${x1} ${middle}, ${x2} ${middle}, ${x2} ${toY}`
|
||||
}
|
||||
|
||||
/** Newest-first, topological rows. Duplicate targets join only at their commit. */
|
||||
export function layoutGraph(entries: readonly GitLogEntry[]): GraphRow[] {
|
||||
let frontier: Lane[] = []
|
||||
let nextColor = 0
|
||||
const color = (): string => COLORS[nextColor++ % COLORS.length]!
|
||||
|
||||
return entries.map(entry => {
|
||||
const input = frontier
|
||||
const match = input.findIndex(lane => lane.hash === entry.hashFull)
|
||||
const lane = match < 0 ? input.length : match
|
||||
const nodeColor = input[match]?.color ?? color()
|
||||
const output: Lane[] = []
|
||||
const paths: GraphPath[] = []
|
||||
const firstParent = entry.parents[0]
|
||||
const addParent = (parent: string, parentColor: string): void => {
|
||||
paths.push({
|
||||
d: curve(lane, HEIGHT / 2, output.length, HEIGHT),
|
||||
child: entry.hashFull, parent, color: parentColor,
|
||||
})
|
||||
output.push({ hash: parent, child: entry.hashFull, color: parentColor })
|
||||
}
|
||||
|
||||
input.forEach((edge, index) => {
|
||||
if (edge.hash === entry.hashFull) {
|
||||
paths.push({
|
||||
d: curve(index, 0, lane, HEIGHT / 2),
|
||||
child: edge.child, parent: edge.hash, color: edge.color,
|
||||
})
|
||||
if (index === match && firstParent) addParent(firstParent, nodeColor)
|
||||
} else {
|
||||
paths.push({
|
||||
d: curve(index, 0, output.length, HEIGHT),
|
||||
child: edge.child, parent: edge.hash, color: edge.color,
|
||||
})
|
||||
output.push(edge)
|
||||
}
|
||||
})
|
||||
if (match < 0 && firstParent) addParent(firstParent, nodeColor)
|
||||
for (const parent of entry.parents.slice(1)) addParent(parent, color())
|
||||
|
||||
frontier = output
|
||||
return { lane, color: nodeColor, input, output, paths }
|
||||
})
|
||||
}
|
||||
|
||||
export function GitGraph({ entries, selectedHash, onPreview, onContextMenu }: {
|
||||
entries: readonly GitLogEntry[]
|
||||
selectedHash?: string
|
||||
onPreview: (entry: GitLogEntry) => void
|
||||
onContextMenu: (event: MouseEvent, entry: GitLogEntry) => void
|
||||
}): ReactNode {
|
||||
const rows = useMemo(() => layoutGraph(entries), [entries])
|
||||
const laneCount = rows.reduce((max, row) => Math.max(max, row.lane + 1, row.input.length, row.output.length), 1)
|
||||
const width = (laneCount + 1) * STEP
|
||||
|
||||
return entries.map((entry, index) => {
|
||||
const row = rows[index]!
|
||||
const refs = [...new Set(entry.refs.split(',').flatMap(ref => ref.trim().split(' -> ')).filter(Boolean))]
|
||||
return (
|
||||
<div
|
||||
key={entry.hashFull}
|
||||
role="button"
|
||||
aria-pressed={selectedHash === entry.hashFull}
|
||||
tabIndex={0}
|
||||
className={css.logRow}
|
||||
data-graph-row={entry.hashFull}
|
||||
data-hash={entry.hashFull}
|
||||
data-selected={selectedHash === entry.hashFull ? 'true' : undefined}
|
||||
title={`${entry.author} · ${entry.date}\n${entry.hashFull}`}
|
||||
onClick={() => { onPreview(entry) }}
|
||||
onContextMenu={event => { event.preventDefault(); onContextMenu(event, entry) }}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
onPreview(entry)
|
||||
} else if (event.key === 'ContextMenu' || (event.key === 'F10' && event.shiftKey)) {
|
||||
event.preventDefault()
|
||||
const bounds = event.currentTarget.getBoundingClientRect()
|
||||
event.currentTarget.dispatchEvent(new window.MouseEvent('contextmenu', {
|
||||
bubbles: true, cancelable: true,
|
||||
clientX: bounds.left + bounds.width / 2, clientY: bounds.bottom,
|
||||
}))
|
||||
}
|
||||
}}
|
||||
>
|
||||
<svg className={css.graphSvg} width={width} height={HEIGHT} viewBox={`0 0 ${width} ${HEIGHT}`} preserveAspectRatio="none" aria-hidden="true" focusable="false">
|
||||
{row.paths.map((path, pathIndex) => (
|
||||
<path
|
||||
key={pathIndex}
|
||||
d={path.d}
|
||||
data-child={path.child}
|
||||
data-parent={path.parent}
|
||||
stroke={path.color}
|
||||
strokeWidth={1.5}
|
||||
fill="none"
|
||||
/>
|
||||
))}
|
||||
<circle cx={(row.lane + 1) * STEP} cy={HEIGHT / 2} r={3.5} fill={row.color} data-node={entry.hashFull} />
|
||||
</svg>
|
||||
<span className={css.graphContent}>
|
||||
{refs.length > 0 && <span className={css.logRefs}>
|
||||
{refs.map(ref => <span key={ref} className={css.logRef}>{ref}</span>)}
|
||||
</span>}
|
||||
<span className={css.logSubject}>{entry.subject}</span>
|
||||
<span className={css.logMeta}>{entry.author}</span>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
}
|
||||
+265
-297
@@ -1,35 +1,17 @@
|
||||
/**
|
||||
* The Git lens of the changes tab: repository truth — the changed files
|
||||
* (unstaged / staged) as a directory tree, stage/unstage, commit with a
|
||||
* message box, branch and checkout switching, and a VSCode-like history with
|
||||
* decorations, author and relative time. Clicking a changed file or a history
|
||||
* row previews it in the tab's shared bottom pane (see {@link DiffPane}); rows
|
||||
* carry right-click context menus with advanced operations (open in editor,
|
||||
* discard, revert, cherry-pick, copy paths/hashes).
|
||||
* Source Control inside the unchanged changes-tab shell: independent Changes
|
||||
* and Graph disclosures, a draft above the resource groups, and a sticky
|
||||
* checkout/sync footer. Status still comes from the one shared Git poller;
|
||||
* mutations, worktree inventory and history reuse the existing host routes.
|
||||
*
|
||||
* The change list is a TREE, not a flat list: {@link buildChangeTree} folds
|
||||
* each group's paths into directories (single-child chains compressed), so a
|
||||
* nested change reads as structure instead of as a wall of rows. Directory
|
||||
* rows disclose their subtree (`aria-expanded`); file rows carry the host's
|
||||
* own file artwork, the porcelain letter and the trailing stage action, which
|
||||
* only shows on hover/focus to keep the row quiet.
|
||||
*
|
||||
* The git status itself is NOT fetched here: it comes from the plugin's one
|
||||
* shared store (`ui/git-status.ts`), which the file tree also subscribes to,
|
||||
* so both surfaces color/lists the same answer from a single poller. This
|
||||
* component owns the checkout-derived surfaces a status call cannot answer
|
||||
* (worktree inventory, branch choices, history) and every mutation.
|
||||
*
|
||||
* Two error channels, one each: the commit bar owns its single status line
|
||||
* (commit / stage / discard / revert failures), and the lens owns the top
|
||||
* banner (refresh, branch switch, history paging). Branch and history
|
||||
* failures used to land under the commit box, which read as "your commit
|
||||
* failed" for an action the user never ran.
|
||||
* UI semantics reference: VS Code 76f9f309edc0682f4ef9465be8d12af754b87236,
|
||||
* extensions/git and src/vs/workbench/contrib/scm (not a runtime dependency).
|
||||
*/
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode } from 'react'
|
||||
import {
|
||||
Button, IconChevronRightOutlineRegular, IconCodeOutlineRegular, IconCopyOutlineRegular, IconPlusOutlineRegular,
|
||||
IconSparkleRegular, IconTrashOutlineRegular, Menu, writeClipboard,
|
||||
Button, IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronRightOutlineRegular,
|
||||
IconCodeOutlineRegular, IconCopyOutlineRegular, IconEllipsisOutlineRegular, IconPlusOutlineRegular,
|
||||
IconRefreshOutlineRegular, IconSparkleRegular, IconTrashOutlineRegular, Menu, writeClipboard,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { Context } from '../../context-types.ts'
|
||||
import type { GitLineCounts, GitLogEntry, GitStatusEntry, GitStatusResult, GitWorktree, SessionScope } from '../api.ts'
|
||||
@@ -38,7 +20,8 @@ import { builtinFileIcon, builtinFolderIcon } from '../file-icons.tsx'
|
||||
import { usePolling } from '../use-polling.ts'
|
||||
import { baseName, relativeTo } from '../paths.ts'
|
||||
import { resolveSidebarPath } from '../paths.ts'
|
||||
import { isZh, relativeTime, t } from '../locales.ts'
|
||||
import { isZh, t } from '../locales.ts'
|
||||
import { GitGraph } from './GitGraph.tsx'
|
||||
import type { SidebarDiffRef, SidebarStore } from '../state.ts'
|
||||
import {
|
||||
ConfirmDialog, IconButton, Notice, SectionHeader, StatusBadge, invalidateGitStatus, statusOfXY,
|
||||
@@ -77,18 +60,6 @@ const BADGE_TONE: Record<GitTone, StatusTone> = {
|
||||
conflict: 'conflict',
|
||||
}
|
||||
|
||||
/** The ref names of one log row's decorations (`HEAD -> main` → `main`), deduped. */
|
||||
function refNames(refs: string): string[] {
|
||||
return [...new Set(
|
||||
refs
|
||||
.split(',')
|
||||
.map(ref => ref.trim())
|
||||
.filter(ref => ref !== '')
|
||||
.map(ref => (ref.includes(' -> ') ? ref.slice(ref.indexOf(' -> ') + 4) : ref))
|
||||
.map(ref => (ref.startsWith('tag: ') ? ref.slice(5) : ref)),
|
||||
)]
|
||||
}
|
||||
|
||||
/** One thrown value as display text (every error line here normalizes through
|
||||
* this so non-Error rejections never render as '[object Object]'). */
|
||||
function errorMessage(reason: unknown): string {
|
||||
@@ -226,8 +197,9 @@ const FileRow = memo(function FileRow(props: {
|
||||
onContextMenu={(event) => { props.onContextMenu(event, node, staged) }}
|
||||
>
|
||||
<span className={css.rowIcon} aria-hidden="true">{props.glyph(node.path)}</span>
|
||||
<StatusBadge tone={BADGE_TONE[node.status.tone]} title={node.path}>{node.status.letter}</StatusBadge>
|
||||
<span className={css.rowName}>{node.name}</span>
|
||||
<span className={css.rowPath}>{node.path.slice(0, -node.name.length).replace(/[\\/]+$/, '') || '/'}</span>
|
||||
<StatusBadge tone={BADGE_TONE[node.status.tone]} title={node.path}>{node.status.letter}</StatusBadge>
|
||||
{/* The row's own line counts (#131): read straight off the node, so a
|
||||
poll that answered different numbers re-renders this row with them. */}
|
||||
<LineCounts counts={node.counts} untracked={node.status.tone === 'untracked'} />
|
||||
@@ -338,7 +310,12 @@ export function GitLens(props: GitLensProps) {
|
||||
const [logEntries, setLogEntries] = useState<GitLogEntry[]>([])
|
||||
/** Whether the history was fully paged (a batch shorter than LOG_BATCH). */
|
||||
const [logEnded, setLogEnded] = useState(false)
|
||||
const [logLoading, setLogLoading] = useState(false)
|
||||
const [logLoadingMore, setLogLoadingMore] = useState(false)
|
||||
const [changesOpen, setChangesOpen] = useState(true)
|
||||
const [graphOpen, setGraphOpen] = useState(true)
|
||||
const [moreOpen, setMoreOpen] = useState(false)
|
||||
const [branchOpen, setBranchOpen] = useState(false)
|
||||
/** The history's own failure state: an empty list must not claim "no commits"
|
||||
* when the log call failed. */
|
||||
const [logFailed, setLogFailed] = useState(false)
|
||||
@@ -348,12 +325,16 @@ export function GitLens(props: GitLensProps) {
|
||||
* kept-mounted tab shows a conversation its own message when it comes back
|
||||
* (#712). */
|
||||
const [commitDrafts, setCommitDrafts] = useState<Record<string, string>>({})
|
||||
const draftKey = `${scope.sessionId}\u0000${scope.cwd ?? ''}`
|
||||
// Primary selection canonicalizes to "" so the initial inventory cannot
|
||||
// move a just-typed draft to a different key; linked checkouts stay isolated.
|
||||
const draftWorktree = selectedWorktree === worktrees.find(entry => entry.current)?.path ? '' : selectedWorktree ?? ''
|
||||
const draftKey = `${scope.sessionId}\u0000${scope.cwd ?? ''}\u0000${repoRoot ?? ''}\u0000${draftWorktree}`
|
||||
const commitMsg = commitDrafts[draftKey] ?? ''
|
||||
const writeDraft = (text: string): void => {
|
||||
setCommitDrafts(prev => ({ ...prev, [draftKey]: text }))
|
||||
}
|
||||
const [busy, setBusy] = useState(false)
|
||||
const actionLock = useRef<symbol | null>(null)
|
||||
/** Whether a commit-message suggestion is being generated host-side (the
|
||||
* host streams the diff through the harness LLM — no agent is spawned). */
|
||||
const [suggesting, setSuggesting] = useState(false)
|
||||
@@ -375,8 +356,8 @@ export function GitLens(props: GitLensProps) {
|
||||
const next = Math.min(box.scrollHeight, max)
|
||||
box.style.height = `${next}px`
|
||||
box.style.overflowY = box.scrollHeight > max ? 'auto' : 'hidden'
|
||||
}, [commitMsg])
|
||||
/** The commit bar's ONE status line (commit / stage / discard / revert). */
|
||||
}, [commitMsg, changesOpen, visible])
|
||||
/** One footer status channel for generation and Git mutations. */
|
||||
const [actionError, setActionError] = useState<string | null>(null)
|
||||
/** The lens-level error banner (refresh / branch switch / history paging). */
|
||||
const [viewError, setViewError] = useState<string | null>(null)
|
||||
@@ -464,18 +445,30 @@ export function GitLens(props: GitLensProps) {
|
||||
|
||||
/** Drop every checkout-derived surface before another one loads. */
|
||||
const clearDerived = (): void => {
|
||||
scopeGen.current += 1
|
||||
actionLock.current = null
|
||||
setBusy(false)
|
||||
setSuggesting(false)
|
||||
setCommitting(false)
|
||||
setBranchNames([])
|
||||
setLogEntries([])
|
||||
setLogEnded(false)
|
||||
setLogLoading(false)
|
||||
setLogLoadingMore(false)
|
||||
setLogFailed(false)
|
||||
setActionError(null)
|
||||
setFileMenu(null)
|
||||
setHistoryMenu(null)
|
||||
setConfirm(null)
|
||||
setMoreOpen(false)
|
||||
setBranchOpen(false)
|
||||
}
|
||||
|
||||
/** Load the branch choices and the first history page of one checkout. */
|
||||
const loadTarget = useCallback(async (target: string | undefined): Promise<void> => {
|
||||
const generation = scopeGen.current
|
||||
const gitScope = gitScopeNow()
|
||||
setLogLoading(true)
|
||||
const [branchResult, logResult] = await Promise.all([
|
||||
api.gitBranch(gitScope, target).catch(() => ({ current: '', names: [] as string[] })),
|
||||
api.gitLog(gitScope, LOG_BATCH, 0, target).then(
|
||||
@@ -483,7 +476,8 @@ export function GitLens(props: GitLensProps) {
|
||||
() => ({ entries: [] as GitLogEntry[], failed: true }),
|
||||
),
|
||||
])
|
||||
if (generation !== scopeGen.current) return
|
||||
if (generation !== scopeGen.current || target !== chosenPathRef.current) return
|
||||
setLogLoading(false)
|
||||
setBranchNames(branchResult.names)
|
||||
setLogEntries(logResult.entries)
|
||||
setLogEnded(logResult.entries.length < LOG_BATCH)
|
||||
@@ -615,25 +609,33 @@ export function GitLens(props: GitLensProps) {
|
||||
const pollInventory = useCallback((signal: AbortSignal): Promise<void> => refresh(true, signal), [refresh])
|
||||
usePolling(visible, pollInventory, { intervalMs: WORKTREE_POLL_MS, mode: 'self-scheduling' })
|
||||
|
||||
/** Run one mutating git action: lock the bar, refresh the shared status and
|
||||
* the derived surfaces on success, and report the failure in the commit
|
||||
* bar's single status line (never as an unhandled rejection). */
|
||||
/** Lock one target's mutation and refresh even a partially failed sync. */
|
||||
const runAction = async (
|
||||
action: () => Promise<unknown>,
|
||||
failure: (reason: unknown) => string = errorMessage,
|
||||
onSuccess?: () => void,
|
||||
): Promise<void> => {
|
||||
if (actionLock.current !== null) return
|
||||
const lock = Symbol()
|
||||
actionLock.current = lock
|
||||
const generation = scopeGen.current
|
||||
const sessionId = scope.sessionId
|
||||
setBusy(true)
|
||||
setActionError(null)
|
||||
try {
|
||||
await action()
|
||||
onSuccess?.()
|
||||
invalidateGitStatus(scope.sessionId)
|
||||
await refresh(false)
|
||||
} catch (reason) {
|
||||
setActionError(failure(reason))
|
||||
if (generation === scopeGen.current) setActionError(failure(reason))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
// A Pull can succeed before Push fails: refresh on failure too.
|
||||
invalidateGitStatus(sessionId)
|
||||
if (generation === scopeGen.current) await refresh(false)
|
||||
if (actionLock.current === lock) {
|
||||
actionLock.current = null
|
||||
setBusy(false)
|
||||
setCommitting(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -651,22 +653,27 @@ export function GitLens(props: GitLensProps) {
|
||||
)
|
||||
}
|
||||
|
||||
const stageAll = (staged: boolean): void => {
|
||||
void runAction(
|
||||
() => (staged ? api.gitUnstage(gitScopeNow(), undefined, selectedWorktree) : api.gitStage(gitScopeNow(), undefined, selectedWorktree)),
|
||||
stageError,
|
||||
)
|
||||
const stageAll = (staged: boolean, merge = false): void => {
|
||||
const gitScope = gitScopeNow()
|
||||
const target = selectedWorktree
|
||||
void runAction(async () => {
|
||||
if (!staged && mergeEntries.length > 0) {
|
||||
// Separate Merge/Changes groups must not stage each other's files.
|
||||
for (const entry of merge ? mergeEntries : unstagedEntries) await api.gitStage(gitScope, entry.path, target)
|
||||
} else if (staged) await api.gitUnstage(gitScope, undefined, target)
|
||||
else await api.gitStage(gitScope, undefined, target)
|
||||
}, stageError)
|
||||
}
|
||||
|
||||
const commit = (): void => {
|
||||
const message = commitMsg.trim()
|
||||
if (message === '' || busy || suggesting) return
|
||||
if (!canCommit || actionLock.current) return
|
||||
setCommitting(true)
|
||||
void runAction(
|
||||
() => api.gitCommit(gitScopeNow(), message, selectedWorktree),
|
||||
errorMessage,
|
||||
() => { writeDraft('') },
|
||||
).finally(() => { setCommitting(false) })
|
||||
)
|
||||
}
|
||||
|
||||
/** The generate button's label/tooltip: names the model when one resolves,
|
||||
@@ -678,20 +685,27 @@ export function GitLens(props: GitLensProps) {
|
||||
/** Ask the host to draft a commit message from the pending changes, then
|
||||
* fill the message box (still editable; regenerating is allowed). */
|
||||
const suggestMessage = async (): Promise<void> => {
|
||||
if (busy || suggesting) return
|
||||
if (actionLock.current !== null || entries.length === 0) return
|
||||
const lock = Symbol()
|
||||
actionLock.current = lock
|
||||
const generation = scopeGen.current
|
||||
setSuggesting(true)
|
||||
setActionError(null)
|
||||
try {
|
||||
const { message } = await api.gitSuggestMessage(gitScopeNow(), isZh() ? 'zh' : 'en', selectedWorktree)
|
||||
writeDraft(message)
|
||||
if (generation === scopeGen.current) writeDraft(message)
|
||||
} catch (reason) {
|
||||
if (generation !== scopeGen.current) return
|
||||
if (reason instanceof SidebarApiError && reason.code === 'git-suggest-empty') {
|
||||
setActionError(t('suggestCommitEmpty'))
|
||||
} else {
|
||||
setActionError(`${t('suggestCommitError')}: ${errorMessage(reason)}`)
|
||||
}
|
||||
} finally {
|
||||
setSuggesting(false)
|
||||
if (actionLock.current === lock) {
|
||||
actionLock.current = null
|
||||
setSuggesting(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -708,6 +722,16 @@ export function GitLens(props: GitLensProps) {
|
||||
void runAction(() => api.gitPull(gitScopeNow(), selectedWorktree), pullError)
|
||||
}
|
||||
|
||||
const sync = (): void => {
|
||||
if (!canSync) return
|
||||
const gitScope = gitScopeNow()
|
||||
const target = selectedWorktree
|
||||
void runAction(async () => {
|
||||
try { await api.gitPull(gitScope, target) } catch (reason) { throw new Error(pullError(reason)) }
|
||||
try { await api.gitPush(gitScope, target) } catch (reason) { throw new Error(pushError(reason)) }
|
||||
})
|
||||
}
|
||||
|
||||
/** Switching the selected checkout changes which rows are legitimate to act
|
||||
* on: clear the derived surfaces before the asynchronous refresh resolves
|
||||
* so a stale history row can never run over the new checkout's repository. */
|
||||
@@ -736,17 +760,23 @@ export function GitLens(props: GitLensProps) {
|
||||
}
|
||||
|
||||
const checkout = async (branch: string): Promise<void> => {
|
||||
if (branch === (snapshot?.branch ?? '') || busy) return
|
||||
if (branch === (snapshot?.branch ?? '') || actionLock.current !== null) return
|
||||
const lock = Symbol()
|
||||
actionLock.current = lock
|
||||
const generation = scopeGen.current
|
||||
setBusy(true)
|
||||
setViewError(null)
|
||||
try {
|
||||
await api.gitCheckout(gitScopeNow(), branch, selectedWorktree)
|
||||
invalidateGitStatus(scope.sessionId)
|
||||
await refresh(false)
|
||||
if (generation === scopeGen.current) await refresh(false)
|
||||
} catch (reason) {
|
||||
setViewError(`${t('checkoutError')}: ${errorMessage(reason)}`)
|
||||
if (generation === scopeGen.current) setViewError(`${t('checkoutError')}: ${errorMessage(reason)}`)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
if (actionLock.current === lock) {
|
||||
actionLock.current = null
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -819,14 +849,21 @@ export function GitLens(props: GitLensProps) {
|
||||
const contentKey = useMemo(() => entriesKey(entries), [entries])
|
||||
// One fold per group, rebuilt only when the change list's CONTENT changes —
|
||||
// never on a poll that answered the same files, however fresh its arrays are.
|
||||
const { stagedEntries, unstagedEntries, stagedTree, unstagedTree } = useMemo(() => {
|
||||
const staged = entries.filter(isStagedEntry)
|
||||
const unstaged = entries.filter(isUnstagedEntry)
|
||||
const { mergeEntries, stagedEntries, unstagedEntries, mergeTree, stagedTree, unstagedTree } = useMemo(() => {
|
||||
const merge = entries.filter(entry => statusOfXY(entry.xy)?.tone === 'conflict')
|
||||
const regular = entries.filter(entry => statusOfXY(entry.xy)?.tone !== 'conflict')
|
||||
const staged = regular.filter(isStagedEntry)
|
||||
const unstaged = regular.filter(isUnstagedEntry)
|
||||
const sideEntries = (rows: GitStatusEntry[], index: number): GitStatusEntry[] => rows.map(entry => ({
|
||||
...entry, xy: entry.xy === '??' ? '??' : index === 0 ? `${entry.xy[0]} ` : ` ${entry.xy[1]}`,
|
||||
}))
|
||||
return {
|
||||
mergeEntries: merge,
|
||||
stagedEntries: staged,
|
||||
unstagedEntries: unstaged,
|
||||
stagedTree: buildChangeTree(staged),
|
||||
unstagedTree: buildChangeTree(unstaged),
|
||||
mergeTree: buildChangeTree(merge),
|
||||
stagedTree: buildChangeTree(sideEntries(staged, 0)),
|
||||
unstagedTree: buildChangeTree(sideEntries(unstaged, 1)),
|
||||
}
|
||||
// The key stands in for `entries`: same content ⇒ same tree objects ⇒ the
|
||||
// memoized rows below keep their props and never re-render.
|
||||
@@ -838,8 +875,20 @@ export function GitLens(props: GitLensProps) {
|
||||
const stagedTotal = useMemo(() => sumLineCounts(stagedTree), [stagedTree])
|
||||
const isRepo = snapshot?.isRepo === true
|
||||
const branch = snapshot?.branch ?? ''
|
||||
const branchOptions = branch === '' ? branchNames : [branch, ...branchNames.filter(name => name !== branch)]
|
||||
const clean = isRepo && stagedEntries.length === 0 && unstagedEntries.length === 0
|
||||
const clean = isRepo && entries.length === 0
|
||||
const canCommit = isRepo && !busy && !suggesting && mergeEntries.length === 0
|
||||
&& stagedEntries.length > 0 && commitMsg.trim() !== ''
|
||||
const branchLabel = branch || t('gitDetached')
|
||||
const branchMarkers = `${unstagedEntries.length > 0 ? '*' : ''}${stagedEntries.length > 0 ? '+' : ''}${snapshot?.operation !== undefined || mergeEntries.length > 0 ? '!' : ''}`
|
||||
const shortcut = /Mac|iPhone|iPad/.test(globalThis.navigator?.platform ?? '') ? 'Cmd+Enter' : 'Ctrl+Enter'
|
||||
const messagePlaceholder = t('commitPlaceholder', { branch: branchLabel, shortcut })
|
||||
const canSync = isRepo && !busy && !suggesting && branch !== '' && snapshot?.detached !== true
|
||||
&& snapshot?.upstream !== undefined && snapshot.ahead !== undefined && snapshot.behind !== undefined
|
||||
&& snapshot.operation === undefined && mergeEntries.length === 0
|
||||
const syncLabel = snapshot?.detached === true || branch === '' ? t('gitDetached')
|
||||
: snapshot?.upstream === undefined ? t('gitNoUpstream')
|
||||
: snapshot.ahead === undefined || snapshot.behind === undefined ? t('gitSyncUnavailable')
|
||||
: `${t('gitSync')}: ${snapshot.upstream} · ${snapshot.behind}↓ ${snapshot.ahead}↑`
|
||||
|
||||
/** Fold or unfold one directory row (keyed per group, see `collapsed`).
|
||||
* Stable: it is a memoized row's prop. */
|
||||
@@ -888,7 +937,7 @@ export function GitLens(props: GitLensProps) {
|
||||
row={node}
|
||||
glyph={fileGlyph}
|
||||
staged={staged}
|
||||
busy={busy}
|
||||
busy={busy || suggesting}
|
||||
selected={isPreviewedWorktree(node.path, staged)}
|
||||
onPreview={previewFile}
|
||||
onContextMenu={openRowMenu}
|
||||
@@ -907,7 +956,7 @@ export function GitLens(props: GitLensProps) {
|
||||
folderGlyph={folderGlyph}
|
||||
staged={staged}
|
||||
open={open}
|
||||
busy={busy}
|
||||
busy={busy || suggesting}
|
||||
onToggle={toggleDir}
|
||||
onToggleStage={stagePath}
|
||||
/>
|
||||
@@ -929,55 +978,7 @@ export function GitLens(props: GitLensProps) {
|
||||
|
||||
return (
|
||||
<div className={css.git} data-git-root>
|
||||
{/* The non-scrolling head: the branch / repository / worktree band stays
|
||||
on screen while the change list and the history scroll under it
|
||||
(#194). */}
|
||||
{(repoChoices.length > 1 || worktrees.length > 1 || branch !== '') && (
|
||||
<div className={css.selectors} data-git-head>
|
||||
{repoChoices.length > 1 && (
|
||||
<select
|
||||
className={css.select}
|
||||
value={repoRoot ?? ''}
|
||||
title={repoRoot}
|
||||
disabled={busy}
|
||||
onChange={(event) => { chooseRepo(event.target.value) }}
|
||||
>
|
||||
{repoChoices.map(root => <option key={root} value={root}>{baseName(root)}</option>)}
|
||||
</select>
|
||||
)}
|
||||
{worktrees.length > 1 && (
|
||||
<select
|
||||
className={css.select}
|
||||
value={selectedWorktree ?? ''}
|
||||
title={selectedWorktree}
|
||||
disabled={busy}
|
||||
onChange={(event) => { chooseWorktree(event.target.value) }}
|
||||
>
|
||||
{worktrees.map(entry => (
|
||||
<option key={entry.path} value={entry.path}>
|
||||
{entry.branch} · {baseName(entry.path)} ({entry.changes})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{branch !== '' && (branchOptions.length > 1
|
||||
? (
|
||||
<select
|
||||
className={css.select}
|
||||
value={branch}
|
||||
title={t('branch')}
|
||||
disabled={busy}
|
||||
onChange={(event) => { void checkout(event.target.value) }}
|
||||
>
|
||||
{branchOptions.map(name => <option key={name} value={name}>{name}</option>)}
|
||||
</select>
|
||||
)
|
||||
: <span className={css.branchLabel} title={`${t('branch')}: ${branch}`}>{branch}</span>)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* The ONE scroll body: the change groups and the history scroll here,
|
||||
between the fixed head band and the fixed commit bar (#194). */}
|
||||
{/* Changes and Graph scroll together; only the branch/sync footer docks. */}
|
||||
<div className={css.gitScroll} data-git-scroll>
|
||||
{viewError !== null && <Notice kind="error" role="alert">{viewError}</Notice>}
|
||||
|
||||
@@ -986,184 +987,151 @@ export function GitLens(props: GitLensProps) {
|
||||
{snapshot !== null && !isRepo && <Notice kind="empty" tone="page">{t('notRepo')}</Notice>}
|
||||
{snapshot?.truncated === true && <Notice kind="warn">{t('statusTruncated')}</Notice>}
|
||||
|
||||
{clean && <Notice kind="empty" tone="page">{t('changesClean')}</Notice>}
|
||||
|
||||
{isRepo && !clean && (
|
||||
<>
|
||||
{/* Each group is its own block so its sticky header is released (and
|
||||
replaced) exactly when the group scrolls away. */}
|
||||
<div className={css.group} data-group="unstaged">
|
||||
<SectionHeader
|
||||
className={css.groupHeader}
|
||||
label={t('unstaged')}
|
||||
action={unstagedEntries.length > 0
|
||||
? (
|
||||
<IconButton
|
||||
className={css.headerAction}
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
label={t('stageAll')}
|
||||
icon={<IconPlusOutlineRegular size={14} />}
|
||||
onClick={() => { stageAll(false) }}
|
||||
/>
|
||||
)
|
||||
: undefined}
|
||||
>
|
||||
<span className={css.countPill} data-count={unstagedEntries.length}>{unstagedEntries.length}</span>
|
||||
{/* The group's line total (#131): the sum of its file rows. */}
|
||||
{unstagedTotal.files > 0 && (
|
||||
<PlusMinus additions={unstagedTotal.additions} deletions={unstagedTotal.deletions} note="group" />
|
||||
)}
|
||||
</SectionHeader>
|
||||
{renderTree(unstagedTree, false)}
|
||||
</div>
|
||||
<div className={css.group} data-group="staged">
|
||||
<SectionHeader
|
||||
className={css.groupHeader}
|
||||
label={t('staged')}
|
||||
action={stagedEntries.length > 0
|
||||
? (
|
||||
<IconButton
|
||||
className={css.headerAction}
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
label={t('unstageAll')}
|
||||
icon={<IconTrashOutlineRegular size={14} />}
|
||||
onClick={() => { stageAll(true) }}
|
||||
/>
|
||||
)
|
||||
: undefined}
|
||||
>
|
||||
<span className={css.countPill} data-count={stagedEntries.length}>{stagedEntries.length}</span>
|
||||
{stagedTotal.files > 0 && (
|
||||
<PlusMinus additions={stagedTotal.additions} deletions={stagedTotal.deletions} note="group" />
|
||||
)}
|
||||
</SectionHeader>
|
||||
{renderTree(stagedTree, true)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{isRepo && (
|
||||
<>
|
||||
<SectionHeader label={t('history')} count={logEntries.length > 0 ? logEntries.length : undefined} />
|
||||
{logEntries.length === 0 && logFailed && <Notice kind="error">{t('historyLoadError')}</Notice>}
|
||||
{logEntries.length === 0 && !logFailed && logEnded && <Notice kind="empty" tone="page">{t('changesNoHistory')}</Notice>}
|
||||
{logEntries.map(entry => (
|
||||
<div
|
||||
key={entry.hashFull}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
className={css.logRow}
|
||||
data-selected={selectedRef?.kind === 'commit' && selectedRef.hashFull === entry.hashFull ? 'true' : undefined}
|
||||
title={`${entry.author} · ${entry.date}\n${entry.hashFull}`}
|
||||
onClick={() => { onPreview(commitRefOf(entry)) }}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
onPreview(commitRefOf(entry))
|
||||
}
|
||||
}}
|
||||
onContextMenu={(event) => { openHistoryMenu(event, entry) }}
|
||||
>
|
||||
<span className={css.logLine1}>
|
||||
<span className={css.logHash}>{entry.hash}</span>
|
||||
<span className={css.logSubject}>{entry.subject}</span>
|
||||
<section data-scm-section="changes">
|
||||
<div className={css.scmHeader}>
|
||||
<button type="button" className={css.scmDisclosure} aria-expanded={changesOpen}
|
||||
onClick={() => { setChangesOpen(open => !open) }}>
|
||||
<span className={css.chevron} data-open={changesOpen ? 'true' : undefined} aria-hidden="true">
|
||||
<IconChevronRightOutlineRegular size={12} />
|
||||
</span>
|
||||
<span className={css.logLine2}>
|
||||
{refNames(entry.refs).map(ref => (
|
||||
<span key={ref} className={css.logRef}>{ref}</span>
|
||||
))}
|
||||
<span className={css.logMeta}>{entry.author} · {relativeTime(entry.date)}</span>
|
||||
{t('gitChanges')}
|
||||
</button>
|
||||
<div className={css.scmActions}>
|
||||
<IconButton size="sm" icon={<IconCheckOutlineRegular size={14} />} label={t('commit')}
|
||||
disabled={!canCommit} onClick={commit} />
|
||||
<IconButton size="sm" icon={<IconRefreshOutlineRegular size={14} />} label={t('refresh')}
|
||||
disabled={busy || suggesting} onClick={() => { invalidateGitStatus(scope.sessionId); void refresh(false) }} />
|
||||
<Menu open={moreOpen} onClose={() => { setMoreOpen(false) }} portal compact align="end" autoFocus
|
||||
anchor={<IconButton size="sm" icon={<IconEllipsisOutlineRegular size={14} />} label={t('gitMoreActions')}
|
||||
active={moreOpen} onClick={() => { setMoreOpen(open => !open) }} />}
|
||||
items={[
|
||||
{ id: 'push', label: t('push'), disabled: busy || suggesting || snapshot?.detached === true },
|
||||
{ id: 'pull', label: t('pull'), 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 })),
|
||||
}] : []),
|
||||
...(worktrees.length > 1 ? [{ id: 'worktrees', label: t('worktree'),
|
||||
submenu: worktrees.map(entry => ({ id: `worktree:${entry.path}`,
|
||||
label: `${entry.branch || t('gitDetached')} · ${baseName(entry.path)} (${entry.changes})`, disabled: busy || suggesting,
|
||||
})),
|
||||
}] : []),
|
||||
]}
|
||||
onSelect={id => {
|
||||
setMoreOpen(false)
|
||||
if (id === 'push') push()
|
||||
else if (id === 'pull') pull()
|
||||
else if (id.startsWith('repo:')) chooseRepo(id.slice(5))
|
||||
else if (id.startsWith('worktree:')) chooseWorktree(id.slice(9))
|
||||
}} />
|
||||
</div>
|
||||
</div>
|
||||
{changesOpen && <div data-scm-changes>
|
||||
<div className={css.messageBox} data-message-box>
|
||||
<span className={css.commitInputWrap}>
|
||||
<textarea ref={commitBoxRef} className={css.commitInput}
|
||||
placeholder={busy || suggesting ? '' : messagePlaceholder}
|
||||
value={commitMsg} disabled={busy || suggesting} aria-busy={busy || suggesting}
|
||||
data-message-busy={suggesting || committing ? 'true' : undefined}
|
||||
aria-label={messagePlaceholder} rows={1}
|
||||
onChange={event => { writeDraft(event.currentTarget.value); setActionError(null) }}
|
||||
onKeyDown={event => {
|
||||
if (event.nativeEvent.isComposing) return
|
||||
if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); commit() }
|
||||
if ((event.ctrlKey || event.metaKey) && (event.key === 'g' || event.key === 'G')) {
|
||||
event.preventDefault(); void suggestMessage()
|
||||
}
|
||||
}} />
|
||||
{(suggesting || committing) && <span className={css.commitBusyText} role="status" aria-live="polite">
|
||||
{suggesting ? t('generatingCommitMessage') : t('committingMessage')}
|
||||
</span>}
|
||||
<button type="button" className={suggesting ? `${css.suggestButton} ${css.suggestBusy}` : css.suggestButton}
|
||||
aria-label={generateLabel} aria-busy={suggesting} title={generateLabel}
|
||||
disabled={busy || suggesting || entries.length === 0} onClick={() => { void suggestMessage() }}>
|
||||
<IconSparkleRegular size={14} />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
{!logEnded && (
|
||||
<button
|
||||
type="button"
|
||||
className={css.logMore}
|
||||
disabled={logLoadingMore || busy}
|
||||
onClick={() => { void loadMoreLog() }}
|
||||
>
|
||||
{logLoadingMore ? t('loading') : t('loadMore')}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
{clean && <Notice kind="empty">{t('changesClean')}</Notice>}
|
||||
{mergeEntries.length > 0 && <div className={css.group} data-group="merge">
|
||||
<SectionHeader className={css.groupHeader} label={t('gitMergeChanges')}
|
||||
action={<IconButton className={css.headerAction} size="sm" disabled={busy || suggesting}
|
||||
label={t('stageAll')} icon={<IconPlusOutlineRegular size={14} />} onClick={() => { stageAll(false, true) }} />}>
|
||||
<span className={css.countPill} data-count={mergeEntries.length}>{mergeEntries.length}</span>
|
||||
</SectionHeader>
|
||||
{renderTree(mergeTree, false)}
|
||||
</div>}
|
||||
{stagedEntries.length > 0 && <div className={css.group} data-group="staged">
|
||||
<SectionHeader className={css.groupHeader} label={t('gitStagedChanges')}
|
||||
action={<IconButton className={css.headerAction} size="sm" disabled={busy || suggesting}
|
||||
label={t('unstageAll')} icon={<IconTrashOutlineRegular size={14} />} onClick={() => { stageAll(true) }} />}>
|
||||
<span className={css.countPill} data-count={stagedEntries.length}>{stagedEntries.length}</span>
|
||||
{stagedTotal.files > 0 && <PlusMinus additions={stagedTotal.additions} deletions={stagedTotal.deletions} note="group" />}
|
||||
</SectionHeader>
|
||||
{renderTree(stagedTree, true)}
|
||||
</div>}
|
||||
{unstagedEntries.length > 0 && <div className={css.group} data-group="unstaged">
|
||||
<SectionHeader className={css.groupHeader} label={t('gitChanges')}
|
||||
action={<IconButton className={css.headerAction} size="sm" disabled={busy || suggesting}
|
||||
label={t('stageAll')} icon={<IconPlusOutlineRegular size={14} />} onClick={() => { stageAll(false) }} />}>
|
||||
<span className={css.countPill} data-count={unstagedEntries.length}>{unstagedEntries.length}</span>
|
||||
{unstagedTotal.files > 0 && <PlusMinus additions={unstagedTotal.additions} deletions={unstagedTotal.deletions} note="group" />}
|
||||
</SectionHeader>
|
||||
{renderTree(unstagedTree, false)}
|
||||
</div>}
|
||||
</div>}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{isRepo && <section data-scm-section="graph">
|
||||
<div className={css.scmHeader}>
|
||||
<button type="button" className={css.scmDisclosure} aria-expanded={graphOpen}
|
||||
onClick={() => { setGraphOpen(open => !open) }}>
|
||||
<span className={css.chevron} data-open={graphOpen ? 'true' : undefined} aria-hidden="true">
|
||||
<IconChevronRightOutlineRegular size={12} />
|
||||
</span>
|
||||
{t('gitGraph')}
|
||||
</button>
|
||||
</div>
|
||||
{graphOpen && <div data-scm-graph>
|
||||
{logLoading && <Notice kind="loading">{t('loading')}</Notice>}
|
||||
{logEntries.length === 0 && logFailed && <Notice kind="error">
|
||||
{t('historyLoadError')} <Button variant="ghost" size="sm" onClick={() => { void refresh(false) }}>{t('retry')}</Button>
|
||||
</Notice>}
|
||||
{logEntries.length === 0 && !logFailed && !logLoading && logEnded && <Notice kind="empty">{t('changesNoHistory')}</Notice>}
|
||||
<GitGraph entries={logEntries} selectedHash={selectedRef?.kind === 'commit' ? selectedRef.hashFull : undefined}
|
||||
onPreview={entry => { onPreview(commitRefOf(entry)) }} onContextMenu={openHistoryMenu} />
|
||||
{!logEnded && !logLoading && <button type="button" className={css.logMore}
|
||||
disabled={logLoadingMore || busy || suggesting} onClick={() => { void loadMoreLog() }}>
|
||||
{logLoadingMore ? t('loading') : t('loadMore')}
|
||||
</button>}
|
||||
</div>}
|
||||
</section>}
|
||||
</div>
|
||||
|
||||
{/* The commit bar is OUTSIDE the scroll body: it is the tab's persistent
|
||||
action surface, so the message being written never scrolls away
|
||||
(#194). */}
|
||||
{isRepo && (
|
||||
<div className={css.commitBar} data-commit-bar>
|
||||
<div className={css.commitRow}>
|
||||
<span className={css.commitInputWrap}>
|
||||
{/* A native textarea (the primitives ship no multiline input):
|
||||
commit messages carry a subject AND a body, and Enter must
|
||||
insert a newline — submitting stays on Ctrl/Cmd+Enter. */}
|
||||
<textarea
|
||||
ref={commitBoxRef}
|
||||
className={css.commitInput}
|
||||
// While busy the placeholder steps aside for the sweep label.
|
||||
placeholder={busy || suggesting ? '' : t('commitPlaceholder')}
|
||||
value={commitMsg}
|
||||
disabled={busy || suggesting}
|
||||
aria-busy={busy || suggesting}
|
||||
aria-label={t('commitPlaceholder')}
|
||||
rows={1}
|
||||
onChange={(event) => { writeDraft(event.currentTarget.value); setActionError(null) }}
|
||||
onKeyDown={(event) => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') commit()
|
||||
// Ctrl/Cmd+G drafts the message, mirroring the button (the
|
||||
// placeholder advertises it).
|
||||
if ((event.ctrlKey || event.metaKey) && (event.key === 'g' || event.key === 'G')) {
|
||||
event.preventDefault()
|
||||
void suggestMessage()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{/* Only the two per-input operations get a label: other `busy`
|
||||
work (staging, checkout) disables the box silently. */}
|
||||
{(suggesting || committing) && (
|
||||
<span className={css.commitBusyText} role="status" aria-live="polite">
|
||||
{suggesting ? t('generatingCommitMessage') : t('committingMessage')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className={suggesting ? `${css.suggestButton} ${css.suggestBusy}` : css.suggestButton}
|
||||
aria-label={generateLabel}
|
||||
aria-busy={suggesting}
|
||||
title={generateLabel}
|
||||
disabled={busy || suggesting || (stagedEntries.length === 0 && unstagedEntries.length === 0)}
|
||||
onClick={() => { void suggestMessage() }}
|
||||
>
|
||||
<IconSparkleRegular size={14} />
|
||||
</button>
|
||||
<Button
|
||||
variant="primary"
|
||||
size="sm"
|
||||
disabled={busy || suggesting || commitMsg.trim() === '' || stagedEntries.length === 0}
|
||||
onClick={commit}
|
||||
>
|
||||
{t('commit')}
|
||||
</Button>
|
||||
{/* Shipping the commit without leaving the panel: the two remote
|
||||
actions ride the SAME row and the SAME busy lock as commit /
|
||||
stage, so their failures land on the bar's one status line
|
||||
below instead of opening a second error channel. */}
|
||||
<Button variant="ghost" size="sm" disabled={busy || suggesting} onClick={push}>{t('push')}</Button>
|
||||
<Button variant="ghost" size="sm" disabled={busy || suggesting} onClick={pull}>{t('pull')}</Button>
|
||||
</div>
|
||||
{/* The bar's ONE status line stays directly under the message row it
|
||||
belongs to (the placement `changes-tab.spec.tsx` pins), so it keeps
|
||||
reading as "your commit/stage/push failed" rather than as a tab-level
|
||||
banner. */}
|
||||
{actionError !== null && <Notice kind="error" tone="inline" role="alert">{actionError}</Notice>}
|
||||
{/* A sibling of the scroller: usable even with both sections folded. */}
|
||||
{isRepo && <div className={css.gitFooter} data-git-footer>
|
||||
{actionError !== null && <Notice kind="error" tone="inline" role="alert">{actionError}</Notice>}
|
||||
<div className={css.footerRow} data-footer-row>
|
||||
<Menu open={branchOpen} onClose={() => { setBranchOpen(false) }} portal compact side="top" autoFocus
|
||||
className={css.branchMenu}
|
||||
anchor={<button type="button" className={css.branchButton} aria-haspopup="menu" aria-expanded={branchOpen}
|
||||
title={`${t('branch')}: ${branchLabel}${branchMarkers}`} disabled={busy || suggesting}
|
||||
onClick={() => { setBranchOpen(open => !open) }}>
|
||||
<IconBranchOutlineRegular size={14} /><span>{branchLabel}{branchMarkers}</span>
|
||||
</button>}
|
||||
items={branchNames.length === 0 ? [{ id: 'none', label: t('gitBranchesUnavailable'), disabled: true }]
|
||||
: branchNames.map(name => ({ id: name, label: name, disabled: busy || suggesting }))}
|
||||
selectedId={branch}
|
||||
onSelect={name => { setBranchOpen(false); void checkout(name) }} />
|
||||
<button type="button" className={css.syncButton} aria-label={syncLabel} title={syncLabel}
|
||||
disabled={!canSync} onClick={sync}>
|
||||
<IconRefreshOutlineRegular size={14} />
|
||||
<span>{snapshot?.upstream !== undefined && snapshot.ahead !== undefined && snapshot.behind !== undefined
|
||||
? `${snapshot.behind}↓ ${snapshot.ahead}↑` : syncLabel}</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>}
|
||||
|
||||
{/*
|
||||
The one shared file-row context menu, positioned at the right-click
|
||||
@@ -1194,7 +1162,7 @@ export function GitLens(props: GitLensProps) {
|
||||
if (target === null) return
|
||||
setFileMenu(null)
|
||||
if (id === 'open') {
|
||||
const resolved = resolveSidebarPath(repoRoot ?? selectedWorktree ?? scope.cwd, target.path)
|
||||
const resolved = resolveSidebarPath(selectedWorktree ?? repoRoot ?? snapshot?.root ?? scope.cwd, target.path)
|
||||
// The host accepts any path now (no containment), so the open
|
||||
// guard that mirrored the old fence is gone with it.
|
||||
onOpenFile(resolved)
|
||||
@@ -1214,10 +1182,10 @@ export function GitLens(props: GitLensProps) {
|
||||
return
|
||||
}
|
||||
if (id === 'relative') {
|
||||
copy(relativeTo(repoRoot ?? selectedWorktree ?? scope.cwd ?? '', target.path))
|
||||
copy(relativeTo(selectedWorktree ?? repoRoot ?? snapshot?.root ?? scope.cwd ?? '', target.path))
|
||||
return
|
||||
}
|
||||
if (id === 'absolute') copy(resolveSidebarPath(repoRoot ?? selectedWorktree ?? scope.cwd, target.path))
|
||||
if (id === 'absolute') copy(resolveSidebarPath(selectedWorktree ?? repoRoot ?? snapshot?.root ?? scope.cwd, target.path))
|
||||
}}
|
||||
portal
|
||||
compact
|
||||
|
||||
@@ -18,12 +18,7 @@
|
||||
|
||||
/* ── Git lens (the former git panel) ───────────────────────────────────── */
|
||||
|
||||
/* The Git lens ROOT is not a scroller (#194): it is the fixed frame that holds
|
||||
the non-scrolling head band (branch / repository / worktree pickers) above
|
||||
the ONE inner scroll body and the commit bar below it. Everything that used
|
||||
to scroll here — the change groups, the history, the state lines — now
|
||||
scrolls inside `.gitScroll`, so the branch bar and the commit box stay on
|
||||
screen while the list moves. */
|
||||
/* Changes and Graph share one scroll body; branch/sync stays outside it. */
|
||||
.git {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
@@ -44,24 +39,22 @@
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
/* The selector band: branch / repository / worktree pickers (only rendered
|
||||
for real choices) and nothing else — the counts live in the section bands. */
|
||||
.selectors { flex: none; display: flex; align-items: center; gap: 6px; padding: 6px 12px 0; }
|
||||
.scmHeader { display: flex; align-items: center; min-height: 28px; padding: 0 6px; }
|
||||
.scmDisclosure { flex: 1; min-width: 0; display: flex; align-items: center; gap: 6px; min-height: 28px; padding: 0; border: none; background: transparent; color: var(--dsw-alias-label-primary); font: var(--dsw-font-xxs-strong-12); text-align: left; cursor: pointer; }
|
||||
.scmActions { display: flex; align-items: center; gap: 2px; opacity: 0; }
|
||||
.scmHeader:hover .scmActions, .scmHeader:focus-within .scmActions { opacity: 1; }
|
||||
@media (hover: none) { .scmActions { opacity: 1; } }
|
||||
|
||||
.select {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 28px;
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border-radius: 3px;
|
||||
background: var(--dsw-alias-bg-base);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
font: var(--dsw-font-xxs-12);
|
||||
}
|
||||
|
||||
/* A single branch has nothing to choose: it reads as the row's label. */
|
||||
.branchLabel { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dsw-alias-label-secondary); font: var(--dsw-font-xxxs-11); }
|
||||
.gitFooter { flex: none; min-width: 0; border-top: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-base); }
|
||||
.footerRow { display: flex; align-items: center; min-width: 0; min-height: 28px; }
|
||||
.branchMenu { display: flex; flex: 1; min-width: 0; }
|
||||
.branchButton, .syncButton { display: flex; align-items: center; gap: 5px; min-width: 0; min-height: 28px; padding: 3px 8px; border: none; background: transparent; color: var(--dsw-alias-label-secondary); font: var(--dsw-font-xxxs-11); cursor: pointer; }
|
||||
.branchButton { flex: 1; text-align: left; }
|
||||
.syncButton { max-width: 55%; }
|
||||
.branchButton svg, .syncButton svg { flex: none; }
|
||||
.branchButton span, .syncButton span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.branchButton:hover:not(:disabled), .syncButton:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }
|
||||
.branchButton:disabled, .syncButton:disabled { opacity: 0.45; cursor: default; }
|
||||
|
||||
/* ── Change groups (one directory tree each) ───────────────────────────── */
|
||||
|
||||
@@ -194,7 +187,8 @@
|
||||
/* The row's icons are content at the plugin's own scale, not chrome. */
|
||||
.rowIcon { flex: none; display: inline-flex; align-items: center; }
|
||||
|
||||
.rowName { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: var(--dsw-font-xxs-12); color: var(--dsw-alias-label-primary); }
|
||||
.rowName { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: var(--dsw-font-xxs-12); color: var(--dsw-alias-label-primary); }
|
||||
.rowPath { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: var(--dsw-font-xxxs-11); color: var(--dsw-alias-label-tertiary); }
|
||||
|
||||
/* A row's / band's line counts (#131): `+N −M` in the diff pane's own ink (the
|
||||
`.statAdd` / `.statDel` atoms of `diff.module.css`, reused rather than
|
||||
@@ -230,22 +224,9 @@
|
||||
.row:not(:hover):not(:focus-within) .rowAction { opacity: 1; }
|
||||
}
|
||||
|
||||
/* ── Commit bar (docked below the scroll body, never inside it) ─────────── */
|
||||
/* ── Message draft (inside Changes) ─────────────────────────────────────── */
|
||||
|
||||
/* Since #194 the bar is a SIBLING of `.gitScroll` in the lens root's column:
|
||||
it is always on screen, so it needs neither `position: sticky` nor a
|
||||
stacking order over the sticky group headers (they are inside the scroller,
|
||||
which clips them). */
|
||||
.commitBar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 8px 12px;
|
||||
border-top: 1px solid var(--dsw-alias-border-l1);
|
||||
background: var(--dsw-alias-bg-base);
|
||||
}
|
||||
.commitRow { display: flex; align-items: center; gap: 6px; }
|
||||
.messageBox { display: flex; padding: 4px 8px 8px; }
|
||||
|
||||
/* The commit-message box and its busy overlay: the input keeps its own
|
||||
flex sizing through a wrapper so the overlay can sit exactly on top of it
|
||||
@@ -269,9 +250,9 @@
|
||||
the stylesheet's half of that contract. */
|
||||
min-height: 30px;
|
||||
max-height: 120px;
|
||||
padding: 6px 8px;
|
||||
padding: 6px 32px 6px 8px;
|
||||
border: 0.5px solid var(--dsw-alias-border-l4);
|
||||
border-radius: 8px;
|
||||
border-radius: 3px;
|
||||
background: var(--dsw-alias-bg-layer-1);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
font: var(--dsw-font-s-13);
|
||||
@@ -292,6 +273,7 @@
|
||||
.commitInput:disabled {
|
||||
opacity: 0.5;
|
||||
}
|
||||
.commitInput[data-message-busy='true'] { color: transparent; caret-color: transparent; }
|
||||
|
||||
/* Busy text in the input's place: the running-status sweep used by the side
|
||||
chat (gradient text scrolled by background-position). The real placeholder
|
||||
@@ -327,9 +309,11 @@
|
||||
.commitBusyText { animation: none; }
|
||||
}
|
||||
|
||||
/* The AI commit-message button: a quiet square secondary button beside the
|
||||
input. While the host streams a suggestion it pulses. */
|
||||
/* Generate fills the draft only. Inline on the input's right edge. */
|
||||
.suggestButton {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 2px;
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -337,8 +321,8 @@
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
padding: 0;
|
||||
border: 1px solid var(--dsw-alias-border-l1);
|
||||
border-radius: 6px;
|
||||
border: none;
|
||||
border-radius: 3px;
|
||||
background: transparent;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
cursor: pointer;
|
||||
@@ -500,36 +484,16 @@
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
/* ── History ───────────────────────────────────────────────────────────── */
|
||||
/* ── Commit graph ──────────────────────────────────────────────────────── */
|
||||
|
||||
/* A history row: line 1 = short-hash badge + subject, line 2 = ref pills +
|
||||
author·time flushed right (the badges live on the second line so they never
|
||||
crowd the subject, and the time never pushes the refs around). */
|
||||
.logRow {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
padding: 6px 10px;
|
||||
margin: 0 6px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.logRow { position: relative; display: flex; align-items: center; min-width: 0; height: 22px; margin: 0 6px; cursor: pointer; }
|
||||
.logRow:hover { background: var(--dsw-alias-interactive-bg-hover); }
|
||||
|
||||
.logLine1 { display: flex; align-items: baseline; gap: 8px; min-width: 0; }
|
||||
.logHash {
|
||||
flex: none;
|
||||
padding: 1px 4px;
|
||||
border-radius: 2px;
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
font: var(--dsw-font-markdown-code-block-small);
|
||||
}
|
||||
.logLine2 { display: flex; align-items: center; gap: 6px; min-width: 0; flex-wrap: wrap; }
|
||||
.logRef { flex: none; padding: 0 6px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 999px; font: var(--dsw-font-xxxs-strong-11); color: var(--dsw-alias-brand-primary); white-space: nowrap; }
|
||||
.logSubject { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: var(--dsw-font-xxs-strong-12); color: var(--dsw-alias-label-primary); }
|
||||
.logMeta { margin-left: auto; font: var(--dsw-font-xxxs-11); color: var(--dsw-alias-label-tertiary); white-space: nowrap; }
|
||||
.graphSvg { flex: none; max-width: 40%; height: 22px; overflow: hidden; }
|
||||
.graphContent { display: flex; align-items: center; gap: 6px; flex: 1; min-width: 0; padding-right: 4px; }
|
||||
.logRefs { display: inline-flex; gap: 3px; flex-shrink: 1; min-width: 0; max-width: 45%; overflow: hidden; }
|
||||
.logRef { flex: none; padding: 0 4px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 3px; font: var(--dsw-font-xxxs-strong-11); color: var(--dsw-alias-brand-primary); white-space: nowrap; }
|
||||
.logSubject { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: var(--dsw-font-xxs-12); color: var(--dsw-alias-label-primary); }
|
||||
.logMeta { max-width: 28%; overflow: hidden; text-overflow: ellipsis; font: var(--dsw-font-xxxs-11); color: var(--dsw-alias-label-tertiary); white-space: nowrap; }
|
||||
|
||||
.logMore {
|
||||
display: block;
|
||||
@@ -604,7 +568,7 @@
|
||||
|
||||
/* Keyboard focus rings match the shared sidebar convention (the kit atoms and
|
||||
the tree rows carry their own). */
|
||||
.logRow:focus-visible, .logMore:focus-visible, .select:focus-visible, .dragHandle:focus-visible {
|
||||
.logRow:focus-visible, .logMore:focus-visible, .scmDisclosure:focus-visible, .branchButton:focus-visible, .syncButton:focus-visible, .suggestButton:focus-visible, .dragHandle:focus-visible {
|
||||
outline: 2px solid var(--dsw-alias-interactive-bg-hover-accent);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
@@ -208,7 +208,18 @@ export const ar: Record<string, string> = {
|
||||
unstage: 'إلغاء الإدراج',
|
||||
stageAll: 'إدراج الكل',
|
||||
unstageAll: 'إلغاء إدراج الكل',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'التغييرات',
|
||||
gitGraph: 'الرسم البياني',
|
||||
gitMergeChanges: 'تغييرات الدمج',
|
||||
gitStagedChanges: 'التغييرات المُدرجة',
|
||||
gitMoreActions: 'المزيد من الإجراءات',
|
||||
gitRepository: 'المستودع',
|
||||
gitDetached: 'HEAD منفصل',
|
||||
gitBranchesUnavailable: 'لا توجد فروع متاحة',
|
||||
gitNoUpstream: 'لا يوجد فرع تتبّع',
|
||||
gitSyncUnavailable: 'المزامنة غير متاحة',
|
||||
gitSync: 'مزامنة التغييرات',
|
||||
commitPlaceholder: 'رسالة (اضغط {shortcut} للتثبيت على "{branch}")',
|
||||
commit: 'تثبيت',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -193,7 +193,18 @@ export const de: Record<string, string> = {
|
||||
unstage: 'Unstagen',
|
||||
stageAll: 'Alle stagen',
|
||||
unstageAll: 'Alle unstagen',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'Änderungen',
|
||||
gitGraph: 'Graph',
|
||||
gitMergeChanges: 'Merge-Änderungen',
|
||||
gitStagedChanges: 'Gestagte Änderungen',
|
||||
gitMoreActions: 'Weitere Aktionen',
|
||||
gitRepository: 'Repository',
|
||||
gitDetached: 'Losgelöster HEAD',
|
||||
gitBranchesUnavailable: 'Keine Branches verfügbar',
|
||||
gitNoUpstream: 'Kein Upstream',
|
||||
gitSyncUnavailable: 'Synchronisierung nicht verfügbar',
|
||||
gitSync: 'Änderungen synchronisieren',
|
||||
commitPlaceholder: 'Nachricht ({shortcut} zum Committen auf "{branch}")',
|
||||
commit: 'Committen',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -200,7 +200,18 @@ export const fr: Record<string, string> = {
|
||||
unstage: 'Annuler la mise en scène',
|
||||
stageAll: 'Tout mettre en scène',
|
||||
unstageAll: 'Tout retirer de la scène',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'Modifications',
|
||||
gitGraph: 'Graphe',
|
||||
gitMergeChanges: 'Modifications de fusion',
|
||||
gitStagedChanges: 'Modifications indexées',
|
||||
gitMoreActions: 'Autres actions',
|
||||
gitRepository: 'Dépôt',
|
||||
gitDetached: 'HEAD détachée',
|
||||
gitBranchesUnavailable: 'Aucune branche disponible',
|
||||
gitNoUpstream: 'Aucune branche en amont',
|
||||
gitSyncUnavailable: 'Synchronisation indisponible',
|
||||
gitSync: 'Synchroniser les modifications',
|
||||
commitPlaceholder: 'Message ({shortcut} pour valider sur « {branch} »)',
|
||||
commit: 'Valider',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -207,7 +207,18 @@ export const hi: Record<string, string> = {
|
||||
unstage: 'अनस्टेज',
|
||||
stageAll: 'सभी स्टेज करें',
|
||||
unstageAll: 'सभी अनस्टेज करें',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'बदलाव',
|
||||
gitGraph: 'ग्राफ़',
|
||||
gitMergeChanges: 'मर्ज के बदलाव',
|
||||
gitStagedChanges: 'स्टेज किए गए बदलाव',
|
||||
gitMoreActions: 'और कार्रवाइयाँ',
|
||||
gitRepository: 'रिपॉज़िटरी',
|
||||
gitDetached: 'अलग HEAD',
|
||||
gitBranchesUnavailable: 'कोई ब्रांच उपलब्ध नहीं',
|
||||
gitNoUpstream: 'अपस्ट्रीम सेट नहीं है',
|
||||
gitSyncUnavailable: 'सिंक उपलब्ध नहीं',
|
||||
gitSync: 'बदलाव सिंक करें',
|
||||
commitPlaceholder: 'संदेश ("{branch}" पर कमिट करने के लिए {shortcut})',
|
||||
commit: 'कमिट',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -205,7 +205,18 @@ export const id: Record<string, string> = {
|
||||
unstage: 'Unstage',
|
||||
stageAll: 'Stage semua',
|
||||
unstageAll: 'Unstage semua',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'Perubahan',
|
||||
gitGraph: 'Graf',
|
||||
gitMergeChanges: 'Perubahan penggabungan',
|
||||
gitStagedChanges: 'Perubahan yang di-stage',
|
||||
gitMoreActions: 'Tindakan lainnya',
|
||||
gitRepository: 'Repositori',
|
||||
gitDetached: 'HEAD terlepas',
|
||||
gitBranchesUnavailable: 'Tidak ada branch yang tersedia',
|
||||
gitNoUpstream: 'Upstream belum diatur',
|
||||
gitSyncUnavailable: 'Sinkronisasi tidak tersedia',
|
||||
gitSync: 'Sinkronkan perubahan',
|
||||
commitPlaceholder: 'Pesan ({shortcut} untuk commit pada "{branch}")',
|
||||
commit: 'Commit',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -198,7 +198,18 @@ export const it: Record<string, string> = {
|
||||
unstage: 'Rimuovi dalla preparazione',
|
||||
stageAll: 'Prepara tutto',
|
||||
unstageAll: 'Rimuovi tutto dalla preparazione',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'Modifiche',
|
||||
gitGraph: 'Grafo',
|
||||
gitMergeChanges: 'Modifiche di merge',
|
||||
gitStagedChanges: 'Modifiche preparate',
|
||||
gitMoreActions: 'Altre azioni',
|
||||
gitRepository: 'Repository',
|
||||
gitDetached: 'HEAD scollegata',
|
||||
gitBranchesUnavailable: 'Nessun ramo disponibile',
|
||||
gitNoUpstream: 'Nessun upstream',
|
||||
gitSyncUnavailable: 'Sincronizzazione non disponibile',
|
||||
gitSync: 'Sincronizza modifiche',
|
||||
commitPlaceholder: 'Messaggio ({shortcut} per eseguire il commit su "{branch}")',
|
||||
commit: 'Commit',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -207,7 +207,18 @@ export const ja: Record<string, string> = {
|
||||
unstage: 'ステージ解除',
|
||||
stageAll: 'すべてステージ',
|
||||
unstageAll: 'すべてステージ解除',
|
||||
commitPlaceholder: 'コミットメッセージ (Ctrl+G で生成、Ctrl+Enter でコミット)',
|
||||
gitChanges: '変更',
|
||||
gitGraph: 'グラフ',
|
||||
gitMergeChanges: 'マージの変更',
|
||||
gitStagedChanges: 'ステージ済みの変更',
|
||||
gitMoreActions: 'その他の操作',
|
||||
gitRepository: 'リポジトリ',
|
||||
gitDetached: '切り離された HEAD',
|
||||
gitBranchesUnavailable: '利用可能なブランチがありません',
|
||||
gitNoUpstream: 'アップストリーム未設定',
|
||||
gitSyncUnavailable: '同期は利用できません',
|
||||
gitSync: '変更を同期',
|
||||
commitPlaceholder: 'メッセージ({shortcut} で「{branch}」にコミット)',
|
||||
commit: 'コミット',
|
||||
generateCommitMessage: 'コミットメッセージを生成',
|
||||
generateCommitMessageWith: 'コミットメッセージを生成({model} を使用)',
|
||||
|
||||
@@ -199,7 +199,18 @@ export const ko: Record<string, string> = {
|
||||
unstage: '스테이징 해제',
|
||||
stageAll: '모두 스테이징',
|
||||
unstageAll: '모두 스테이징 해제',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: '변경 사항',
|
||||
gitGraph: '그래프',
|
||||
gitMergeChanges: '병합 변경 사항',
|
||||
gitStagedChanges: '스테이징된 변경 사항',
|
||||
gitMoreActions: '추가 작업',
|
||||
gitRepository: '저장소',
|
||||
gitDetached: '분리된 HEAD',
|
||||
gitBranchesUnavailable: '사용 가능한 브랜치가 없습니다',
|
||||
gitNoUpstream: '업스트림이 설정되지 않았습니다',
|
||||
gitSyncUnavailable: '동기화할 수 없습니다',
|
||||
gitSync: '변경 사항 동기화',
|
||||
commitPlaceholder: '메시지 ({shortcut}로 "{branch}"에 커밋)',
|
||||
commit: '커밋',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -205,7 +205,18 @@ export const nl: Record<string, string> = {
|
||||
unstage: 'Unstagen',
|
||||
stageAll: 'Alles stagen',
|
||||
unstageAll: 'Alles unstagen',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'Wijzigingen',
|
||||
gitGraph: 'Graaf',
|
||||
gitMergeChanges: 'Mergewijzigingen',
|
||||
gitStagedChanges: 'Gestagede wijzigingen',
|
||||
gitMoreActions: 'Meer acties',
|
||||
gitRepository: 'Repository',
|
||||
gitDetached: 'Losgekoppelde HEAD',
|
||||
gitBranchesUnavailable: 'Geen branches beschikbaar',
|
||||
gitNoUpstream: 'Geen upstream',
|
||||
gitSyncUnavailable: 'Synchronisatie niet beschikbaar',
|
||||
gitSync: 'Wijzigingen synchroniseren',
|
||||
commitPlaceholder: 'Bericht ({shortcut} om te committen op "{branch}")',
|
||||
commit: 'Commit',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -209,7 +209,18 @@ export const pl: Record<string, string> = {
|
||||
unstage: 'Usuń z indeksu',
|
||||
stageAll: 'Dodaj wszystko do indeksu',
|
||||
unstageAll: 'Usuń wszystko z indeksu',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'Zmiany',
|
||||
gitGraph: 'Graf',
|
||||
gitMergeChanges: 'Zmiany scalania',
|
||||
gitStagedChanges: 'Zmiany w indeksie',
|
||||
gitMoreActions: 'Więcej działań',
|
||||
gitRepository: 'Repozytorium',
|
||||
gitDetached: 'Odłączony HEAD',
|
||||
gitBranchesUnavailable: 'Brak dostępnych gałęzi',
|
||||
gitNoUpstream: 'Brak gałęzi nadrzędnej',
|
||||
gitSyncUnavailable: 'Synchronizacja niedostępna',
|
||||
gitSync: 'Synchronizuj zmiany',
|
||||
commitPlaceholder: 'Wiadomość ({shortcut}, aby utworzyć commit na "{branch}")',
|
||||
commit: 'Commit',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -190,7 +190,18 @@ export const pt: Record<string, string> = {
|
||||
unstage: 'Desfazer stage',
|
||||
stageAll: 'Preparar tudo',
|
||||
unstageAll: 'Desfazer stage de tudo',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'Alterações',
|
||||
gitGraph: 'Grafo',
|
||||
gitMergeChanges: 'Alterações de mesclagem',
|
||||
gitStagedChanges: 'Alterações preparadas',
|
||||
gitMoreActions: 'Mais ações',
|
||||
gitRepository: 'Repositório',
|
||||
gitDetached: 'HEAD desanexado',
|
||||
gitBranchesUnavailable: 'Nenhuma branch disponível',
|
||||
gitNoUpstream: 'Nenhum upstream',
|
||||
gitSyncUnavailable: 'Sincronização indisponível',
|
||||
gitSync: 'Sincronizar alterações',
|
||||
commitPlaceholder: 'Mensagem ({shortcut} para fazer commit em "{branch}")',
|
||||
commit: 'Commit',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -203,7 +203,18 @@ export const ru: Record<string, string> = {
|
||||
unstage: 'Убрать из индекса',
|
||||
stageAll: 'Индексировать всё',
|
||||
unstageAll: 'Убрать всё из индекса',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'Изменения',
|
||||
gitGraph: 'Граф',
|
||||
gitMergeChanges: 'Изменения слияния',
|
||||
gitStagedChanges: 'Изменения в индексе',
|
||||
gitMoreActions: 'Другие действия',
|
||||
gitRepository: 'Репозиторий',
|
||||
gitDetached: 'Отсоединённый HEAD',
|
||||
gitBranchesUnavailable: 'Нет доступных веток',
|
||||
gitNoUpstream: 'Нет вышестоящей ветки',
|
||||
gitSyncUnavailable: 'Синхронизация недоступна',
|
||||
gitSync: 'Синхронизировать изменения',
|
||||
commitPlaceholder: 'Сообщение ({shortcut} для коммита в "{branch}")',
|
||||
commit: 'Закоммитить',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -190,7 +190,18 @@ export const sv: Record<string, string> = {
|
||||
unstage: 'Avköa',
|
||||
stageAll: 'Köa alla',
|
||||
unstageAll: 'Avköa alla',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'Ändringar',
|
||||
gitGraph: 'Graf',
|
||||
gitMergeChanges: 'Sammanslagningsändringar',
|
||||
gitStagedChanges: 'Köade ändringar',
|
||||
gitMoreActions: 'Fler åtgärder',
|
||||
gitRepository: 'Arkiv',
|
||||
gitDetached: 'Frikopplad HEAD',
|
||||
gitBranchesUnavailable: 'Inga grenar tillgängliga',
|
||||
gitNoUpstream: 'Ingen upstream',
|
||||
gitSyncUnavailable: 'Synkronisering otillgänglig',
|
||||
gitSync: 'Synkronisera ändringar',
|
||||
commitPlaceholder: 'Meddelande ({shortcut} för att committa på "{branch}")',
|
||||
commit: 'Commit',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -207,7 +207,18 @@ export const th: Record<string, string> = {
|
||||
unstage: 'Unstage',
|
||||
stageAll: 'Stage ทั้งหมด',
|
||||
unstageAll: 'Unstage ทั้งหมด',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'การเปลี่ยนแปลง',
|
||||
gitGraph: 'กราฟ',
|
||||
gitMergeChanges: 'การเปลี่ยนแปลงจากการผสาน',
|
||||
gitStagedChanges: 'การเปลี่ยนแปลงที่ Stage แล้ว',
|
||||
gitMoreActions: 'การดำเนินการเพิ่มเติม',
|
||||
gitRepository: 'ที่เก็บ',
|
||||
gitDetached: 'HEAD ที่แยกออก',
|
||||
gitBranchesUnavailable: 'ไม่มี branch ที่พร้อมใช้งาน',
|
||||
gitNoUpstream: 'ไม่ได้ตั้งค่า upstream',
|
||||
gitSyncUnavailable: 'ไม่สามารถซิงค์ได้',
|
||||
gitSync: 'ซิงค์การเปลี่ยนแปลง',
|
||||
commitPlaceholder: 'ข้อความ ({shortcut} เพื่อ commit บน "{branch}")',
|
||||
commit: 'Commit',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -207,7 +207,18 @@ export const tr: Record<string, string> = {
|
||||
unstage: 'Sahnelemeden kaldır',
|
||||
stageAll: 'Tümünü sahnele',
|
||||
unstageAll: 'Tümünü sahnelemeden kaldır',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'Değişiklikler',
|
||||
gitGraph: 'Grafik',
|
||||
gitMergeChanges: 'Birleştirme değişiklikleri',
|
||||
gitStagedChanges: 'Sahnelenmiş değişiklikler',
|
||||
gitMoreActions: 'Diğer işlemler',
|
||||
gitRepository: 'Depo',
|
||||
gitDetached: 'Ayrılmış HEAD',
|
||||
gitBranchesUnavailable: 'Kullanılabilir dal yok',
|
||||
gitNoUpstream: 'Üst dal ayarlanmamış',
|
||||
gitSyncUnavailable: 'Eşitleme kullanılamıyor',
|
||||
gitSync: 'Değişiklikleri eşitle',
|
||||
commitPlaceholder: 'Mesaj ("{branch}" dalında işlemek için {shortcut})',
|
||||
commit: 'İşle',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -207,7 +207,18 @@ export const vi: Record<string, string> = {
|
||||
unstage: 'Unstage',
|
||||
stageAll: 'Stage tất cả',
|
||||
unstageAll: 'Unstage tất cả',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'Thay đổi',
|
||||
gitGraph: 'Đồ thị',
|
||||
gitMergeChanges: 'Thay đổi hợp nhất',
|
||||
gitStagedChanges: 'Thay đổi đã stage',
|
||||
gitMoreActions: 'Thao tác khác',
|
||||
gitRepository: 'Kho lưu trữ',
|
||||
gitDetached: 'HEAD tách rời',
|
||||
gitBranchesUnavailable: 'Không có nhánh khả dụng',
|
||||
gitNoUpstream: 'Chưa đặt upstream',
|
||||
gitSyncUnavailable: 'Không thể đồng bộ',
|
||||
gitSync: 'Đồng bộ thay đổi',
|
||||
commitPlaceholder: 'Thông điệp ({shortcut} để commit trên "{branch}")',
|
||||
commit: 'Commit',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -222,7 +222,18 @@ export const zhHK: Record<string, string> = {
|
||||
unstage: '取消暫存',
|
||||
stageAll: '全部暫存',
|
||||
unstageAll: '全部取消暫存',
|
||||
commitPlaceholder: '提交訊息 (Ctrl+G 產生,Ctrl+Enter 提交)',
|
||||
gitChanges: '變更',
|
||||
gitGraph: '提交圖',
|
||||
gitMergeChanges: '合併變更',
|
||||
gitStagedChanges: '暫存的變更',
|
||||
gitMoreActions: '更多操作',
|
||||
gitRepository: '倉庫',
|
||||
gitDetached: '游離 HEAD',
|
||||
gitBranchesUnavailable: '沒有可用分支',
|
||||
gitNoUpstream: '未設定上游',
|
||||
gitSyncUnavailable: '同步不可用',
|
||||
gitSync: '同步變更',
|
||||
commitPlaceholder: '訊息(按 {shortcut} 提交至「{branch}」)',
|
||||
commit: '提交',
|
||||
generateCommitMessage: '產生提交訊息',
|
||||
generateCommitMessageWith: '產生提交訊息(使用 {model})',
|
||||
|
||||
@@ -222,7 +222,18 @@ export const zhMO: Record<string, string> = {
|
||||
unstage: '取消暫存',
|
||||
stageAll: '全部暫存',
|
||||
unstageAll: '全部取消暫存',
|
||||
commitPlaceholder: '提交訊息 (Ctrl+G 產生,Ctrl+Enter 提交)',
|
||||
gitChanges: '變更',
|
||||
gitGraph: '提交圖',
|
||||
gitMergeChanges: '合併變更',
|
||||
gitStagedChanges: '暫存的變更',
|
||||
gitMoreActions: '更多操作',
|
||||
gitRepository: '倉庫',
|
||||
gitDetached: '游離 HEAD',
|
||||
gitBranchesUnavailable: '沒有可用分支',
|
||||
gitNoUpstream: '未設定上游',
|
||||
gitSyncUnavailable: '同步不可用',
|
||||
gitSync: '同步變更',
|
||||
commitPlaceholder: '訊息(按 {shortcut} 提交至「{branch}」)',
|
||||
commit: '提交',
|
||||
generateCommitMessage: '產生提交訊息',
|
||||
generateCommitMessageWith: '產生提交訊息(使用 {model})',
|
||||
|
||||
@@ -222,7 +222,18 @@ export const zhTW: Record<string, string> = {
|
||||
unstage: '取消暫存',
|
||||
stageAll: '全部暫存',
|
||||
unstageAll: '全部取消暫存',
|
||||
commitPlaceholder: '提交訊息 (Ctrl+G 產生,Ctrl+Enter 提交)',
|
||||
gitChanges: '變更',
|
||||
gitGraph: '提交圖',
|
||||
gitMergeChanges: '合併變更',
|
||||
gitStagedChanges: '暫存的變更',
|
||||
gitMoreActions: '更多操作',
|
||||
gitRepository: '儲存庫',
|
||||
gitDetached: '游離 HEAD',
|
||||
gitBranchesUnavailable: '沒有可用分支',
|
||||
gitNoUpstream: '未設定上游',
|
||||
gitSyncUnavailable: '同步不可用',
|
||||
gitSync: '同步變更',
|
||||
commitPlaceholder: '訊息(按 {shortcut} 提交至「{branch}」)',
|
||||
commit: '提交',
|
||||
generateCommitMessage: '產生提交訊息',
|
||||
generateCommitMessageWith: '產生提交訊息(使用 {model})',
|
||||
|
||||
+24
-2
@@ -218,7 +218,18 @@ export const zh = {
|
||||
unstage: '取消暂存',
|
||||
stageAll: '全部暂存',
|
||||
unstageAll: '全部取消暂存',
|
||||
commitPlaceholder: '提交信息 (Ctrl+G 生成,Ctrl+Enter 提交)',
|
||||
gitChanges: '更改',
|
||||
gitGraph: '提交图',
|
||||
gitMergeChanges: '合并更改',
|
||||
gitStagedChanges: '暂存的更改',
|
||||
gitMoreActions: '更多操作',
|
||||
gitRepository: '仓库',
|
||||
gitDetached: '游离 HEAD',
|
||||
gitBranchesUnavailable: '没有可用分支',
|
||||
gitNoUpstream: '未设置上游',
|
||||
gitSyncUnavailable: '同步不可用',
|
||||
gitSync: '同步更改',
|
||||
commitPlaceholder: 'Message ({shortcut} to commit on "{branch}")',
|
||||
commit: '提交',
|
||||
generateCommitMessage: '生成提交信息',
|
||||
generateCommitMessageWith: '生成提交信息(使用 {model})',
|
||||
@@ -820,7 +831,18 @@ export const en: Record<keyof typeof zh, string> = {
|
||||
unstage: 'Unstage',
|
||||
stageAll: 'Stage all',
|
||||
unstageAll: 'Unstage all',
|
||||
commitPlaceholder: 'Commit message (Ctrl+G generate, Ctrl+Enter commit)',
|
||||
gitChanges: 'Changes',
|
||||
gitGraph: 'Graph',
|
||||
gitMergeChanges: 'Merge Changes',
|
||||
gitStagedChanges: 'Staged Changes',
|
||||
gitMoreActions: 'More Actions',
|
||||
gitRepository: 'Repository',
|
||||
gitDetached: 'Detached HEAD',
|
||||
gitBranchesUnavailable: 'No branches available',
|
||||
gitNoUpstream: 'No upstream',
|
||||
gitSyncUnavailable: 'Sync unavailable',
|
||||
gitSync: 'Sync Changes',
|
||||
commitPlaceholder: 'Message ({shortcut} to commit on "{branch}")',
|
||||
commit: 'Commit',
|
||||
generateCommitMessage: 'Generate commit message',
|
||||
generateCommitMessageWith: 'Generate commit message (using {model})',
|
||||
|
||||
@@ -114,6 +114,8 @@ function sameCounts(left: GitLineCounts | undefined, right: GitLineCounts | unde
|
||||
function sameStatus(a: GitStatusResult, b: GitStatusResult): boolean {
|
||||
if (a === b) return true
|
||||
if (a.isRepo !== b.isRepo || a.branch !== b.branch || a.root !== b.root
|
||||
|| a.upstream !== b.upstream || a.ahead !== b.ahead || a.behind !== b.behind
|
||||
|| a.detached !== b.detached || a.operation !== b.operation
|
||||
|| a.truncated !== b.truncated || a.entries.length !== b.entries.length) return false
|
||||
if (a.repositories?.length !== b.repositories?.length) return false
|
||||
if (a.repositories !== undefined && b.repositories !== undefined
|
||||
|
||||
+74
-16
@@ -16,7 +16,7 @@ import { join } from 'node:path'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { resolve } from 'node:path'
|
||||
|
||||
/** A parsed `git status --porcelain=v1 -z` entry. */
|
||||
/** A parsed porcelain status entry (v1 XY convention). */
|
||||
export interface GitStatusEntry {
|
||||
path: string
|
||||
/** Two-letter index/worktree status (X Y), e.g. 'M ', ' M', 'A ', '??'. */
|
||||
@@ -36,7 +36,15 @@ export type GitLineCounts = { additions: number; deletions: number } | { binary:
|
||||
/** The source-control panel snapshot. */
|
||||
export interface GitStatusResult {
|
||||
isRepo: boolean
|
||||
/** Absent when HEAD is detached; unborn branches keep their real name. */
|
||||
branch?: string
|
||||
/** Native tracking ref (e.g. origin/main); never inferred from a remote. */
|
||||
upstream?: string
|
||||
/** Present only when Git can compare HEAD with the tracking ref. */
|
||||
ahead?: number
|
||||
behind?: number
|
||||
detached?: boolean
|
||||
operation?: 'merge' | 'rebase'
|
||||
entries: GitStatusEntry[]
|
||||
/** True when the working tree had more rows than `GIT_STATUS_LIMIT`; the
|
||||
* panel shows a truncation notice instead of freezing on a huge untracked
|
||||
@@ -65,6 +73,8 @@ export interface GitLogEntry {
|
||||
hash: string
|
||||
/** Full 40-char hash (advanced operations: revert / cherry-pick). */
|
||||
hashFull: string
|
||||
/** Full parent hashes in Git's order; root commits have none. */
|
||||
parents: string[]
|
||||
subject: string
|
||||
author: string
|
||||
/** ISO 8601 author date (`%ai`), e.g. `2024-01-01 10:00:00 +0800`. */
|
||||
@@ -105,6 +115,38 @@ export function parsePorcelainZ(output: string): GitStatusEntry[] {
|
||||
return entries
|
||||
}
|
||||
|
||||
/** Native branch metadata and rows from `git status --porcelain=v2 --branch -z`.
|
||||
* Fixed metadata fields are split off; path spaces/newlines remain literal. */
|
||||
export function parseStatusPorcelainV2Z(output: string): GitStatusResult {
|
||||
const result: GitStatusResult = { isRepo: true, entries: [] }
|
||||
const tokens = output.split('\0')
|
||||
for (let index = 0; index < tokens.length; index += 1) {
|
||||
const token = tokens[index]!
|
||||
if (token.startsWith('# branch.head ')) {
|
||||
const head = token.slice('# branch.head '.length)
|
||||
result.detached = head === '(detached)'
|
||||
if (!result.detached) result.branch = head
|
||||
} else if (token.startsWith('# branch.upstream ')) {
|
||||
result.upstream = token.slice('# branch.upstream '.length)
|
||||
} else if (token.startsWith('# branch.ab ')) {
|
||||
const counts = /^# branch\.ab \+(\d+) -(\d+)$/.exec(token)
|
||||
if (counts !== null) {
|
||||
result.ahead = Number(counts[1])
|
||||
result.behind = Number(counts[2])
|
||||
}
|
||||
} else if (token.startsWith('? ')) {
|
||||
result.entries.push({ xy: '??', path: token.slice(2) })
|
||||
} else if (token.startsWith('1 ') || token.startsWith('2 ') || token.startsWith('u ')) {
|
||||
const fields = token.startsWith('u ') ? 10 : token.startsWith('2 ') ? 9 : 8
|
||||
const path = token.split(' ').slice(fields).join(' ')
|
||||
// v2 uses '.' for the clean side; existing callers consume v1 spaces.
|
||||
result.entries.push({ xy: token.slice(2, 4).replaceAll('.', ' '), path })
|
||||
if (token.startsWith('2 ')) index += 1 // The origin path is the next NUL field.
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one `--numstat` path field to the path the file has NOW: the plain
|
||||
* (`old => new`) and brace (`src/{a => b}/x.ts`) rename notations both fold
|
||||
@@ -224,12 +266,12 @@ export function parseWorktreeList(output: string): GitWorktreeRecord[] {
|
||||
return rows
|
||||
}
|
||||
|
||||
/** Parse `git log --pretty=format:%h%x1f%s%x1f%an%x1f%ai%x1f%H%x1f%D` rows. */
|
||||
/** Parse `git log --pretty=format:%h%x1f%s%x1f%an%x1f%ai%x1f%H%x1f%D%x1f%P` rows. */
|
||||
export function parseLogLines(output: string): GitLogEntry[] {
|
||||
const rows: GitLogEntry[] = []
|
||||
for (const line of output.split('\n')) {
|
||||
if (line === '') continue
|
||||
const [hash, subject, author, date, hashFull, refs] = line.split('\x1f')
|
||||
const [hash, subject, author, date, hashFull, refs, parents] = line.split('\x1f')
|
||||
if (hash === undefined || subject === undefined) continue
|
||||
rows.push({
|
||||
hash,
|
||||
@@ -238,6 +280,7 @@ export function parseLogLines(output: string): GitLogEntry[] {
|
||||
date: date ?? '',
|
||||
hashFull: hashFull ?? hash,
|
||||
refs: refs ?? '',
|
||||
parents: parents?.split(' ').filter(Boolean) ?? [],
|
||||
})
|
||||
}
|
||||
return rows
|
||||
@@ -475,12 +518,25 @@ export async function repoRoot(cwd: string, selected?: string): Promise<string>
|
||||
return roots[0]!
|
||||
}
|
||||
|
||||
/** The current branch name (`git rev-parse --abbrev-ref HEAD`; 'HEAD' when detached). */
|
||||
/** Symbolic HEAD's real branch, including an unborn branch; rejects when detached. */
|
||||
export async function currentBranch(cwd: string): Promise<string> {
|
||||
const out = await runGit(cwd, ['rev-parse', '--abbrev-ref', 'HEAD'])
|
||||
const out = await runGit(cwd, ['symbolic-ref', '--quiet', '--short', 'HEAD'])
|
||||
return out.trim()
|
||||
}
|
||||
|
||||
/** Operation markers live in THIS checkout's Git directory (not the common
|
||||
* directory shared by linked worktrees). `git am` also uses rebase-apply, but
|
||||
* only a rebase creates its `rebasing` marker. */
|
||||
async function currentOperation(cwd: string): Promise<GitStatusResult['operation']> {
|
||||
const gitDir = (await runGit(cwd, ['rev-parse', '--absolute-git-dir'])).trim()
|
||||
const names = await readdir(gitDir)
|
||||
if (names.includes('rebase-merge')
|
||||
|| (names.includes('rebase-apply') && (await readdir(join(gitDir, 'rebase-apply')).catch((): string[] => [])).includes('rebasing'))) {
|
||||
return 'rebase'
|
||||
}
|
||||
return names.includes('MERGE_HEAD') ? 'merge' : undefined
|
||||
}
|
||||
|
||||
/** Upper bound on status rows shipped to the client. Beyond this the result
|
||||
* is truncated (with `truncated: true`) so a pathological untracked set —
|
||||
* e.g. the working tree discovered under a home-directory cwd — cannot
|
||||
@@ -526,21 +582,22 @@ export async function status(cwd: string, selected?: string): Promise<GitStatusR
|
||||
const repositories = await repoRoots(cwd)
|
||||
if (repositories.length === 0) return { isRepo: false, entries: [], repositories: [] }
|
||||
const root = await repoRoot(cwd, selected)
|
||||
const [branch, raw, unstagedNumstat, stagedNumstat] = await Promise.all([
|
||||
currentBranch(root).catch(() => 'HEAD'),
|
||||
runGit(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all']),
|
||||
const [operation, raw, unstagedNumstat, stagedNumstat] = await Promise.all([
|
||||
currentOperation(root).catch(() => undefined),
|
||||
runGit(root, ['status', '--porcelain=v2', '--branch', '--ahead-behind', '-z', '--untracked-files=all']),
|
||||
runGit(root, ['diff', '--numstat', '-z']).catch(() => ''),
|
||||
runGit(root, ['diff', '--cached', '--numstat', '-z']).catch(() => ''),
|
||||
])
|
||||
const parsed = parsePorcelainZ(raw)
|
||||
const snapshot = parseStatusPorcelainV2Z(raw)
|
||||
const parsed = snapshot.entries
|
||||
const lineCounts = new Map<string, GitLineCounts>()
|
||||
addLineCounts(lineCounts, parseNumstat(stagedNumstat))
|
||||
addLineCounts(lineCounts, parseNumstat(unstagedNumstat))
|
||||
const truncated = parsed.length > GIT_STATUS_LIMIT
|
||||
const bounded = truncated ? parsed.slice(0, GIT_STATUS_LIMIT) : parsed
|
||||
return {
|
||||
isRepo: true,
|
||||
branch,
|
||||
...snapshot,
|
||||
operation,
|
||||
// Paths git has no numstat row for (untracked files) keep their entry
|
||||
// untouched: the absence IS the information.
|
||||
entries: bounded.map((entry): GitStatusEntry => {
|
||||
@@ -662,11 +719,11 @@ export async function commit(cwd: string, message: string, selected?: string): P
|
||||
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([
|
||||
currentBranch(root).catch(() => 'HEAD'),
|
||||
currentBranch(root).catch(() => ''),
|
||||
runGit(root, ['for-each-ref', '--format=%(refname:short)', 'refs/heads']),
|
||||
])
|
||||
const names = raw.split('\n').filter(line => line !== '')
|
||||
return { current, names: names.includes(current) ? names : [current, ...names] }
|
||||
return { current, names: current !== '' && !names.includes(current) ? [current, ...names] : names }
|
||||
}
|
||||
|
||||
/** Switch to an existing branch.
|
||||
@@ -678,11 +735,12 @@ export async function checkout(cwd: string, branch: string, selected?: string):
|
||||
await runGit(await repoRoot(cwd, selected), ['checkout', '--end-of-options', branch])
|
||||
}
|
||||
|
||||
/** Recent commit history (newest first), lazily pageable via skip/count. */
|
||||
/** All refs plus HEAD in child-before-parent order for graph lanes, pageable
|
||||
* via skip/count. `--all` also permits an empty history on an unborn HEAD. */
|
||||
export async function log(cwd: string, count = 30, skip = 0, selected?: string): Promise<GitLogEntry[]> {
|
||||
const raw = await runGit(await repoRoot(cwd, selected), [
|
||||
'log', '-n', String(count), '--skip', String(skip), '--decorate=short',
|
||||
'--pretty=format:%h%x1f%s%x1f%an%x1f%ai%x1f%H%x1f%D',
|
||||
'log', '--all', '--topo-order', '-n', String(count), '--skip', String(skip), '--decorate=short',
|
||||
'--pretty=format:%h%x1f%s%x1f%an%x1f%ai%x1f%H%x1f%D%x1f%P',
|
||||
])
|
||||
return parseLogLines(raw)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
/** @vitest-environment jsdom */
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import type { GitLogEntry } from '../src/client/api.ts'
|
||||
import { GitGraph, layoutGraph } from '../src/client/changes/GitGraph.tsx'
|
||||
import css from '../src/client/changes/changes.module.css'
|
||||
import { renderRoot, setupReactAct } from './test-utils.ts'
|
||||
|
||||
setupReactAct()
|
||||
|
||||
it('draws real fork/merge ancestry across page boundaries and preserves row activation', () => {
|
||||
const hash = (suffix: number): string => '1234567' + suffix.toString().padStart(33, '0')
|
||||
const entry = (id: number, parents: number[], refs = ''): GitLogEntry => ({
|
||||
hash: '1234567', hashFull: hash(id), parents: parents.map(hash),
|
||||
subject: `Commit ${id}`, author: 'Ada', date: '2026-10-13 12:00:00 +0800', refs,
|
||||
})
|
||||
// Merge -> two children -> shared parent, then a disconnected root. All
|
||||
// short hashes deliberately collide: ancestry must use full hashes only.
|
||||
const entries = [entry(1, [2, 3], 'HEAD -> main, origin/main, tag: v1'), entry(2, [4]), entry(3, [4]), entry(4, []), entry(5, [])]
|
||||
const page = layoutGraph(entries.slice(0, 2))
|
||||
const rows = layoutGraph(entries)
|
||||
expect(rows.slice(0, 2)).toEqual(page)
|
||||
expect(page[1]!.output.map(lane => lane.hash)).toEqual([hash(4), hash(3)])
|
||||
expect(rows.map(row => row.lane)).toEqual([0, 0, 1, 0, 0])
|
||||
expect(rows[1]!.input).toEqual(rows[0]!.output)
|
||||
expect(rows[2]!.input).toEqual(rows[1]!.output)
|
||||
expect(rows[0]!.color).toBe(rows[1]!.color)
|
||||
expect(rows[0]!.output[1]!.color).toBe(rows[2]!.color)
|
||||
expect(rows[2]!.output.map(lane => lane.hash)).toEqual([hash(4), hash(4)])
|
||||
expect(rows[3]!.paths.map(path => [path.child, path.parent])).toEqual([[hash(2), hash(4)], [hash(3), hash(4)]])
|
||||
expect(rows[3]!.paths.some(path => path.d.includes(' C '))).toBe(true)
|
||||
expect(rows[3]!.output).toEqual([])
|
||||
expect(rows[4]!.paths).toEqual([])
|
||||
expect(layoutGraph([])).toEqual([])
|
||||
const octopus = layoutGraph([entry(6, [7, 8, 9])])
|
||||
expect(octopus[0]!.output.map(lane => lane.hash)).toEqual([hash(7), hash(8), hash(9)])
|
||||
|
||||
const onPreview = vi.fn()
|
||||
const onContextMenu = vi.fn()
|
||||
const render = (history: readonly GitLogEntry[]) => <GitGraph entries={history} selectedHash={hash(3)} onPreview={onPreview} onContextMenu={onContextMenu} />
|
||||
const view = renderRoot(render(entries.slice(0, 2)))
|
||||
try {
|
||||
const nodesBefore = [...view.container.querySelectorAll('circle')].map(node => [node.getAttribute('cx'), node.getAttribute('fill')])
|
||||
const pathsBefore = [...view.container.querySelectorAll('path')].map(path => path.getAttribute('d'))
|
||||
view.rerender(render(entries))
|
||||
const rowEls = view.container.querySelectorAll<HTMLElement>('[data-graph-row]')
|
||||
expect(rowEls.length).toBe(entries.length)
|
||||
expect(rowEls[2]!.dataset.selected).toBe('true')
|
||||
expect(rowEls[2]!.getAttribute('aria-pressed')).toBe('true')
|
||||
expect(rowEls[0]!.title).toContain(entries[0]!.hashFull)
|
||||
expect(rowEls[0]!.title).toContain(entries[0]!.date)
|
||||
expect(rowEls[0]!.title).toContain(entries[0]!.author)
|
||||
expect(rowEls[0]!.querySelector(`.${css.logSubject}`)?.textContent).toBe(entries[0]!.subject)
|
||||
expect(rowEls[0]!.querySelector(`.${css.logMeta}`)?.textContent).toBe(entries[0]!.author)
|
||||
expect([...rowEls[0]!.querySelectorAll(`.${css.logRef}`)].map(ref => ref.textContent)).toEqual(['HEAD', 'main', 'origin/main', 'tag: v1'])
|
||||
expect([...view.container.querySelectorAll('circle')].slice(0, 2).map(node => [node.getAttribute('cx'), node.getAttribute('fill')])).toEqual(nodesBefore)
|
||||
expect([...view.container.querySelectorAll('path')].slice(0, pathsBefore.length).map(path => path.getAttribute('d'))).toEqual(pathsBefore)
|
||||
expect(view.container.querySelectorAll('svg[aria-hidden="true"]').length).toBe(entries.length)
|
||||
// Width can be capped independently of the fixed row height. No vertical
|
||||
// letterboxing: parent edges must still meet at y=0/22 between rows.
|
||||
expect(view.container.querySelectorAll('svg[preserveAspectRatio="none"]').length).toBe(entries.length)
|
||||
const links = new Set([...view.container.querySelectorAll('path')].map(path => `${path.getAttribute('data-child')}/${path.getAttribute('data-parent')}`))
|
||||
expect(links).toEqual(new Set([`${hash(1)}/${hash(2)}`, `${hash(1)}/${hash(3)}`, `${hash(2)}/${hash(4)}`, `${hash(3)}/${hash(4)}`]))
|
||||
for (const glyph of view.container.querySelectorAll('path, circle')) {
|
||||
expect(glyph.getAttribute(glyph.tagName === 'path' ? 'stroke' : 'fill')).toMatch(/^var\(--dsw-alias-/)
|
||||
}
|
||||
act(() => {
|
||||
rowEls[2]!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
|
||||
rowEls[2]!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
|
||||
rowEls[2]!.dispatchEvent(new KeyboardEvent('keydown', { key: ' ', bubbles: true, cancelable: true }))
|
||||
rowEls[2]!.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 15, clientY: 20 }))
|
||||
rowEls[2]!.dispatchEvent(new KeyboardEvent('keydown', { key: 'ContextMenu', bubbles: true, cancelable: true }))
|
||||
rowEls[2]!.dispatchEvent(new KeyboardEvent('keydown', { key: 'F10', shiftKey: true, bubbles: true, cancelable: true }))
|
||||
})
|
||||
expect(onPreview.mock.calls.map(call => call[0])).toEqual([entries[2], entries[2], entries[2]])
|
||||
expect(onContextMenu.mock.calls.map(call => call[1])).toEqual([entries[2], entries[2], entries[2]])
|
||||
} finally {
|
||||
view.unmount()
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,190 @@
|
||||
/** @vitest-environment jsdom */
|
||||
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 { createSidebarStore } from '../src/client/state.ts'
|
||||
import { invalidateGitStatus } from '../src/client/ui/git-status.ts'
|
||||
import { t } from '../src/client/locales.ts'
|
||||
import { renderRoot, setupReactAct } from './test-utils.ts'
|
||||
|
||||
setupReactAct()
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
const CWD = 'C:/repo'
|
||||
const store = createSidebarStore()
|
||||
const tracked = (): GitStatusResult => ({
|
||||
isRepo: true, branch: 'main', root: CWD, upstream: 'origin/main', ahead: 1, behind: 0,
|
||||
entries: [{ path: 'src/partial.ts', xy: 'MD' }, { path: 'new.ts', xy: '??' }],
|
||||
})
|
||||
const flush = async (): Promise<void> => { await act(async () => { await Promise.resolve() }) }
|
||||
const click = async (button: HTMLButtonElement): Promise<void> => { await act(async () => { button.click() }) }
|
||||
const input = (container: HTMLElement): HTMLTextAreaElement => container.querySelector<HTMLTextAreaElement>('[data-message-box] textarea')!
|
||||
const write = async (box: HTMLTextAreaElement, value: string): Promise<void> => {
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(box, value)
|
||||
box.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
})
|
||||
}
|
||||
const enter = async (box: HTMLTextAreaElement): Promise<void> => {
|
||||
await act(async () => { box.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', ctrlKey: true, bubbles: true, cancelable: true })) })
|
||||
}
|
||||
async function mount(readStatus: (scope: SessionScope) => GitStatusResult) {
|
||||
vi.spyOn(api, 'gitStatus').mockImplementation(async scope => readStatus(scope))
|
||||
vi.spyOn(api, 'gitWorktrees').mockResolvedValue([{ path: CWD, branch: 'main', current: true, changes: 2 }])
|
||||
vi.spyOn(api, 'gitBranch').mockResolvedValue({ current: 'main', names: ['main', 'feature'] })
|
||||
vi.spyOn(api, 'gitCommitModel').mockResolvedValue({ pinned: false })
|
||||
vi.spyOn(api, 'gitLog').mockResolvedValue([{ hash: 'abc1234', hashFull: 'a'.repeat(40), parents: [], subject: 'Initial', author: 'Ada', date: '2026-10-13', refs: 'HEAD -> main' }])
|
||||
const render = (sessionId: string) => <GitLens scope={{ sessionId, cwd: CWD }} store={store} visible
|
||||
selectedRef={null} onOpenFile={() => {}} onPreview={() => {}} />
|
||||
const view = renderRoot(render('scm-A'))
|
||||
await flush()
|
||||
await flush()
|
||||
return { ...view, switchTo: async (session: string) => { view.rerender(render(session)); await flush(); await flush() } }
|
||||
}
|
||||
|
||||
it('orders distinct conflict/index/worktree groups, folds independently, and keeps the footer', async () => {
|
||||
const snapshot = { ...tracked(), operation: 'merge' as const, entries: [...tracked().entries, { path: 'conflict.ts', xy: 'UU' }] }
|
||||
const view = await mount(() => snapshot)
|
||||
const stage = vi.spyOn(api, 'gitStage').mockResolvedValue({ ok: true })
|
||||
try {
|
||||
const { container } = view
|
||||
expect([...container.querySelectorAll<HTMLElement>('[data-group]')].map(el => el.dataset.group)).toEqual(['merge', 'staged', 'unstaged'])
|
||||
expect([...container.querySelectorAll('[data-group] > header [data-count], [data-group] > div:first-child [data-count]')].map(el => el.textContent)).toEqual(['1', '1', '2'])
|
||||
expect(container.querySelector('[data-group="staged"] [data-path="src/partial.ts"] [data-tone]')!.textContent).toBe('M')
|
||||
expect(container.querySelector('[data-group="unstaged"] [data-path="src/partial.ts"] [data-tone]')!.textContent).toBe('D')
|
||||
const footer = container.querySelector('[data-git-footer]')!
|
||||
expect(footer.textContent).toContain('main*+!')
|
||||
expect(container.querySelector('[data-git-scroll]')!.contains(footer)).toBe(false)
|
||||
const changes = container.querySelector<HTMLButtonElement>('[data-scm-section="changes"] button[aria-expanded]')!
|
||||
const graph = container.querySelector<HTMLButtonElement>('[data-scm-section="graph"] button[aria-expanded]')!
|
||||
await write(input(container), 'kept draft')
|
||||
await click(changes)
|
||||
expect(input(container)).toBeNull()
|
||||
expect(container.querySelector('[data-graph-row]')).not.toBeNull()
|
||||
await click(graph)
|
||||
expect(container.querySelector('[data-graph-row]')).toBeNull()
|
||||
expect(footer.querySelector('button[aria-haspopup="menu"]')).not.toBeNull()
|
||||
await click(changes)
|
||||
expect(input(container).value).toBe('kept draft')
|
||||
await click(container.querySelector<HTMLButtonElement>(`[data-group="unstaged"] button[aria-label="${t('stageAll')}"]`)!)
|
||||
expect(stage.mock.calls.map(call => call[1])).toEqual(['src/partial.ts', 'new.ts'])
|
||||
expect(changes.getAttribute('aria-expanded')).toBe('true')
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
|
||||
it('applies the same commit guard to keyboard and button, without auto-staging', async () => {
|
||||
let snapshot = { ...tracked(), entries: [{ path: 'new.ts', xy: '??' }] }
|
||||
const commit = vi.spyOn(api, 'gitCommit').mockResolvedValue({ ok: true })
|
||||
const stage = vi.spyOn(api, 'gitStage').mockResolvedValue({ ok: true })
|
||||
const view = await mount(() => snapshot)
|
||||
const refresh = async () => { await act(async () => { invalidateGitStatus('scm-A') }); await flush() }
|
||||
try {
|
||||
await write(input(view.container), 'feat: multiline\n\nbody')
|
||||
await enter(input(view.container))
|
||||
expect(commit).not.toHaveBeenCalled()
|
||||
snapshot = { ...tracked(), entries: [{ path: 'ready.ts', xy: 'M ' }, { path: 'conflict.ts', xy: 'UU' }] }
|
||||
await refresh()
|
||||
await enter(input(view.container))
|
||||
expect(commit).not.toHaveBeenCalled()
|
||||
snapshot = { ...tracked(), entries: [{ path: 'ready.ts', xy: 'M ' }] }
|
||||
await refresh()
|
||||
await write(input(view.container), ' ')
|
||||
await enter(input(view.container))
|
||||
expect(commit).not.toHaveBeenCalled()
|
||||
await write(input(view.container), 'feat: multiline\n\nbody')
|
||||
await enter(input(view.container))
|
||||
expect(commit).toHaveBeenCalledExactlyOnceWith({ sessionId: 'scm-A', cwd: CWD }, 'feat: multiline\n\nbody', CWD)
|
||||
expect(stage).not.toHaveBeenCalled()
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
|
||||
it('isolates late generation, failure and busy state across scopes, while preserving drafts', async () => {
|
||||
let resolveA!: (value: { message: string; provider: string; model: string }) => void
|
||||
let resolveB!: (value: { message: string; provider: string; model: string }) => void
|
||||
const suggest = vi.spyOn(api, 'gitSuggestMessage')
|
||||
.mockReturnValueOnce(new Promise(resolve => { resolveA = resolve }))
|
||||
.mockReturnValueOnce(new Promise(resolve => { resolveB = resolve }))
|
||||
.mockRejectedValueOnce(new Error('temporary outage'))
|
||||
.mockResolvedValueOnce({ message: 'retry draft', provider: 'test', model: 'test' })
|
||||
const commit = vi.spyOn(api, 'gitCommit').mockResolvedValue({ ok: true })
|
||||
const view = await mount(() => tracked())
|
||||
const generate = (): HTMLButtonElement => view.container.querySelector<HTMLButtonElement>('button[aria-label^="Generate commit message"]')!
|
||||
try {
|
||||
await write(input(view.container), 'A draft')
|
||||
await click(generate())
|
||||
expect(input(view.container).disabled).toBe(true)
|
||||
await view.switchTo('scm-B')
|
||||
expect(input(view.container).disabled).toBe(false)
|
||||
await write(input(view.container), 'B draft')
|
||||
await click(generate())
|
||||
await act(async () => { resolveA({ message: 'late A', provider: 'test', model: 'test' }); await Promise.resolve() })
|
||||
expect(input(view.container).value).toBe('B draft')
|
||||
expect(input(view.container).disabled).toBe(true)
|
||||
await act(async () => { resolveB({ message: 'generated B', provider: 'test', model: 'test' }); await Promise.resolve() })
|
||||
expect(input(view.container).value).toBe('generated B')
|
||||
expect(commit).not.toHaveBeenCalled()
|
||||
await view.switchTo('scm-A')
|
||||
expect(input(view.container).value).toBe('A draft')
|
||||
await click(generate())
|
||||
expect(view.container.textContent).toContain('temporary outage')
|
||||
await click(generate())
|
||||
expect(input(view.container).value).toBe('retry draft')
|
||||
expect(view.container.textContent).not.toContain('temporary outage')
|
||||
expect(suggest).toHaveBeenCalledTimes(4)
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
|
||||
it('shows genuine upstream counts, syncs Pull then Push, and never pushes after a failed Pull', async () => {
|
||||
let snapshot = tracked()
|
||||
const order: string[] = []
|
||||
const pull = vi.spyOn(api, 'gitPull').mockImplementation(async () => { order.push('pull'); return { ok: true } })
|
||||
const push = vi.spyOn(api, 'gitPush').mockImplementation(async () => { order.push('push'); return { ok: true } })
|
||||
const view = await mount(() => snapshot)
|
||||
const sync = (): HTMLButtonElement => view.container.querySelector<HTMLButtonElement>(`[data-git-footer] button[aria-label^="${t('gitSync')}"]`)!
|
||||
try {
|
||||
expect(sync().textContent).toContain('0↓ 1↑')
|
||||
expect(sync().title).toContain('origin/main')
|
||||
await click(sync())
|
||||
expect(order).toEqual(['pull', 'push'])
|
||||
pull.mockRejectedValueOnce(new Error('diverged'))
|
||||
await click(sync())
|
||||
expect(push).toHaveBeenCalledTimes(1)
|
||||
expect(view.container.textContent).toContain('diverged')
|
||||
snapshot = { ...tracked(), ahead: 2, behind: 3 }
|
||||
await act(async () => { invalidateGitStatus('scm-A') }); await flush()
|
||||
expect(sync().textContent).toContain('3↓ 2↑')
|
||||
const statusCalls = vi.mocked(api.gitStatus).mock.calls.length
|
||||
push.mockRejectedValueOnce(new Error('push denied'))
|
||||
await click(sync())
|
||||
expect(view.container.textContent).toContain('push denied')
|
||||
expect(vi.mocked(api.gitStatus).mock.calls.length).toBeGreaterThan(statusCalls)
|
||||
snapshot = { ...tracked(), upstream: undefined, ahead: undefined, behind: undefined }
|
||||
await act(async () => { invalidateGitStatus('scm-A') }); await flush()
|
||||
expect(view.container.querySelector<HTMLButtonElement>('[data-git-footer] button[aria-label="No upstream"]')!.disabled).toBe(true)
|
||||
snapshot = { ...snapshot, branch: '', detached: true }
|
||||
await act(async () => { invalidateGitStatus('scm-A') }); await flush()
|
||||
expect(view.container.querySelector<HTMLButtonElement>('[data-git-footer] button[aria-label="Detached HEAD"]')!.disabled).toBe(true)
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
|
||||
it('checks out a plain branch and refreshes placeholder, resources, graph and footer together', async () => {
|
||||
let snapshot = tracked()
|
||||
const checkout = vi.spyOn(api, 'gitCheckout').mockImplementation(async (_scope, branch) => {
|
||||
snapshot = { ...tracked(), branch, entries: [], ahead: 0, behind: 2, upstream: 'origin/feature' }
|
||||
return { ok: true }
|
||||
})
|
||||
const view = await mount(() => snapshot)
|
||||
try {
|
||||
expect(input(view.container).placeholder).toBe('Message (Ctrl+Enter to commit on "main")')
|
||||
const logCalls = vi.mocked(api.gitLog).mock.calls.length
|
||||
await click(view.container.querySelector<HTMLButtonElement>('[data-git-footer] button[aria-haspopup="menu"]')!)
|
||||
const feature = [...document.querySelectorAll<HTMLButtonElement>('[role="menuitem"]')].find(button => button.textContent === 'feature')!
|
||||
await click(feature)
|
||||
await flush()
|
||||
expect(checkout).toHaveBeenCalledExactlyOnceWith({ sessionId: 'scm-A', cwd: CWD }, 'feature', CWD)
|
||||
expect(input(view.container).placeholder).toBe('Message (Ctrl+Enter to commit on "feature")')
|
||||
expect(view.container.querySelectorAll('[data-group]')).toHaveLength(0)
|
||||
expect(view.container.querySelector('[data-git-footer]')!.textContent).toContain('2↓ 0↑')
|
||||
expect(vi.mocked(api.gitLog).mock.calls.length).toBeGreaterThan(logCalls)
|
||||
} finally { view.unmount() }
|
||||
})
|
||||
+161
-4
@@ -6,7 +6,7 @@ import { join } from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseUnifiedDiff } from '../src/client/diff/rows.ts'
|
||||
import { checkout, parseLogLines, parseNumstat, parsePorcelainZ, repoRoots, status } from '../src/git.ts'
|
||||
import { branches, checkout, currentBranch, log, parseLogLines, parseNumstat, parsePorcelainZ, parseStatusPorcelainV2Z, repoRoots, status } from '../src/git.ts'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const normalizePath = (path: string): string => path.replaceAll('\\', '/')
|
||||
@@ -52,6 +52,69 @@ describe('git parsing', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('parses v2 branch metadata and keeps v1 XY and literal rename/conflict paths', () => {
|
||||
const raw = [
|
||||
'# branch.oid deadbeef', '# branch.head feature/topic',
|
||||
'# branch.upstream upstream/review', '# branch.ab +2 -3',
|
||||
'1 .M N... 100644 100644 100644 abc abc src/space name.ts',
|
||||
'2 R. N... 100644 100644 100644 abc abc R100 src/new name.ts', 'src/old name.ts',
|
||||
'u UU N... 100644 100644 100644 100644 abc abc abc src/conflict.ts',
|
||||
'? newdir/line\nbreak.ts', '',
|
||||
].join('\0')
|
||||
expect(parseStatusPorcelainV2Z(raw)).toEqual({
|
||||
isRepo: true, branch: 'feature/topic', upstream: 'upstream/review', ahead: 2, behind: 3, detached: false,
|
||||
entries: [
|
||||
{ path: 'src/space name.ts', xy: ' M' },
|
||||
{ path: 'src/new name.ts', xy: 'R ' },
|
||||
{ path: 'src/conflict.ts', xy: 'UU' },
|
||||
{ path: 'newdir/line\nbreak.ts', xy: '??' },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('reports nonrepo, unborn, no-upstream and detached HEAD without inventing a branch', async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-git-head-'))
|
||||
const nonrepo = join(root, 'plain')
|
||||
const repo = join(root, 'repo')
|
||||
const git = (...args: string[]): string => execFileSync('git', args, { cwd: repo, encoding: 'utf8' }).trim()
|
||||
try {
|
||||
mkdirSync(nonrepo)
|
||||
mkdirSync(repo)
|
||||
expect(await status(nonrepo)).toEqual({ isRepo: false, entries: [], repositories: [] })
|
||||
git('init', '-q', '-b', 'fresh')
|
||||
git('config', 'user.email', 't@t')
|
||||
git('config', 'user.name', 't')
|
||||
writeFileSync(join(repo, 'new.txt'), 'unborn\n')
|
||||
const unborn = await status(repo)
|
||||
expect(unborn).toMatchObject({ branch: 'fresh', detached: false, entries: [{ path: 'new.txt', xy: '??' }] })
|
||||
expect(unborn.upstream).toBeUndefined()
|
||||
expect(unborn.ahead).toBeUndefined()
|
||||
expect(unborn.behind).toBeUndefined()
|
||||
expect(unborn.operation).toBeUndefined()
|
||||
await expect(currentBranch(repo)).resolves.toBe('fresh')
|
||||
await expect(branches(repo)).resolves.toEqual({ current: 'fresh', names: ['fresh'] })
|
||||
await expect(log(repo)).resolves.toEqual([])
|
||||
|
||||
git('commit', '-q', '--allow-empty', '-m', 'base')
|
||||
const untracked = await status(repo)
|
||||
expect(untracked.branch).toBe('fresh')
|
||||
expect(untracked.upstream).toBeUndefined()
|
||||
expect(untracked.ahead).toBeUndefined()
|
||||
expect(untracked.behind).toBeUndefined()
|
||||
git('checkout', '-q', '--detach')
|
||||
const detached = await status(repo)
|
||||
expect(detached.detached).toBe(true)
|
||||
expect(detached.branch).toBeUndefined()
|
||||
expect(detached.upstream).toBeUndefined()
|
||||
expect(detached.ahead).toBeUndefined()
|
||||
expect(detached.behind).toBeUndefined()
|
||||
await expect(currentBranch(repo)).rejects.toThrow()
|
||||
await expect(branches(repo)).resolves.toEqual({ current: '', names: ['fresh'] })
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps untracked files inside new directories as individual rows (status --untracked-files=all)', () => {
|
||||
// status() runs with --untracked-files=all, so a new folder must surface
|
||||
// as one entry PER FILE (?? newdir/a.ts), never a collapsed ?? newdir/
|
||||
@@ -136,10 +199,10 @@ describe('git parsing', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('parses log rows with unit separators (full hash + refs)', () => {
|
||||
it('parses log rows with unit separators (full hash + refs + parent hashes)', () => {
|
||||
const rows = parseLogLines(
|
||||
'abc1234\x1fFirst subject\x1fAlice\x1f2024-01-01 10:00:00 +0800\x1fabc1234def5678abc1234def5678abc1234def5678\x1fHEAD -> main, origin/main\n'
|
||||
+ 'def5678\x1fSecond subject\x1fBob\x1f2024-01-02 10:00:00 +0800\x1fdef5678abc1234def5678abc1234def5678abc1234\x1f\n',
|
||||
'abc1234\x1fFirst subject\x1fAlice\x1f2024-01-01 10:00:00 +0800\x1fabc1234def5678abc1234def5678abc1234def5678\x1fHEAD -> main, origin/main\x1fdef5678abc1234def5678abc1234def5678abc1234 1234567890123456789012345678901234567890\n'
|
||||
+ 'def5678\x1fSecond subject\x1fBob\x1f2024-01-02 10:00:00 +0800\x1fdef5678abc1234def5678abc1234def5678abc1234\x1f\x1f\n',
|
||||
)
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
@@ -149,6 +212,7 @@ describe('git parsing', () => {
|
||||
date: '2024-01-01 10:00:00 +0800',
|
||||
hashFull: 'abc1234def5678abc1234def5678abc1234def5678',
|
||||
refs: 'HEAD -> main, origin/main',
|
||||
parents: ['def5678abc1234def5678abc1234def5678abc1234', '1234567890123456789012345678901234567890'],
|
||||
},
|
||||
{
|
||||
hash: 'def5678',
|
||||
@@ -157,10 +221,103 @@ describe('git parsing', () => {
|
||||
date: '2024-01-02 10:00:00 +0800',
|
||||
hashFull: 'def5678abc1234def5678abc1234def5678abc1234',
|
||||
refs: '',
|
||||
parents: [],
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('logs real merge parents and other local refs in topological order with stable pagination', async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-git-graph-'))
|
||||
const git = (...args: string[]): string => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: 'pipe' }).trim()
|
||||
const commit = (subject: string, date: string): string => {
|
||||
execFileSync('git', ['commit', '-q', '--allow-empty', '-m', subject], {
|
||||
cwd: root, stdio: 'pipe', env: { ...process.env, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date },
|
||||
})
|
||||
return git('rev-parse', 'HEAD')
|
||||
}
|
||||
try {
|
||||
git('init', '-q', '-b', 'main')
|
||||
git('config', 'user.email', 't@t')
|
||||
git('config', 'user.name', 't')
|
||||
const base = commit('base', '2024-01-01T00:00:00Z')
|
||||
git('branch', 'topic')
|
||||
const main = commit('main tip', '2024-01-04T00:00:00Z')
|
||||
git('checkout', '-q', 'topic')
|
||||
const topic = commit('topic tip', '2024-01-03T00:00:00Z')
|
||||
git('checkout', '-q', 'main')
|
||||
git('merge', '-q', '--no-ff', '--no-edit', 'topic')
|
||||
const merge = git('rev-parse', 'HEAD')
|
||||
git('checkout', '-q', '-b', 'unmerged', base)
|
||||
const unmerged = commit('other local ref', '2024-01-05T00:00:00Z')
|
||||
// A detached commit reachable only from HEAD must not disappear under --all.
|
||||
git('checkout', '-q', '--detach', merge)
|
||||
const detached = commit('detached tip', '2024-01-02T00:00:00Z')
|
||||
const rows = await log(root, 20)
|
||||
expect(rows).toHaveLength(6)
|
||||
expect(rows.find(row => row.hashFull === merge)?.parents).toEqual([main, topic])
|
||||
expect(rows.find(row => row.hashFull === main)?.parents).toEqual([base])
|
||||
expect(rows.find(row => row.hashFull === topic)?.parents).toEqual([base])
|
||||
expect(rows.find(row => row.hashFull === detached)?.parents).toEqual([merge])
|
||||
expect(rows.find(row => row.hashFull === base)?.parents).toEqual([])
|
||||
expect(rows.find(row => row.hashFull === unmerged)?.refs).toContain('unmerged')
|
||||
const positions = new Map(rows.map((row, index) => [row.hashFull, index]))
|
||||
for (const [index, row] of rows.entries()) {
|
||||
for (const parent of row.parents) expect(positions.get(parent)).toBeGreaterThan(index)
|
||||
}
|
||||
expect([...await log(root, 2), ...await log(root, 20, 2)]).toEqual(rows)
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('reads merge and both rebase backends from the selected linked worktree only', async () => {
|
||||
const scratch = mkdtempSync(join(tmpdir(), 'dsh-git-operation-'))
|
||||
const root = join(scratch, 'repo')
|
||||
const linked = join(scratch, 'linked')
|
||||
const git = (cwd: string, ...args: string[]): string => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: 'pipe' }).trim()
|
||||
try {
|
||||
mkdirSync(root)
|
||||
git(root, 'init', '-q', '-b', 'main')
|
||||
git(root, 'config', 'user.email', 't@t')
|
||||
git(root, 'config', 'user.name', 't')
|
||||
git(root, 'config', 'core.autocrlf', 'false')
|
||||
writeFileSync(join(root, 'a.txt'), 'base\n')
|
||||
git(root, 'add', '-A')
|
||||
git(root, 'commit', '-q', '-m', 'base')
|
||||
git(root, 'branch', 'topic')
|
||||
writeFileSync(join(root, 'a.txt'), 'main\n')
|
||||
git(root, 'commit', '-q', '-am', 'main change')
|
||||
git(root, 'worktree', 'add', '-q', linked, 'topic')
|
||||
writeFileSync(join(linked, 'a.txt'), 'topic\n')
|
||||
git(linked, 'commit', '-q', '-am', 'topic change')
|
||||
|
||||
expect(() => git(linked, 'merge', '--no-edit', 'main')).toThrow()
|
||||
expect(await status(linked)).toMatchObject({
|
||||
branch: 'topic', detached: false, operation: 'merge', entries: [{ path: 'a.txt', xy: 'UU' }],
|
||||
})
|
||||
expect((await status(root)).operation).toBeUndefined()
|
||||
git(linked, 'merge', '--abort')
|
||||
expect((await status(linked)).operation).toBeUndefined()
|
||||
for (const backend of ['--merge', '--apply']) {
|
||||
expect(() => git(linked, 'rebase', backend, 'main')).toThrow()
|
||||
const rebasing = await status(linked)
|
||||
expect(rebasing).toMatchObject({ detached: true, operation: 'rebase' })
|
||||
expect(rebasing.branch).toBeUndefined()
|
||||
expect((await status(root)).operation).toBeUndefined()
|
||||
git(linked, 'rebase', '--abort')
|
||||
expect((await status(linked)).operation).toBeUndefined()
|
||||
}
|
||||
// `git am` shares rebase-apply storage, but is not a rebase.
|
||||
const patch = join(scratch, 'topic.patch')
|
||||
writeFileSync(patch, git(linked, 'format-patch', '-1', '--stdout'))
|
||||
expect(() => git(root, 'am', patch)).toThrow()
|
||||
expect((await status(root)).operation).toBeUndefined()
|
||||
git(root, 'am', '--abort')
|
||||
} finally {
|
||||
rmSync(scratch, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('parses a multi-file unified diff with aligned line numbers', () => {
|
||||
const diff = [
|
||||
'diff --git a/src/a.ts b/src/a.ts',
|
||||
|
||||
@@ -202,6 +202,30 @@ describe('useGitStatus', () => {
|
||||
await unmount()
|
||||
})
|
||||
|
||||
it('publishes metadata-only changes while sharing the unchanged file rows', async () => {
|
||||
gitStatus.mockResolvedValue(snapshot({ upstream: 'origin/main', ahead: 0, behind: 0, detached: false }))
|
||||
let view: GitStatusView | undefined
|
||||
const { unmount } = await mount(createElement(Probe, {
|
||||
scope: { sessionId: 's-metadata' }, onView: (next) => { view = next },
|
||||
}))
|
||||
try {
|
||||
const updates: Partial<GitStatusResult>[] = [
|
||||
{ upstream: 'origin/review' }, { ahead: 1 }, { behind: 2 }, { detached: true },
|
||||
{ operation: 'merge' }, { operation: 'rebase' }, { operation: undefined },
|
||||
]
|
||||
for (const update of updates) {
|
||||
const before = view!.snapshot!
|
||||
const next = { ...before, ...update }
|
||||
gitStatus.mockResolvedValue(next)
|
||||
await act(async () => { view?.refresh(); await Promise.resolve(); await Promise.resolve() })
|
||||
expect(view!.snapshot).toBe(next)
|
||||
expect(view!.snapshot!.entries).toBe(before.entries)
|
||||
}
|
||||
} finally {
|
||||
await unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('invalidateGitStatus re-reads every live key of one session', async () => {
|
||||
gitStatus.mockResolvedValue(snapshot())
|
||||
const { unmount } = await mount(createElement(Probe, { scope: { sessionId: 's6' }, onView: () => {} }))
|
||||
|
||||
Reference in new issue
Block a user