Show committed files in the "source control" tab (#181)

* refactor: auto-review fixes and UI improvements

- Remove dead code and fix type assertion in getBranchDiff
- Tighten GitDiffBinaryResult type constraint
- Fix race condition in CombinedDiffViewer with generationRef
- Fix reference stability in setGitBranchCompareResult
- Extract LazySection component to fix max-lines lint
- Update filesystem IPC to match updated signatures
- Adjust file explorer item spacing and font size

* fix: correct test expectation for staged diff header label
This commit is contained in:
Jinjing
2026-03-28 17:00:40 -07:00
committed by GitHub
parent dbab855611
commit 3644aa8f29
21 changed files with 2956 additions and 670 deletions
+123 -27
View File
@@ -20,7 +20,7 @@ vi.mock('fs/promises', () => ({
rm: rmMock
}))
import { discardChanges, getDiff, isWithinWorktree } from './status'
import { discardChanges, getBranchCompare, getDiff, isWithinWorktree } from './status'
describe('discardChanges', () => {
beforeEach(() => {
@@ -88,39 +88,135 @@ describe('getDiff', () => {
readFileMock.mockReset()
})
it('returns base64 payloads for unstaged image diffs', async () => {
execFileAsyncMock.mockResolvedValueOnce({
stdout: Buffer.from([0x89, 0x50, 0x4e, 0x47])
})
readFileMock.mockResolvedValueOnce(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00]))
it('uses the index as the left side for unstaged diffs when present', async () => {
execFileAsyncMock.mockResolvedValueOnce({ stdout: Buffer.from('index-content\n') })
readFileMock.mockResolvedValue(Buffer.from('working-tree-content'))
await expect(getDiff('/repo', 'image.png', false)).resolves.toEqual({
originalContent: Buffer.from([0x89, 0x50, 0x4e, 0x47]).toString('base64'),
modifiedContent: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00]).toString('base64'),
isImage: true,
mimeType: 'image/png'
})
const result = await getDiff('/repo', 'src/file.ts', false)
expect(execFileAsyncMock).toHaveBeenCalledWith('git', ['show', 'HEAD:image.png'], {
cwd: '/repo',
encoding: 'buffer',
maxBuffer: 10 * 1024 * 1024
expect(execFileAsyncMock).toHaveBeenCalledWith(
'git',
['show', ':src/file.ts'],
expect.objectContaining({
cwd: '/repo',
encoding: 'buffer',
maxBuffer: 10 * 1024 * 1024
})
)
expect(readFileMock).toHaveBeenCalledWith('/repo/src/file.ts')
expect(result).toEqual({
kind: 'text',
originalContent: 'index-content\n',
modifiedContent: 'working-tree-content',
originalIsBinary: false,
modifiedIsBinary: false
})
expect(readFileMock).toHaveBeenCalledWith('/repo/image.png')
})
it('returns base64 payloads for staged image diffs', async () => {
it('falls back to HEAD for unstaged diffs when the file is not in the index', async () => {
execFileAsyncMock
.mockResolvedValueOnce({ stdout: Buffer.from([0x01, 0x02]) })
.mockResolvedValueOnce({ stdout: Buffer.from([0x03, 0x04]) })
.mockRejectedValueOnce(new Error('missing index'))
.mockResolvedValueOnce({ stdout: Buffer.from('head-content\n') })
readFileMock.mockResolvedValue(Buffer.from('working-tree-content'))
await expect(getDiff('/repo', 'image.png', true)).resolves.toEqual({
originalContent: Buffer.from([0x01, 0x02]).toString('base64'),
modifiedContent: Buffer.from([0x03, 0x04]).toString('base64'),
isImage: true,
mimeType: 'image/png'
})
const result = await getDiff('/repo', 'src/file.ts', false)
expect(readFileMock).not.toHaveBeenCalled()
expect(execFileAsyncMock).toHaveBeenNthCalledWith(
2,
'git',
['show', 'HEAD:src/file.ts'],
expect.objectContaining({
cwd: '/repo',
encoding: 'buffer',
maxBuffer: 10 * 1024 * 1024
})
)
expect(result.originalContent).toBe('head-content\n')
expect(result.modifiedContent).toBe('working-tree-content')
})
it('marks binary content in the diff payload', async () => {
execFileAsyncMock.mockResolvedValueOnce({ stdout: Buffer.from([0x00, 0x61, 0x62]) })
readFileMock.mockResolvedValue(Buffer.from('working-tree-content'))
const result = await getDiff('/repo', 'src/file.bin', false)
expect(result.kind).toBe('binary')
expect(result.originalIsBinary).toBe(true)
expect(result.modifiedIsBinary).toBe(false)
})
})
describe('getBranchCompare', () => {
beforeEach(() => {
execFileAsyncMock.mockReset()
readFileMock.mockReset()
})
it('returns a pinned branch compare snapshot and parsed branch entries', async () => {
execFileAsyncMock
.mockResolvedValueOnce({ stdout: 'main\n' })
.mockResolvedValueOnce({ stdout: 'head-oid\n' })
.mockResolvedValueOnce({ stdout: 'base-oid\n' })
.mockResolvedValueOnce({ stdout: 'merge-base-oid\n' })
.mockResolvedValueOnce({
stdout: 'M\tfile-a.ts\nR100\told-name.ts\tnew-name.ts\nC100\told-copy.ts\tnew-copy.ts\n'
})
.mockResolvedValueOnce({ stdout: '7\n' })
const result = await getBranchCompare('/repo', 'origin/main')
expect(result.summary).toEqual({
baseRef: 'origin/main',
baseOid: 'base-oid',
compareRef: 'main',
headOid: 'head-oid',
mergeBase: 'merge-base-oid',
changedFiles: 3,
commitsAhead: 7,
status: 'ready'
})
expect(result.entries).toEqual([
{ path: 'file-a.ts', status: 'modified' },
{ path: 'new-name.ts', oldPath: 'old-name.ts', status: 'renamed' },
{ path: 'new-copy.ts', oldPath: 'old-copy.ts', status: 'copied' }
])
})
it('returns invalid-base when the compare ref does not resolve', async () => {
execFileAsyncMock
.mockResolvedValueOnce({ stdout: 'main\n' })
.mockResolvedValueOnce({ stdout: 'head-oid\n' })
.mockRejectedValueOnce(new Error('missing base'))
const result = await getBranchCompare('/repo', 'origin/missing')
expect(result.summary.status).toBe('invalid-base')
expect(result.summary.errorMessage).toContain('origin/missing')
expect(result.entries).toEqual([])
})
it('returns unborn-head when HEAD cannot be resolved', async () => {
execFileAsyncMock.mockRejectedValueOnce(new Error('unborn'))
const result = await getBranchCompare('/repo', 'origin/main')
expect(result.summary.status).toBe('unborn-head')
expect(result.summary.errorMessage).toContain('committed HEAD')
expect(result.entries).toEqual([])
})
it('returns no-merge-base when histories do not intersect', async () => {
execFileAsyncMock
.mockResolvedValueOnce({ stdout: 'main\n' })
.mockResolvedValueOnce({ stdout: 'head-oid\n' })
.mockResolvedValueOnce({ stdout: 'base-oid\n' })
.mockRejectedValueOnce(new Error('no merge base'))
const result = await getBranchCompare('/repo', 'origin/main')
expect(result.summary.status).toBe('no-merge-base')
expect(result.summary.errorMessage).toContain('merge base')
expect(result.entries).toEqual([])
})
})
+323 -69
View File
@@ -1,20 +1,20 @@
/* eslint-disable max-lines */
import { execFile } from 'child_process'
import { readFile, rm } from 'fs/promises'
import { promisify } from 'util'
import * as path from 'path'
import type { GitStatusEntry, GitFileStatus, GitDiffResult } from '../../shared/types'
import type {
GitBranchChangeEntry,
GitBranchChangeStatus,
GitBranchCompareResult,
GitBranchCompareSummary,
GitDiffResult,
GitFileStatus,
GitStatusEntry
} from '../../shared/types'
const execFileAsync = promisify(execFile)
const IMAGE_MIME_TYPES: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
'.ico': 'image/x-icon'
}
const MAX_GIT_SHOW_BYTES = 10 * 1024 * 1024
/**
* Parse `git status --porcelain=v2` output into structured entries.
@@ -97,6 +97,23 @@ function parseStatusChar(char: string): GitFileStatus {
}
}
function parseBranchStatusChar(char: string): GitBranchChangeStatus {
switch (char) {
case 'M':
return 'modified'
case 'A':
return 'added'
case 'D':
return 'deleted'
case 'R':
return 'renamed'
case 'C':
return 'copied'
default:
return 'modified'
}
}
/**
* Get original and modified content for diffing a file.
*/
@@ -105,91 +122,328 @@ export async function getDiff(
filePath: string,
staged: boolean
): Promise<GitDiffResult> {
const mimeType = IMAGE_MIME_TYPES[path.extname(filePath).toLowerCase()]
if (mimeType) {
const originalBuffer = await readGitFileVersion(worktreePath, filePath, 'head')
const modifiedBuffer = staged
? await readGitFileVersion(worktreePath, filePath, 'index')
: await readWorkingTreeFile(worktreePath, filePath)
return {
originalContent: originalBuffer?.toString('base64') ?? '',
modifiedContent: modifiedBuffer?.toString('base64') ?? '',
isImage: true,
mimeType
}
}
let originalContent = ''
let modifiedContent = ''
let originalIsBinary = false
let modifiedIsBinary = false
try {
// Get original content (HEAD version)
try {
const { stdout } = await execFileAsync('git', ['show', `HEAD:${filePath}`], {
cwd: worktreePath,
encoding: 'utf-8',
maxBuffer: 10 * 1024 * 1024
})
originalContent = stdout
} catch {
// File is new (no HEAD version)
originalContent = ''
}
const leftBlob = staged
? await readGitBlobAtOidPath(worktreePath, 'HEAD', filePath)
: await readUnstagedLeftBlob(worktreePath, filePath)
originalContent = leftBlob.content
originalIsBinary = leftBlob.isBinary
if (staged) {
// Staged: modified is the index version
try {
const { stdout } = await execFileAsync('git', ['show', `:${filePath}`], {
cwd: worktreePath,
encoding: 'utf-8',
maxBuffer: 10 * 1024 * 1024
})
modifiedContent = stdout
} catch {
modifiedContent = ''
}
const rightBlob = await readGitBlobAtIndexPath(worktreePath, filePath)
modifiedContent = rightBlob.content
modifiedIsBinary = rightBlob.isBinary
} else {
// Unstaged: modified is the working tree version
try {
modifiedContent = await readFile(path.join(worktreePath, filePath), 'utf-8')
} catch {
modifiedContent = ''
}
const workingTreeBlob = await readWorkingTreeFile(path.join(worktreePath, filePath))
modifiedContent = workingTreeBlob.content
modifiedIsBinary = workingTreeBlob.isBinary
}
} catch {
// Fallback
}
return { originalContent, modifiedContent }
return buildDiffResult(originalContent, modifiedContent, originalIsBinary, modifiedIsBinary)
}
async function readGitFileVersion(
export async function getBranchCompare(
worktreePath: string,
filePath: string,
source: 'head' | 'index'
): Promise<Buffer | null> {
baseRef: string
): Promise<GitBranchCompareResult> {
const summary: GitBranchCompareSummary = {
baseRef,
baseOid: null,
compareRef: 'HEAD',
headOid: null,
mergeBase: null,
changedFiles: 0,
status: 'loading'
}
const compareRef = await resolveCompareRef(worktreePath)
summary.compareRef = compareRef
let headOid = ''
try {
const objectSpec = source === 'head' ? `HEAD:${filePath}` : `:${filePath}`
const { stdout } = await execFileAsync('git', ['show', objectSpec], {
headOid = await resolveRefOid(worktreePath, 'HEAD')
summary.headOid = headOid
} catch {
summary.status = 'unborn-head'
summary.errorMessage =
'This branch does not have a committed HEAD yet, so compare-to-base is unavailable.'
return { summary, entries: [] }
}
let baseOid = ''
try {
baseOid = await resolveRefOid(worktreePath, baseRef)
summary.baseOid = baseOid
} catch {
summary.status = 'invalid-base'
summary.errorMessage = `Base ref ${baseRef} could not be resolved in this repository.`
return { summary, entries: [] }
}
let mergeBase = ''
try {
mergeBase = await resolveMergeBase(worktreePath, baseOid, headOid)
summary.mergeBase = mergeBase
} catch {
summary.status = 'no-merge-base'
summary.errorMessage = `This branch and ${baseRef} do not share a merge base, so compare-to-base is unavailable.`
return { summary, entries: [] }
}
try {
const entries = await loadBranchChanges(worktreePath, mergeBase, headOid)
const commitsAhead = await countAheadCommits(worktreePath, baseOid, headOid)
summary.changedFiles = entries.length
summary.commitsAhead = commitsAhead
summary.status = 'ready'
return { summary, entries }
} catch (error) {
summary.status = 'error'
summary.errorMessage = error instanceof Error ? error.message : 'Failed to load branch compare'
return { summary, entries: [] }
}
}
export async function getBranchDiff(
worktreePath: string,
args: {
headOid: string
mergeBase: string
filePath: string
oldPath?: string
}
): Promise<GitDiffResult> {
try {
const leftPath = args.oldPath ?? args.filePath
const leftBlob = await readGitBlobAtOidPath(worktreePath, args.mergeBase, leftPath)
const rightBlob = await readGitBlobAtOidPath(worktreePath, args.headOid, args.filePath)
return buildDiffResult(
leftBlob.content,
rightBlob.content,
leftBlob.isBinary,
rightBlob.isBinary
)
} catch {
return {
kind: 'text',
originalContent: '',
modifiedContent: '',
originalIsBinary: false,
modifiedIsBinary: false
}
}
}
async function loadBranchChanges(
worktreePath: string,
mergeBase: string,
headOid: string
): Promise<GitBranchChangeEntry[]> {
const { stdout } = await execFileAsync(
'git',
['diff', '--name-status', '-M', '-C', mergeBase, headOid],
{
cwd: worktreePath,
encoding: 'utf-8',
maxBuffer: MAX_GIT_SHOW_BYTES
}
)
const entries: GitBranchChangeEntry[] = []
for (const line of stdout.split('\n')) {
if (!line) {
continue
}
const entry = parseBranchChangeLine(line)
if (entry) {
entries.push(entry)
}
}
return entries
}
function parseBranchChangeLine(line: string): GitBranchChangeEntry | null {
const parts = line.split('\t')
const rawStatus = parts[0] ?? ''
const status = parseBranchStatusChar(rawStatus[0] ?? 'M')
if (rawStatus.startsWith('R') || rawStatus.startsWith('C')) {
const oldPath = parts[1]
const path = parts[2]
if (!path) {
return null
}
return { path, oldPath, status }
}
const path = parts[1]
if (!path) {
return null
}
return { path, status }
}
async function resolveCompareRef(worktreePath: string): Promise<string> {
try {
const { stdout } = await execFileAsync('git', ['branch', '--show-current'], {
cwd: worktreePath,
encoding: 'utf-8'
})
const branch = stdout.trim()
return branch || 'HEAD'
} catch {
return 'HEAD'
}
}
async function resolveRefOid(worktreePath: string, ref: string): Promise<string> {
const { stdout } = await execFileAsync('git', ['rev-parse', '--verify', ref], {
cwd: worktreePath,
encoding: 'utf-8'
})
return stdout.trim()
}
async function resolveMergeBase(
worktreePath: string,
baseOid: string,
headOid: string
): Promise<string> {
const { stdout } = await execFileAsync('git', ['merge-base', baseOid, headOid], {
cwd: worktreePath,
encoding: 'utf-8'
})
return stdout.trim()
}
async function countAheadCommits(
worktreePath: string,
baseOid: string,
headOid: string
): Promise<number> {
const { stdout } = await execFileAsync('git', ['rev-list', '--count', `${baseOid}..${headOid}`], {
cwd: worktreePath,
encoding: 'utf-8'
})
return Number.parseInt(stdout.trim(), 10) || 0
}
async function readUnstagedLeftBlob(
worktreePath: string,
filePath: string
): Promise<GitBlobReadResult> {
const indexBlob = await readGitBlobAtIndexPath(worktreePath, filePath)
if (indexBlob.exists) {
return indexBlob
}
return readGitBlobAtOidPath(worktreePath, 'HEAD', filePath)
}
async function readGitBlobAtIndexPath(
worktreePath: string,
filePath: string
): Promise<GitBlobReadResult> {
try {
const { stdout } = (await execFileAsync('git', ['show', `:${filePath}`], {
cwd: worktreePath,
encoding: 'buffer',
maxBuffer: 10 * 1024 * 1024
})
return stdout
maxBuffer: MAX_GIT_SHOW_BYTES
})) as { stdout: Buffer }
return { ...bufferToBlob(stdout), exists: true }
} catch {
return null
return { content: '', isBinary: false, exists: false }
}
}
async function readWorkingTreeFile(worktreePath: string, filePath: string): Promise<Buffer | null> {
async function readGitBlobAtOidPath(
worktreePath: string,
oid: string,
filePath: string
): Promise<GitBlobReadResult> {
try {
return await readFile(path.join(worktreePath, filePath))
const { stdout } = (await execFileAsync('git', ['show', `${oid}:${filePath}`], {
cwd: worktreePath,
encoding: 'buffer',
maxBuffer: MAX_GIT_SHOW_BYTES
})) as { stdout: Buffer }
return { ...bufferToBlob(stdout), exists: true }
} catch {
return null
return { content: '', isBinary: false, exists: false }
}
}
async function readWorkingTreeFile(filePath: string): Promise<GitBlobReadResult> {
try {
const buffer = await readFile(filePath)
return bufferToBlob(buffer)
} catch {
return { content: '', isBinary: false, exists: false }
}
}
function bufferToBlob(buffer: Buffer): GitBlobReadResult {
const isBinary = isBinaryBuffer(buffer)
return {
content: isBinary ? '' : buffer.toString('utf-8'),
isBinary,
exists: true
}
}
function isBinaryBuffer(buffer: Buffer): boolean {
const len = Math.min(buffer.length, 8192)
for (let i = 0; i < len; i += 1) {
if (buffer[i] === 0) {
return true
}
}
return false
}
function buildDiffResult(
originalContent: string,
modifiedContent: string,
originalIsBinary: boolean,
modifiedIsBinary: boolean
): GitDiffResult {
if (originalIsBinary || modifiedIsBinary) {
return {
kind: 'binary',
originalContent,
modifiedContent,
originalIsBinary,
modifiedIsBinary
} as GitDiffResult
}
return {
kind: 'text',
originalContent,
modifiedContent,
originalIsBinary: false,
modifiedIsBinary: false
}
}
type GitBlobReadResult = {
content: string
isBinary: boolean
exists: boolean
}
/**
* Stage a file.
*/