mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat: add MiniScanner component and git service tests
- Extract session busy indicator to reusable MiniScanner component - Refactor SessionCard to use MiniScanner for cleaner code - Add comprehensive tests for GitBranchService, GitDiffService - Add repo-git route tests
This commit is contained in:
1 parent
7f30a28be9
commit
570a67e7b0
5 files changed
+1259
-9
No files matched your search
@@ -0,0 +1,282 @@
|
||||
import { describe, it, expect, vi, beforeEach, type MockedFunction } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import { createRepoGitRoutes } from '../../src/routes/repo-git'
|
||||
import * as db from '../../src/db/queries'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/db/queries', () => ({
|
||||
getRepoById: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/process', () => ({
|
||||
executeCommand: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
getReposPath: vi.fn(() => '/repos'),
|
||||
}))
|
||||
|
||||
const getRepoByIdMock = db.getRepoById as MockedFunction<typeof db.getRepoById>
|
||||
|
||||
describe('Repo Git Routes', () => {
|
||||
let app: Hono
|
||||
let mockDatabase: Database
|
||||
let mockGitAuthService: GitAuthService
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockDatabase = {
|
||||
run: vi.fn(),
|
||||
prepare: vi.fn(() => ({
|
||||
run: vi.fn(),
|
||||
get: vi.fn(),
|
||||
all: vi.fn(),
|
||||
iterate: vi.fn(),
|
||||
values: vi.fn(),
|
||||
})),
|
||||
exec: vi.fn(),
|
||||
query: vi.fn(),
|
||||
inTransaction: vi.fn(),
|
||||
close: vi.fn(),
|
||||
} as unknown as Database
|
||||
mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue({}),
|
||||
} as unknown as GitAuthService
|
||||
app = createRepoGitRoutes(mockDatabase, mockGitAuthService)
|
||||
})
|
||||
|
||||
describe('POST /git-status-batch', () => {
|
||||
it('returns 400 when repoIds is not an array', async () => {
|
||||
const response = await app.request('/git-status-batch', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ repoIds: 'not-an-array' }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'repoIds must be an array of numbers')
|
||||
})
|
||||
|
||||
it('returns 400 when repoIds contains non-numbers', async () => {
|
||||
const response = await app.request('/git-status-batch', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ repoIds: [1, 'two', 3] }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'repoIds must be an array of numbers')
|
||||
})
|
||||
|
||||
it('returns empty object when no repos found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/git-status-batch', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ repoIds: [1, 2, 3] }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toEqual({})
|
||||
})
|
||||
|
||||
it('returns status for multiple repos', async () => {
|
||||
const { executeCommand } = await import('../../src/utils/process')
|
||||
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
|
||||
|
||||
getRepoByIdMock.mockImplementation((_, id) => {
|
||||
if (id === 1) return { id: 1, fullPath: '/repo1' } as any
|
||||
if (id === 2) return { id: 2, fullPath: '/repo2' } as any
|
||||
return null
|
||||
})
|
||||
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
if (args.includes('status')) return Promise.resolve('')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const response = await app.request('/git-status-batch', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ repoIds: [1, 2] }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('1')
|
||||
expect(body).toHaveProperty('2')
|
||||
})
|
||||
|
||||
it('skips repos that fail and continues with others', async () => {
|
||||
const { executeCommand } = await import('../../src/utils/process')
|
||||
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
|
||||
|
||||
getRepoByIdMock.mockImplementation((_, id) => {
|
||||
if (id === 1) return { id: 1, fullPath: '/repo1' } as any
|
||||
if (id === 2) return null
|
||||
return null
|
||||
})
|
||||
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
if (args.includes('status')) return Promise.resolve('')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const response = await app.request('/git-status-batch', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ repoIds: [1, 2] }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('1')
|
||||
expect(body).not.toHaveProperty('2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /:id/git/diff-full', () => {
|
||||
it('returns 400 when path parameter is missing', async () => {
|
||||
const response = await app.request('/1/git/diff-full')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'path query parameter is required')
|
||||
})
|
||||
|
||||
it('returns 404 when repo does not exist', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/999/git/diff-full?path=file.ts')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('returns diff with includeStaged=true', async () => {
|
||||
const { executeCommand } = await import('../../src/utils/process')
|
||||
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
|
||||
|
||||
getRepoByIdMock.mockReturnValue({ id: 1, localPath: 'test-repo' } as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) return Promise.resolve('+added line')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const response = await app.request('/1/git/diff-full?path=file.ts&includeStaged=true')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('path')
|
||||
expect(body).toHaveProperty('diff')
|
||||
expect(body).toHaveProperty('additions')
|
||||
expect(body).toHaveProperty('deletions')
|
||||
})
|
||||
|
||||
it('returns diff with includeStaged=false', async () => {
|
||||
const { executeCommand } = await import('../../src/utils/process')
|
||||
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
|
||||
|
||||
getRepoByIdMock.mockReturnValue({ id: 1, localPath: 'test-repo' } as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) return Promise.resolve('-removed line')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const response = await app.request('/1/git/diff-full?path=file.ts&includeStaged=false')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('deletions')
|
||||
})
|
||||
|
||||
it('returns 500 when diff operation fails', async () => {
|
||||
const { executeCommand } = await import('../../src/utils/process')
|
||||
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
|
||||
|
||||
getRepoByIdMock.mockReturnValue({ id: 1, localPath: 'test-repo' } as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) return Promise.reject(new Error('Diff failed'))
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const response = await app.request('/1/git/diff-full?path=file.ts')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /:id/git/branches', () => {
|
||||
it('returns 404 when repo does not exist', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/999/git/branches')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('returns branches and status', async () => {
|
||||
const { executeCommand } = await import('../../src/utils/process')
|
||||
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
|
||||
|
||||
getRepoByIdMock.mockReturnValue({ id: 1, fullPath: '/path/to/repo' } as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('branch')) return Promise.resolve('* main abc123 [origin/main] Initial commit')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const response = await app.request('/1/git/branches')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('branches')
|
||||
expect(body).toHaveProperty('status')
|
||||
expect(Array.isArray((body as { branches: unknown[] }).branches)).toBe(true)
|
||||
})
|
||||
|
||||
it('returns 500 when branch operation fails', async () => {
|
||||
const { executeCommand } = await import('../../src/utils/process')
|
||||
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
|
||||
|
||||
getRepoByIdMock.mockReturnValue({ id: 1, fullPath: '/path/to/repo' } as any)
|
||||
executeCommandMock.mockRejectedValue(new Error('Git operation failed'))
|
||||
|
||||
const response = await app.request('/1/git/branches')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,446 @@
|
||||
import { describe, it, expect, vi, beforeEach, type MockedFunction } from 'vitest'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { GitAuthService } from '../../../src/services/git-auth'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/utils/process', () => ({
|
||||
executeCommand: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/db/queries', () => ({
|
||||
getRepoById: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { GitBranchService } from '../../../src/services/git/GitBranchService'
|
||||
import { executeCommand } from '../../../src/utils/process'
|
||||
import { getRepoById } from '../../../src/db/queries'
|
||||
|
||||
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
|
||||
const getRepoByIdMock = getRepoById as MockedFunction<typeof getRepoById>
|
||||
|
||||
describe('GitBranchService', () => {
|
||||
let service: GitBranchService
|
||||
let database: Database
|
||||
let mockGitAuthService: GitAuthService
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
database = {} as Database
|
||||
mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue({}),
|
||||
} as unknown as GitAuthService
|
||||
service = new GitBranchService(mockGitAuthService)
|
||||
})
|
||||
|
||||
describe('getBranches', () => {
|
||||
it('returns list of local branches', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('branch')) return Promise.resolve('* main abc123 [origin/main] Initial commit\n feature def456 [origin/feature] Feature work')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getBranches(1, database)
|
||||
|
||||
expect(result).toHaveLength(2)
|
||||
expect(result[0]).toMatchObject({ name: 'main', type: 'local', current: true })
|
||||
expect(result[1]).toMatchObject({ name: 'feature', type: 'local', current: false })
|
||||
})
|
||||
|
||||
it('returns remote branches with remotes/ prefix', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('branch')) return Promise.resolve('* main abc123\n remotes/origin/main def456\n remotes/origin/develop ghi789')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getBranches(1, database)
|
||||
|
||||
expect(result.filter(b => b.type === 'remote')).toHaveLength(2)
|
||||
expect(result.find(b => b.name === 'remotes/origin/main')).toMatchObject({ type: 'remote' })
|
||||
})
|
||||
|
||||
it('parses upstream tracking info with ahead/behind', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('feature')
|
||||
if (args.includes('branch')) return Promise.resolve('* feature abc123 [origin/feature: ahead 3, behind 2] Work in progress')
|
||||
if (args.includes('rev-list')) return Promise.resolve('3 2')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getBranches(1, database)
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
name: 'feature',
|
||||
upstream: 'origin/feature',
|
||||
ahead: 3,
|
||||
behind: 2,
|
||||
})
|
||||
})
|
||||
|
||||
it('parses upstream with only ahead count', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('branch')) return Promise.resolve('* main abc123 [origin/main: ahead 5] Latest changes')
|
||||
if (args.includes('rev-list')) return Promise.resolve('5 0')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getBranches(1, database)
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
upstream: 'origin/main',
|
||||
ahead: 5,
|
||||
behind: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('parses upstream with only behind count', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('branch')) return Promise.resolve('* main abc123 [origin/main: behind 3] Old version')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 3')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getBranches(1, database)
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
upstream: 'origin/main',
|
||||
ahead: 0,
|
||||
behind: 3,
|
||||
})
|
||||
})
|
||||
|
||||
it('sorts branches: current first, then local, then remote, alphabetically', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('feature')
|
||||
if (args.includes('branch')) {
|
||||
return Promise.resolve(
|
||||
' main abc123\n' +
|
||||
'* feature def456\n' +
|
||||
' remotes/origin/main ghi789\n' +
|
||||
' another jkl012\n' +
|
||||
' remotes/origin/develop mno345'
|
||||
)
|
||||
}
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getBranches(1, database)
|
||||
|
||||
expect(result[0]!.name).toBe('feature')
|
||||
expect(result[0]!.current).toBe(true)
|
||||
expect(result.slice(1, 3).every((b) => b.type === 'local')).toBe(true)
|
||||
expect(result.slice(3).every((b) => b.type === 'remote')).toBe(true)
|
||||
})
|
||||
|
||||
it('deduplicates branch names', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('branch')) return Promise.resolve('* main abc123\n main def456')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getBranches(1, database)
|
||||
|
||||
expect(result.filter(b => b.name === 'main')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('handles current branch rev-parse failure gracefully', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.reject(new Error('Not a git repo'))
|
||||
if (args.includes('branch')) return Promise.resolve('* main abc123\n feature def456')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getBranches(1, database)
|
||||
|
||||
expect(result).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('fetches branch status for current branch without ahead/behind', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('branch')) return Promise.resolve('* main abc123 Initial commit')
|
||||
if (args.includes('rev-list')) return Promise.resolve('1 2')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getBranches(1, database)
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
name: 'main',
|
||||
current: true,
|
||||
ahead: 1,
|
||||
behind: 2,
|
||||
})
|
||||
})
|
||||
|
||||
it('handles getBranchStatus failure for current branch gracefully', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
let revListCalls = 0
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('branch')) return Promise.resolve('* main abc123 Initial commit')
|
||||
if (args.includes('rev-list')) {
|
||||
revListCalls++
|
||||
return Promise.reject(new Error('No upstream'))
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getBranches(1, database)
|
||||
|
||||
expect(result[0]!.name).toBe('main')
|
||||
expect(result[0]!.ahead).toBe(0)
|
||||
expect(result[0]!.behind).toBe(0)
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.getBranches(999, database)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('throws error when branch command fails', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('branch')) return Promise.reject(new Error('Not a git repository'))
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
await expect(service.getBranches(1, database)).rejects.toThrow('Not a git repository')
|
||||
})
|
||||
|
||||
it('handles empty branch output', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('branch')) return Promise.resolve('')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getBranches(1, database)
|
||||
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('skips lines with empty branch names', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('branch')) return Promise.resolve('* main abc123\n \n feature def456')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getBranches(1, database)
|
||||
|
||||
expect(result).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getBranchStatus', () => {
|
||||
it('returns correct ahead/behind counts', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('3\t5')
|
||||
|
||||
const result = await service.getBranchStatus(1, database)
|
||||
|
||||
expect(result).toEqual({ ahead: 3, behind: 5 })
|
||||
})
|
||||
|
||||
it('returns zeros when no upstream', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockRejectedValue(new Error('No upstream branch'))
|
||||
|
||||
const result = await service.getBranchStatus(1, database)
|
||||
|
||||
expect(result).toEqual({ ahead: 0, behind: 0 })
|
||||
})
|
||||
|
||||
it('returns zeros when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
const result = await service.getBranchStatus(999, database)
|
||||
|
||||
expect(result).toEqual({ ahead: 0, behind: 0 })
|
||||
})
|
||||
|
||||
it('handles malformed rev-list output', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('invalid')
|
||||
|
||||
const result = await service.getBranchStatus(1, database)
|
||||
|
||||
expect(result).toEqual({ ahead: 0, behind: 0 })
|
||||
})
|
||||
|
||||
it('handles space-separated ahead/behind output', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('7 2')
|
||||
|
||||
const result = await service.getBranchStatus(1, database)
|
||||
|
||||
expect(result).toEqual({ ahead: 7, behind: 2 })
|
||||
})
|
||||
|
||||
it('handles only ahead count correctly', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('5\t0')
|
||||
|
||||
const result = await service.getBranchStatus(1, database)
|
||||
|
||||
expect(result).toEqual({ ahead: 5, behind: 0 })
|
||||
})
|
||||
|
||||
it('handles only behind count correctly', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('0\t3')
|
||||
|
||||
const result = await service.getBranchStatus(1, database)
|
||||
|
||||
expect(result).toEqual({ ahead: 0, behind: 3 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('createBranch', () => {
|
||||
it('creates and switches to new branch', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue("Switched to a new branch 'feature-branch'")
|
||||
|
||||
const result = await service.createBranch(1, 'feature-branch', database)
|
||||
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', expect.stringContaining('/path/to/repo'), 'checkout', '-b', 'feature-branch'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toBe("Switched to a new branch 'feature-branch'")
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.createBranch(999, 'new-branch', database)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('throws error when branch already exists', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockRejectedValue(new Error("fatal: a branch named 'existing' already exists"))
|
||||
|
||||
await expect(service.createBranch(1, 'existing', database)).rejects.toThrow("fatal: a branch named 'existing' already exists")
|
||||
})
|
||||
})
|
||||
|
||||
describe('switchBranch', () => {
|
||||
it('switches to existing branch', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue("Switched to branch 'main'")
|
||||
|
||||
const result = await service.switchBranch(1, 'main', database)
|
||||
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', expect.stringContaining('/path/to/repo'), 'checkout', 'main'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toBe("Switched to branch 'main'")
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.switchBranch(999, 'main', database)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('throws error when branch does not exist', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockRejectedValue(new Error("error: pathspec 'nonexistent' did not match any file(s)"))
|
||||
|
||||
await expect(service.switchBranch(1, 'nonexistent', database)).rejects.toThrow("error: pathspec 'nonexistent' did not match any file(s)")
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasCommits', () => {
|
||||
it('returns true when HEAD exists', async () => {
|
||||
executeCommandMock.mockResolvedValue('abc123def456')
|
||||
|
||||
const result = await service.hasCommits('/path/to/repo')
|
||||
|
||||
expect(result).toBe(true)
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', '/path/to/repo', 'rev-parse', 'HEAD'],
|
||||
{ silent: true }
|
||||
)
|
||||
})
|
||||
|
||||
it('returns false when no commits exist', async () => {
|
||||
executeCommandMock.mockRejectedValue(new Error("fatal: ambiguous argument 'HEAD': unknown revision"))
|
||||
|
||||
const result = await service.hasCommits('/path/to/fresh-repo')
|
||||
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false for non-git directory', async () => {
|
||||
executeCommandMock.mockRejectedValue(new Error('fatal: not a git repository'))
|
||||
|
||||
const result = await service.hasCommits('/path/to/not-a-repo')
|
||||
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,440 @@
|
||||
import { describe, it, expect, vi, beforeEach, type MockedFunction } from 'vitest'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { GitAuthService } from '../../../src/services/git-auth'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/utils/process', () => ({
|
||||
executeCommand: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/db/queries', () => ({
|
||||
getRepoById: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
getReposPath: vi.fn(() => '/repos'),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { GitDiffService } from '../../../src/services/git/GitDiffService'
|
||||
import { executeCommand } from '../../../src/utils/process'
|
||||
import { getRepoById } from '../../../src/db/queries'
|
||||
|
||||
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
|
||||
const getRepoByIdMock = getRepoById as MockedFunction<typeof getRepoById>
|
||||
|
||||
describe('GitDiffService', () => {
|
||||
let service: GitDiffService
|
||||
let database: Database
|
||||
let mockGitAuthService: GitAuthService
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
database = {} as Database
|
||||
mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue({}),
|
||||
} as unknown as GitAuthService
|
||||
service = new GitDiffService(mockGitAuthService)
|
||||
})
|
||||
|
||||
describe('getFileDiff', () => {
|
||||
it('returns diff for untracked file (empty status output)', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('')
|
||||
if (args.includes('--no-index')) {
|
||||
return Promise.resolve(
|
||||
'diff --git a/dev/null b/newfile.ts\n' +
|
||||
'--- /dev/null\n' +
|
||||
'+++ b/newfile.ts\n' +
|
||||
'+export const hello = "world";\n' +
|
||||
'+export const foo = "bar";'
|
||||
)
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'newfile.ts', database)
|
||||
|
||||
expect(result.status).toBe('untracked')
|
||||
expect(result.additions).toBe(2)
|
||||
expect(result.deletions).toBe(0)
|
||||
expect(result.isBinary).toBe(false)
|
||||
})
|
||||
|
||||
it('returns diff for modified tracked file with staged changes', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff') && args.includes('HEAD')) {
|
||||
return Promise.resolve(
|
||||
'diff --git a/file.ts b/file.ts\n' +
|
||||
'--- a/file.ts\n' +
|
||||
'+++ b/file.ts\n' +
|
||||
'-const old = "value";\n' +
|
||||
'+const new = "value";\n' +
|
||||
'+const added = true;'
|
||||
)
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'file.ts', database, { includeStaged: true })
|
||||
|
||||
expect(result.status).toBe('modified')
|
||||
expect(result.additions).toBe(2)
|
||||
expect(result.deletions).toBe(1)
|
||||
})
|
||||
|
||||
it('returns diff for unstaged changes only', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('MM file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff') && !args.includes('HEAD')) {
|
||||
return Promise.resolve(
|
||||
'diff --git a/file.ts b/file.ts\n' +
|
||||
'--- a/file.ts\n' +
|
||||
'+++ b/file.ts\n' +
|
||||
'-unstaged change'
|
||||
)
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'file.ts', database, { includeStaged: false })
|
||||
|
||||
expect(result.status).toBe('modified')
|
||||
expect(result.deletions).toBe(1)
|
||||
})
|
||||
|
||||
it('handles file with no porcelain output as untracked', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('')
|
||||
if (args.includes('--no-index')) return Promise.resolve('+new content')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'file.ts', database)
|
||||
|
||||
expect(result.status).toBe('untracked')
|
||||
})
|
||||
|
||||
it('handles status command failure as untracked', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.reject(new Error('Git error'))
|
||||
if (args.includes('--no-index')) return Promise.resolve('+content')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'file.ts', database)
|
||||
|
||||
expect(result.status).toBe('untracked')
|
||||
})
|
||||
|
||||
it('returns special message for new file with no commits', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('A newfile.ts')
|
||||
if (args.includes('rev-parse')) return Promise.reject(new Error('No commits'))
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'newfile.ts', database)
|
||||
|
||||
expect(result.status).toBe('added')
|
||||
expect(result.diff).toContain('New file (no commits yet)')
|
||||
expect(result.additions).toBe(0)
|
||||
expect(result.deletions).toBe(0)
|
||||
expect(result.isBinary).toBe(false)
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.getFileDiff(999, 'file.ts', database)).rejects.toThrow('Repository not found: 999')
|
||||
})
|
||||
|
||||
it('throws error when diff command fails', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) return Promise.reject(new Error('Diff failed'))
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
await expect(service.getFileDiff(1, 'file.ts', database)).rejects.toThrow('Failed to get file diff: Diff failed')
|
||||
})
|
||||
|
||||
it('applies showContext option', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) {
|
||||
expect(args).toContain('-U10')
|
||||
return Promise.resolve('diff output')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
await service.getFileDiff(1, 'file.ts', database, { showContext: 10 })
|
||||
})
|
||||
|
||||
it('applies ignoreWhitespace option', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) {
|
||||
expect(args).toContain('--ignore-all-space')
|
||||
return Promise.resolve('diff output')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
await service.getFileDiff(1, 'file.ts', database, { ignoreWhitespace: true })
|
||||
})
|
||||
|
||||
it('applies unified option', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) {
|
||||
expect(args).toContain('--unified=true')
|
||||
return Promise.resolve('diff output')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
await service.getFileDiff(1, 'file.ts', database, { unified: true })
|
||||
})
|
||||
|
||||
it('detects binary files from "Binary files" message', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M image.png')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) return Promise.resolve('Binary files a/image.png and b/image.png differ')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'image.png', database)
|
||||
|
||||
expect(result.isBinary).toBe(true)
|
||||
expect(result.additions).toBe(0)
|
||||
expect(result.deletions).toBe(0)
|
||||
})
|
||||
|
||||
it('detects binary files from "GIT binary patch" message', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M data.bin')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) return Promise.resolve('GIT binary patch\nliteral 1234\n...')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'data.bin', database)
|
||||
|
||||
expect(result.isBinary).toBe(true)
|
||||
})
|
||||
|
||||
it('handles untracked file with object result from executeCommand', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('')
|
||||
if (args.includes('--no-index')) {
|
||||
return Promise.resolve({ stdout: '+new line\n+another line' } as any)
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'newfile.ts', database)
|
||||
|
||||
expect(result.status).toBe('untracked')
|
||||
expect(result.additions).toBe(2)
|
||||
})
|
||||
|
||||
it('defaults includeStaged to true', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
let diffArgsUsed: string[] = []
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) {
|
||||
diffArgsUsed = args as string[]
|
||||
return Promise.resolve('diff output')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
await service.getFileDiff(1, 'file.ts', database)
|
||||
|
||||
expect(diffArgsUsed).toContain('HEAD')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFullDiff', () => {
|
||||
it('delegates to getFileDiff', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) return Promise.resolve('+added line')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFullDiff(1, 'file.ts', database)
|
||||
|
||||
expect(result.status).toBe('modified')
|
||||
expect(result.additions).toBe(1)
|
||||
})
|
||||
|
||||
it('passes options through to getFileDiff', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) {
|
||||
expect(args).toContain('--ignore-all-space')
|
||||
return Promise.resolve('diff output')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
await service.getFullDiff(1, 'file.ts', database, { ignoreWhitespace: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseDiffOutput (through public methods)', () => {
|
||||
it('correctly counts additions and deletions', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) {
|
||||
return Promise.resolve(
|
||||
'--- a/file.ts\n' +
|
||||
'+++ b/file.ts\n' +
|
||||
'-removed line 1\n' +
|
||||
'-removed line 2\n' +
|
||||
'+added line 1\n' +
|
||||
'+added line 2\n' +
|
||||
'+added line 3\n' +
|
||||
' unchanged line'
|
||||
)
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'file.ts', database)
|
||||
|
||||
expect(result.additions).toBe(3)
|
||||
expect(result.deletions).toBe(2)
|
||||
})
|
||||
|
||||
it('does not count --- and +++ header lines', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) {
|
||||
return Promise.resolve(
|
||||
'--- a/file.ts\n' +
|
||||
'+++ b/file.ts\n' +
|
||||
'+only real addition'
|
||||
)
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'file.ts', database)
|
||||
|
||||
expect(result.additions).toBe(1)
|
||||
expect(result.deletions).toBe(0)
|
||||
})
|
||||
|
||||
it('returns empty path when filePath is not provided', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('?? ')
|
||||
if (args.includes('--no-index')) return Promise.resolve('+content')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, '', database)
|
||||
|
||||
expect(result.path).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasCommits (through getFileDiff)', () => {
|
||||
it('returns true when HEAD exists', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('M file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.resolve('abc123')
|
||||
if (args.includes('diff')) return Promise.resolve('diff output')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'file.ts', database)
|
||||
|
||||
expect(result.diff).toBe('diff output')
|
||||
})
|
||||
|
||||
it('returns false when no commits exist', async () => {
|
||||
const mockRepo = { id: 1, localPath: 'test-repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('A file.ts')
|
||||
if (args.includes('rev-parse')) return Promise.reject(new Error('No commits'))
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'file.ts', database)
|
||||
|
||||
expect(result.diff).toContain('New file (no commits yet)')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { MiniScanner } from "@/components/ui/mini-scanner";
|
||||
import { Trash2, Clock } from "lucide-react";
|
||||
import { formatDistanceToNow } from "date-fns";
|
||||
import type { Session } from "@/api/types";
|
||||
import { useSessionStatusForSession } from "@/stores/sessionStatusStore";
|
||||
|
||||
interface SessionCardProps {
|
||||
session: Session;
|
||||
@@ -22,8 +22,6 @@ export const SessionCard = ({
|
||||
onToggleSelection,
|
||||
onDelete,
|
||||
}: SessionCardProps) => {
|
||||
const sessionStatus = useSessionStatusForSession(session.id);
|
||||
const isSessionBusy = sessionStatus.type === 'busy' || sessionStatus.type === 'retry' || sessionStatus.type === 'compact';
|
||||
|
||||
return (
|
||||
<Card
|
||||
@@ -49,12 +47,7 @@ export const SessionCard = ({
|
||||
}}
|
||||
className="w-5 h-5 flex-shrink-0"
|
||||
/>
|
||||
{isSessionBusy && (
|
||||
<span className="relative flex h-2.5 w-2.5 flex-shrink-0">
|
||||
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
|
||||
<span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-green-500"></span>
|
||||
</span>
|
||||
)}
|
||||
<MiniScanner sessionID={session.id} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { useSessionStatusForSession, type SessionStatusType } from '@/stores/sessionStatusStore'
|
||||
|
||||
interface MiniScannerProps {
|
||||
sessionID: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
const SCANNER_WIDTH = 6
|
||||
const SCANNER_SEGMENTS = 12
|
||||
|
||||
export const MiniScanner = memo(function MiniScanner({
|
||||
sessionID,
|
||||
className = ''
|
||||
}: MiniScannerProps) {
|
||||
const status = useSessionStatusForSession(sessionID)
|
||||
const [position, setPosition] = useState(0)
|
||||
const [direction, setDirection] = useState(1)
|
||||
|
||||
useEffect(() => {
|
||||
if (status.type !== 'busy' && status.type !== 'retry' && status.type !== 'compact') {
|
||||
return
|
||||
}
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setPosition(prev => {
|
||||
const next = prev + direction
|
||||
if (next >= SCANNER_SEGMENTS - SCANNER_WIDTH) {
|
||||
setDirection(-1)
|
||||
return SCANNER_SEGMENTS - SCANNER_WIDTH
|
||||
}
|
||||
if (next <= 0) {
|
||||
setDirection(1)
|
||||
return 0
|
||||
}
|
||||
return next
|
||||
})
|
||||
}, 60)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [status.type, direction])
|
||||
|
||||
const getSegmentColor = (index: number, statusType: SessionStatusType['type']) => {
|
||||
if (statusType === 'idle') {
|
||||
return 'bg-transparent'
|
||||
}
|
||||
|
||||
const distance = Math.abs(index - (position + SCANNER_WIDTH / 2))
|
||||
const maxDistance = SCANNER_WIDTH / 2
|
||||
|
||||
if (distance > maxDistance + 1) {
|
||||
return 'bg-muted/20'
|
||||
}
|
||||
|
||||
const intensity = Math.max(0, 1 - distance / (maxDistance + 2))
|
||||
|
||||
if (statusType === 'retry') {
|
||||
if (intensity > 0.8) return 'bg-amber-500'
|
||||
if (intensity > 0.5) return 'bg-amber-500/70'
|
||||
if (intensity > 0.2) return 'bg-amber-500/40'
|
||||
return 'bg-amber-500/20'
|
||||
}
|
||||
|
||||
if (statusType === 'compact') {
|
||||
if (intensity > 0.8) return 'bg-purple-500'
|
||||
if (intensity > 0.5) return 'bg-purple-500/70'
|
||||
if (intensity > 0.2) return 'bg-purple-500/40'
|
||||
return 'bg-purple-500/20'
|
||||
}
|
||||
|
||||
if (intensity > 0.8) return 'bg-blue-500'
|
||||
if (intensity > 0.5) return 'bg-blue-500/70'
|
||||
if (intensity > 0.2) return 'bg-blue-500/40'
|
||||
return 'bg-blue-500/20'
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`flex items-center ${className}`}>
|
||||
<div className="flex gap-0.5">
|
||||
{Array.from({ length: SCANNER_SEGMENTS }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={`w-0.5 h-2 rounded-sm transition-colors duration-75 ${getSegmentColor(i, status.type)}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
Reference in new issue
Block a user