Refactor: Consolidate git services into single GitService class + Settings dialog improvements (#111)

* refactor: consolidate git services into single GitService class

Merges GitBranchService, GitCommitService, GitDiffService, GitFetchPullService,
GitLogService, GitPushService, and GitStatusService into one cohesive GitService
that simplifies architecture and follows SOLID principles. Updates all route
handlers and tests to use the new consolidated service. Moves GitBranch interface
to shared types location.

* Refactor settings dialog to use URL-based state management with tab synchronization

* Update social preview image
This commit is contained in:
Chris Scott authored and GitHub committed 2026-02-06 21:59:18 -05:00
1 parent b5eef317bd
commit e3716bb294
27 files changed
+1393 -2958

No files matched your search

@@ -1,444 +0,0 @@
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)
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.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)
})
})
})
@@ -1,233 +0,0 @@
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().mockImplementation(() => ({
getSettings: vi.fn().mockReturnValue({
preferences: {
gitIdentity: null,
gitCredentials: [],
},
}),
})),
}))
vi.mock('../../../src/utils/process', () => ({
executeCommand: vi.fn(),
}))
vi.mock('../../../src/db/queries', () => ({
getRepoById: vi.fn(),
}))
vi.mock('../../../src/utils/git-auth', () => ({
resolveGitIdentity: vi.fn().mockResolvedValue(null),
createGitIdentityEnv: vi.fn().mockReturnValue({}),
createSilentGitEnv: vi.fn(),
}))
import { GitCommitService } from '../../../src/services/git/GitCommitService'
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('GitCommitService', () => {
let service: GitCommitService
let database: Database
let mockGitAuthService: GitAuthService
beforeEach(() => {
vi.clearAllMocks()
database = {} as Database
mockGitAuthService = {
getGitEnvironment: vi.fn().mockReturnValue({}),
} as unknown as GitAuthService
service = new GitCommitService(mockGitAuthService)
})
describe('commit', () => {
it('commits staged changes with message', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('[main abc1234] Test commit\n 1 file changed')
const result = await service.commit(1, 'Test commit', database)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'commit', '-m', 'Test commit'],
{ env: expect.any(Object) }
)
expect(result).toBe('[main abc1234] Test commit\n 1 file changed')
})
it('commits specific staged files', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('[main abc1234] Commit specific files\n 2 files changed')
const result = await service.commit(1, 'Commit specific files', database, ['file1.ts', 'file2.ts'])
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'commit', '-m', 'Commit specific files', '--', 'file1.ts', 'file2.ts'],
{ env: expect.any(Object) }
)
expect(result).toBe('[main abc1234] Commit specific files\n 2 files changed')
})
it('throws error when repository not found', async () => {
getRepoByIdMock.mockReturnValue(null)
await expect(service.commit(999, 'Test', database)).rejects.toThrow('Repository not found')
})
it('throws error when commit command fails', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockRejectedValue(new Error('Nothing to commit'))
await expect(service.commit(1, 'Test', database)).rejects.toThrow('Nothing to commit')
})
})
describe('stageFiles', () => {
it('stages files', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('')
const result = await service.stageFiles(1, ['file1.ts', 'file2.ts'], database)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'add', '--', 'file1.ts', 'file2.ts'],
{ env: expect.any(Object) }
)
expect(result).toBe('')
})
it('returns early when no files to stage', async () => {
const result = await service.stageFiles(1, [], database)
expect(executeCommandMock).not.toHaveBeenCalled()
expect(result).toBe('')
})
it('throws error when repository not found', async () => {
getRepoByIdMock.mockReturnValue(null)
await expect(service.stageFiles(999, ['file.ts'], database)).rejects.toThrow('Repository not found')
})
it('throws error when stage command fails', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockRejectedValue(new Error('Pathspec error'))
await expect(service.stageFiles(1, ['invalid.txt'], database)).rejects.toThrow('Pathspec error')
})
})
describe('unstageFiles', () => {
it('unstages files', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('')
const result = await service.unstageFiles(1, ['file1.ts', 'file2.ts'], database)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'restore', '--staged', '--', 'file1.ts', 'file2.ts'],
{ env: expect.any(Object) }
)
expect(result).toBe('')
})
it('returns early when no files to unstage', async () => {
const result = await service.unstageFiles(1, [], database)
expect(executeCommandMock).not.toHaveBeenCalled()
expect(result).toBe('')
})
it('throws error when repository not found', async () => {
getRepoByIdMock.mockReturnValue(null)
await expect(service.unstageFiles(999, ['file.ts'], database)).rejects.toThrow('Repository not found')
})
it('throws error when unstage command fails', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockRejectedValue(new Error('Error unstaging'))
await expect(service.unstageFiles(1, ['file.ts'], database)).rejects.toThrow('Error unstaging')
})
})
describe('resetToCommit', () => {
it('resets to specific commit', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('HEAD is now at abc123')
const result = await service.resetToCommit(1, 'abc123', database)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'reset', '--hard', 'abc123'],
{ env: expect.any(Object) }
)
expect(result).toBe('HEAD is now at abc123')
})
it('throws error when repository not found', async () => {
getRepoByIdMock.mockReturnValue(null)
await expect(service.resetToCommit(999, 'abc123', database)).rejects.toThrow('Repository not found')
})
it('throws error when reset command fails', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockRejectedValue(new Error('Invalid commit hash'))
await expect(service.resetToCommit(1, 'invalid', database)).rejects.toThrow('Invalid commit hash')
})
})
})
@@ -1,440 +0,0 @@
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,379 +0,0 @@
import { describe, it, expect, vi, beforeEach, type MockedFunction } from 'vitest'
vi.mock('bun:sqlite', () => ({
Database: vi.fn()
}))
vi.mock('../../../src/services/settings', () => ({
SettingsService: vi.fn()
}))
import { GitLogService } from '../../../src/services/git/GitLogService'
import type { Database } from 'bun:sqlite'
import { executeCommand } from '../../../src/utils/process'
import { getRepoById } from '../../../src/db/queries'
const mockGitAuthService = {
getGitEnvironment: vi.fn(),
}
const mockGitDiffService = {
getFileDiff: vi.fn(),
}
vi.mock('../../../src/utils/process', () => ({
executeCommand: vi.fn(),
}))
vi.mock('../../../src/db/queries', () => ({
getRepoById: vi.fn(),
}))
vi.mock('../../../src/services/git-auth', () => ({
GitAuthService: vi.fn().mockImplementation(() => mockGitAuthService),
}))
vi.mock('@opencode-manager/shared/config/env', () => ({
getReposPath: vi.fn(() => '/repos'),
}))
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
const getRepoByIdMock = getRepoById as MockedFunction<typeof getRepoById>
describe('GitLogService', () => {
let service: GitLogService
let database: Database
beforeEach(() => {
vi.clearAllMocks()
database = {} as Database
service = new GitLogService(mockGitAuthService as any, mockGitDiffService as any)
mockGitAuthService.getGitEnvironment.mockResolvedValue({})
})
describe('getLog', () => {
it('returns list of commits', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock
.mockResolvedValueOnce(
'abc123|John Doe|john@example.com|1704110400|First commit\n' +
'def456|Jane Smith|jane@example.com|1704200400|Second commit'
)
.mockResolvedValueOnce('')
const result = await service.getLog(1, database, 10)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', '/repos/test-repo', 'log', '--all', '-n', '10', '--format=%H|%an|%ae|%at|%s'],
{ env: expect.any(Object) }
)
expect(result).toHaveLength(2)
expect(result[0]).toEqual({
hash: 'abc123',
authorName: 'John Doe',
authorEmail: 'john@example.com',
date: '1704110400',
message: 'First commit',
unpushed: false,
})
expect(result[1]).toEqual({
hash: 'def456',
authorName: 'Jane Smith',
authorEmail: 'jane@example.com',
date: '1704200400',
message: 'Second commit',
unpushed: false,
})
})
it('respects limit parameter', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock
.mockResolvedValueOnce('abc123|John Doe|john@example.com|1704110400|First commit')
.mockResolvedValueOnce('')
await service.getLog(1, database, 5)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', '/repos/test-repo', 'log', '--all', '-n', '5', '--format=%H|%an|%ae|%at|%s'],
{ env: expect.any(Object) }
)
})
it('handles commits with empty messages', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock
.mockResolvedValueOnce('abc123|John Doe|john@example.com|1704110400|')
.mockResolvedValueOnce('')
const result = await service.getLog(1, database, 10)
expect(result).toHaveLength(1)
expect(result[0]?.message).toBe('')
})
it('handles commits with multi-line messages', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock
.mockResolvedValueOnce('abc123|John Doe|john@example.com|1704110400|Multi|line commit')
.mockResolvedValueOnce('')
const result = await service.getLog(1, database, 10)
expect(result).toHaveLength(1)
expect(result[0]?.message).toBe('Multi|line commit')
})
it('handles empty log output', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock
.mockResolvedValueOnce('')
.mockResolvedValueOnce('')
const result = await service.getLog(1, database, 10)
expect(result).toEqual([])
})
it('handles whitespace lines in output', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock
.mockResolvedValueOnce('\n\nabc123|John Doe|john@example.com|1704110400|Test\n\n')
.mockResolvedValueOnce('')
const result = await service.getLog(1, database, 10)
expect(result).toHaveLength(1)
expect(result[0]?.hash).toBe('abc123')
})
it('skips lines without hash', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock
.mockResolvedValueOnce('|John Doe|john@example.com|1704110400|No hash')
.mockResolvedValueOnce('')
const result = await service.getLog(1, database, 10)
expect(result).toEqual([])
})
it('throws error when repository not found', async () => {
getRepoByIdMock.mockReturnValue(null)
await expect(service.getLog(999, database, 10)).rejects.toThrow('Repository not found: 999')
})
it('throws error when log command fails', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockRejectedValue(new Error('Not a git repository'))
await expect(service.getLog(1, database, 10)).rejects.toThrow('Failed to get git log')
})
it('handles commits with empty timestamps', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock
.mockResolvedValueOnce(
'abc123|John Doe|john@example.com|1704110400|Valid commit\n' +
'def456|Jane Smith|jane@example.com||Empty timestamp\n'
)
.mockResolvedValueOnce('')
const result = await service.getLog(1, database, 10)
expect(result).toHaveLength(2)
expect(result[0]).toEqual({
hash: 'abc123',
authorName: 'John Doe',
authorEmail: 'john@example.com',
date: '1704110400',
message: 'Valid commit',
unpushed: false,
})
expect(result[1]?.date).toBe('')
})
it('handles commits with missing date field', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock
.mockResolvedValueOnce('abc123|John Doe|john@example.com')
.mockResolvedValueOnce('')
const result = await service.getLog(1, database, 10)
expect(result).toHaveLength(1)
expect(result[0]).toEqual({
hash: 'abc123',
authorName: 'John Doe',
authorEmail: 'john@example.com',
date: '',
message: '',
unpushed: false,
})
})
})
describe('getCommit', () => {
it('returns commit details for valid hash', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('abc123|John Doe|john@example.com|1704110400|Test commit')
const result = await service.getCommit(1, 'abc123', database)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', '/repos/test-repo', 'log', '--format=%H|%an|%ae|%at|%s', 'abc123', '-1'],
{ env: expect.any(Object) }
)
expect(result).toEqual({
hash: 'abc123',
authorName: 'John Doe',
authorEmail: 'john@example.com',
date: '1704110400',
message: 'Test commit',
})
})
it('returns null when commit hash not found', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('')
const result = await service.getCommit(1, 'nonexistent', database)
expect(result).toBeNull()
})
it('returns null when output is empty', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue(' ')
const result = await service.getCommit(1, 'abc123', database)
expect(result).toBeNull()
})
it('returns null when hash field is empty', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('|John Doe|john@example.com|1704110400|Test')
const result = await service.getCommit(1, 'abc123', database)
expect(result).toBeNull()
})
it('handles commits with empty messages', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('abc123|John Doe|john@example.com|1704110400|')
const result = await service.getCommit(1, 'abc123', database)
expect(result).not.toBeNull()
expect(result?.message).toBe('')
})
it('throws error when repository not found', async () => {
getRepoByIdMock.mockReturnValue(null)
await expect(service.getCommit(999, 'abc123', database)).rejects.toThrow('Repository not found: 999')
})
it('throws error when command fails', async () => {
const mockRepo = {
id: 1,
localPath: 'test-repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockRejectedValue(new Error('Invalid commit hash'))
await expect(service.getCommit(1, 'invalid', database)).rejects.toThrow('Failed to get commit')
})
})
describe('getDiff', () => {
it('returns diff for file', async () => {
const expectedDiff = 'diff --git a/file.ts b/file.ts\nindex 123..456 100644\n--- a/file.ts\n+++ b/file.ts\n@@ -1,1 +1,1 @@\n-old line\n+new line'
mockGitDiffService.getFileDiff.mockResolvedValue({ diff: expectedDiff })
const result = await service.getDiff(1, 'file.ts', database)
expect(mockGitDiffService.getFileDiff).toHaveBeenCalledWith(1, 'file.ts', database)
expect(result).toBe(expectedDiff)
})
it('returns empty diff when file has no changes', async () => {
mockGitDiffService.getFileDiff.mockResolvedValue({ diff: '' })
const result = await service.getDiff(1, 'file.ts', database)
expect(result).toBe('')
})
it('throws error when diff command fails', async () => {
mockGitDiffService.getFileDiff.mockRejectedValue(new Error('Repository not found: 999'))
await expect(service.getDiff(999, 'file.ts', database)).rejects.toThrow('Repository not found: 999')
})
})
})
@@ -1,199 +0,0 @@
import { describe, it, expect, vi, beforeEach } 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/services/git/GitBranchService', () => ({
GitBranchService: vi.fn().mockImplementation(() => ({
getBranches: vi.fn().mockResolvedValue([
{
name: 'main',
type: 'local',
current: true,
upstream: 'origin/main'
},
{
name: 'feature-branch',
type: 'local',
current: false,
upstream: undefined
}
])
}))
}))
describe('GitPushService', () => {
let executeCommand: ReturnType<typeof vi.fn>
let getRepoById: ReturnType<typeof vi.fn>
let mockGitAuthService: GitAuthService
let mockBranchService: any
beforeEach(async () => {
vi.clearAllMocks()
const process = await import('../../../src/utils/process')
const queries = await import('../../../src/db/queries')
executeCommand = process.executeCommand as ReturnType<typeof vi.fn>
getRepoById = queries.getRepoById as ReturnType<typeof vi.fn>
mockGitAuthService = {
getGitEnvironment: vi.fn().mockReturnValue({}),
} as unknown as GitAuthService
const { GitBranchService } = await import('../../../src/services/git/GitBranchService')
mockBranchService = new GitBranchService(mockGitAuthService)
// Reset executeCommand to default resolved value
executeCommand.mockResolvedValue('Everything up-to-date')
})
describe('push', () => {
it('pushes changes to remote with existing upstream', async () => {
const { GitPushService } = await import('../../../src/services/git/GitPushService')
const service = new GitPushService(mockGitAuthService, mockBranchService)
const database = {} as Database
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoById.mockReturnValue(mockRepo)
executeCommand.mockResolvedValue('Everything up-to-date')
const result = await service.push(1, {}, database)
expect(getRepoById).toHaveBeenCalledWith(database, 1)
expect(executeCommand).toHaveBeenCalledWith(
['git', '-C', '/path/to/repo', 'push'],
{ env: expect.any(Object) }
)
expect(result).toBe('Everything up-to-date')
})
it('auto-creates remote branch when no upstream exists', async () => {
// Test the flow without triggering Bun's git error detection
const { isNoUpstreamError } = await import('../../../src/utils/git-errors')
const { GitPushService } = await import('../../../src/services/git/GitPushService')
const service = new GitPushService(mockGitAuthService, mockBranchService)
// Verify error detection works
const testError = new Error('The current branch feature-branch has no upstream branch')
expect(isNoUpstreamError(testError)).toBe(true)
// Test the service flow with a non-triggering error
const mockError = new Error('Push failed - no remote branch tracking configured')
const database = {} as Database
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoById.mockReturnValue(mockRepo)
executeCommand
.mockReset()
.mockRejectedValueOnce(mockError)
.mockResolvedValueOnce('feature-branch\n')
// This should throw since our mock error doesn't trigger upstream detection
await expect(service.push(1, {}, database)).rejects.toThrow('Push failed - no remote branch tracking configured')
})
it('respects setUpstream option', async () => {
const { GitPushService } = await import('../../../src/services/git/GitPushService')
const service = new GitPushService(mockGitAuthService, mockBranchService)
const database = {} as Database
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoById.mockReturnValue(mockRepo)
executeCommand
.mockReset()
.mockResolvedValueOnce('main\n')
.mockResolvedValueOnce('')
const result = await service.push(1, { setUpstream: true }, database)
expect(executeCommand).toHaveBeenNthCalledWith(
1,
['git', '-C', '/path/to/repo', 'rev-parse', '--abbrev-ref', 'HEAD'],
expect.any(Object)
)
expect(executeCommand).toHaveBeenNthCalledWith(
2,
['git', '-C', '/path/to/repo', 'push', '--set-upstream', 'origin', 'main'],
expect.any(Object)
)
expect(result).toBe('')
})
it('throws error when repository not found', async () => {
const { GitPushService } = await import('../../../src/services/git/GitPushService')
const service = new GitPushService(mockGitAuthService, mockBranchService)
const database = {} as Database
getRepoById.mockReturnValue(null)
await expect(service.push(999, {}, database)).rejects.toThrow('Repository not found')
})
it('throws error when push command fails with non-upstream error', async () => {
const { GitPushService } = await import('../../../src/services/git/GitPushService')
const service = new GitPushService(mockGitAuthService, mockBranchService)
const database = {} as Database
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
const authError = new Error('Authentication failed')
getRepoById.mockReturnValue(mockRepo)
executeCommand.mockRejectedValue(authError)
await expect(service.push(1, {}, database)).rejects.toThrow('Authentication failed')
})
// Note: Skipping due to Bun test runner issue with git error detection
it.skip('falls back to HEAD when branch detection fails during upstream retry', async () => {
// This test would verify fallback behavior when branch service fails
// but Bun's test runner treats any Error with "upstream" as real git error
})
})
describe('Git Error Utilities', () => {
it('detects no upstream branch error', async () => {
const { isNoUpstreamError } = await import('../../../src/utils/git-errors')
const error1 = new Error('The current branch main has no upstream branch')
const error2 = new Error('fatal: no upstream configured for branch')
const error3 = new Error('Authentication failed')
const error4 = new Error('no upstream branch')
expect(isNoUpstreamError(error1)).toBe(true)
expect(isNoUpstreamError(error2)).toBe(true)
expect(isNoUpstreamError(error3)).toBe(false)
expect(isNoUpstreamError(error4)).toBe(true)
})
it('parses branch name from error message', async () => {
const { parseBranchNameFromError } = await import('../../../src/utils/git-errors')
const error1 = new Error('The current branch feature-branch has no upstream branch')
const error2 = new Error('The current branch main has no upstream branch')
const error3 = new Error('Some other error')
expect(parseBranchNameFromError(error1)).toBe('feature-branch')
expect(parseBranchNameFromError(error2)).toBe('main')
expect(parseBranchNameFromError(error3)).toBe(null)
})
})
})
@@ -0,0 +1,523 @@
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().mockImplementation(() => ({
getSettings: vi.fn().mockReturnValue({
preferences: {
gitIdentity: null,
gitCredentials: [],
},
}),
})),
}))
vi.mock('../../../src/utils/process', () => ({
executeCommand: vi.fn(),
}))
vi.mock('../../../src/db/queries', () => ({
getRepoById: vi.fn(),
}))
vi.mock('../../../src/utils/git-auth', () => ({
resolveGitIdentity: vi.fn().mockResolvedValue(null),
createGitIdentityEnv: vi.fn().mockReturnValue({}),
createSilentGitEnv: vi.fn(),
}))
vi.mock('../../../src/utils/git-errors', () => ({
isNoUpstreamError: vi.fn().mockReturnValue(false),
parseBranchNameFromError: vi.fn().mockReturnValue(null),
}))
import { GitService } from '../../../src/services/git/GitService'
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('GitService', () => {
let service: GitService
let database: Database
let mockGitAuthService: GitAuthService
let mockSettingsService: any
beforeEach(() => {
vi.clearAllMocks()
database = {} as Database
mockGitAuthService = {
getGitEnvironment: vi.fn().mockReturnValue({}),
} as unknown as GitAuthService
mockSettingsService = {
getSettings: vi.fn().mockReturnValue({
preferences: {
gitIdentity: null,
gitCredentials: [],
},
}),
}
service = new GitService(mockGitAuthService, mockSettingsService)
})
describe('getStatus', () => {
it('returns empty status for clean repository', 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('rev-list')) return Promise.resolve('0 0')
if (args.includes('status')) return Promise.resolve('')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.branch).toBe('main')
expect(result.ahead).toBe(0)
expect(result.behind).toBe(0)
expect(result.files).toEqual([])
expect(result.hasChanges).toBe(false)
})
it('parses modified files correctly', 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('rev-list')) return Promise.resolve('0 0')
if (args.includes('status')) return Promise.resolve('MM file.ts')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.files).toHaveLength(1)
expect(result.files[0]).toEqual({ path: 'file.ts', status: 'modified', staged: true })
expect(result.hasChanges).toBe(true)
})
})
describe('getFileDiff', () => {
it('returns diff for untracked file', async () => {
const mockRepo = { id: 1, fullPath: '/path/to/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', async () => {
const mockRepo = { id: 1, fullPath: '/path/to/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 --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)
})
})
describe('getFullDiff', () => {
it('delegates to getFileDiff', async () => {
const mockRepo = { id: 1, fullPath: '/path/to/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, true)
expect(result.status).toBe('modified')
expect(result.additions).toBe(1)
})
})
describe('getLog', () => {
it('returns list of commits', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock
.mockResolvedValueOnce(
'abc123|John Doe|john@example.com|1704110400|First commit\n' +
'def456|Jane Smith|jane@example.com|1704200400|Second commit'
)
.mockResolvedValueOnce('')
const result = await service.getLog(1, database, 10)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(result).toHaveLength(2)
expect(result[0]).toEqual({
hash: 'abc123',
authorName: 'John Doe',
authorEmail: 'john@example.com',
date: '1704110400',
message: 'First commit',
unpushed: false,
})
expect(result[1]).toEqual({
hash: 'def456',
authorName: 'Jane Smith',
authorEmail: 'jane@example.com',
date: '1704200400',
message: 'Second commit',
unpushed: false,
})
})
it('handles empty log output', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValueOnce('').mockResolvedValueOnce('')
const result = await service.getLog(1, database, 10)
expect(result).toEqual([])
})
})
describe('getCommit', () => {
it('returns commit details for valid hash', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('abc123|John Doe|john@example.com|1704110400|Test commit')
const result = await service.getCommit(1, 'abc123', database)
expect(result).toEqual({
hash: 'abc123',
authorName: 'John Doe',
authorEmail: 'john@example.com',
date: '1704110400',
message: 'Test commit',
})
})
it('returns null when commit hash not found', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('')
const result = await service.getCommit(1, 'nonexistent', database)
expect(result).toBeNull()
})
})
describe('getDiff', () => {
it('returns diff for file', async () => {
const expectedDiff = 'diff --git a/file.ts b/file.ts\nindex 123..456 100644\n--- a/file.ts\n+++ b/file.ts\n@@ -1,1 +1,1 @@\n-old line\n+new line'
const mockRepo = { id: 1, fullPath: '/path/to/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(expectedDiff)
return Promise.resolve('')
})
const result = await service.getDiff(1, 'file.ts', database)
expect(result).toBe(expectedDiff)
})
})
describe('commit', () => {
it('commits staged changes with message', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('[main abc1234] Test commit\n 1 file changed')
const result = await service.commit(1, 'Test commit', database)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'commit', '-m', 'Test commit'],
{ env: expect.any(Object) }
)
expect(result).toBe('[main abc1234] Test commit\n 1 file changed')
})
it('commits specific staged files', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('[main abc1234] Commit specific files\n 2 files changed')
const result = await service.commit(1, 'Commit specific files', database, ['file1.ts', 'file2.ts'])
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'commit', '-m', 'Commit specific files', '--', 'file1.ts', 'file2.ts'],
{ env: expect.any(Object) }
)
expect(result).toBe('[main abc1234] Commit specific files\n 2 files changed')
})
})
describe('stageFiles', () => {
it('stages files', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('')
const result = await service.stageFiles(1, ['file1.ts', 'file2.ts'], database)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'add', '--', 'file1.ts', 'file2.ts'],
{ env: expect.any(Object) }
)
expect(result).toBe('')
})
it('returns early when no files to stage', async () => {
const result = await service.stageFiles(1, [], database)
expect(executeCommandMock).not.toHaveBeenCalled()
expect(result).toBe('')
})
})
describe('unstageFiles', () => {
it('unstages files', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('')
const result = await service.unstageFiles(1, ['file1.ts', 'file2.ts'], database)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'restore', '--staged', '--', 'file1.ts', 'file2.ts'],
{ env: expect.any(Object) }
)
expect(result).toBe('')
})
})
describe('resetToCommit', () => {
it('resets to specific commit', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockResolvedValue('HEAD is now at abc123')
const result = await service.resetToCommit(1, 'abc123', database)
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
expect(executeCommandMock).toHaveBeenCalledWith(
['git', '-C', mockRepo.fullPath, 'reset', '--hard', 'abc123'],
{ env: expect.any(Object) }
)
expect(result).toBe('HEAD is now at abc123')
})
})
describe('push', () => {
it('pushes changes to remote', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo)
executeCommandMock.mockResolvedValue('Everything up-to-date')
const result = await service.push(1, {}, database)
expect(getRepoById).toHaveBeenCalledWith(database, 1)
expect(executeCommand).toHaveBeenCalledWith(
['git', '-C', '/path/to/repo', 'push'],
{ env: expect.any(Object) }
)
expect(result).toBe('Everything up-to-date')
})
it('respects setUpstream option', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo)
executeCommandMock.mockResolvedValueOnce('main\n').mockResolvedValueOnce('')
await service.push(1, { setUpstream: true }, database)
expect(executeCommand).toHaveBeenNthCalledWith(
2,
['git', '-C', '/path/to/repo', 'push', '--set-upstream', 'origin', 'main'],
expect.any(Object)
)
})
})
describe('fetch', () => {
it('fetches from remote', async () => {
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
getRepoByIdMock.mockReturnValue(mockRepo)
executeCommandMock.mockResolvedValue('')
const result = await service.fetch(1, database)
expect(result).toBe('')
})
})
describe('pull', () => {
it('pulls from remote', async () => {
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
getRepoByIdMock.mockReturnValue(mockRepo)
executeCommandMock.mockResolvedValue('')
const result = await service.pull(1, database)
expect(result).toBe('')
})
})
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 })
})
})
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 })
})
})
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'")
})
})
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'")
})
})
})
@@ -1,341 +0,0 @@
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/git-auth', () => ({
createSilentGitEnv: vi.fn(),
}))
import { GitStatusService } from '../../../src/services/git/GitStatusService'
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('GitStatusService', () => {
let service: GitStatusService
let database: Database
let mockGitAuthService: GitAuthService
beforeEach(() => {
vi.clearAllMocks()
database = {} as Database
mockGitAuthService = {
getGitEnvironment: vi.fn().mockReturnValue({}),
} as unknown as GitAuthService
service = new GitStatusService(mockGitAuthService)
})
describe('getStatus', () => {
it('returns empty status for clean repository', 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('rev-list')) return Promise.resolve('0 0')
if (args.includes('status')) return Promise.resolve('')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.branch).toBe('main')
expect(result.ahead).toBe(0)
expect(result.behind).toBe(0)
expect(result.files).toEqual([])
expect(result.hasChanges).toBe(false)
})
it('parses modified files correctly', 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('rev-list')) return Promise.resolve('0 0')
if (args.includes('status')) return Promise.resolve('MM file.ts')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.files).toHaveLength(1)
expect(result.files[0]).toEqual({ path: 'file.ts', status: 'modified', staged: true })
expect(result.hasChanges).toBe(true)
})
it('parses staged files correctly', 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('rev-list')) return Promise.resolve('0 0')
if (args.includes('status')) return Promise.resolve('M file1.ts\nA file2.ts')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.files).toHaveLength(2)
expect(result.files[0]).toEqual({ path: 'file1.ts', status: 'modified', staged: true })
expect(result.files[1]).toEqual({ path: 'file2.ts', status: 'added', staged: true })
})
it('parses deleted files correctly', 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('rev-list')) return Promise.resolve('0 0')
if (args.includes('status')) return Promise.resolve('D file1.ts\n D file2.ts')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.files).toHaveLength(2)
expect(result.files[0]).toEqual({ path: 'file1.ts', status: 'deleted', staged: true })
expect(result.files[1]).toEqual({ path: 'file2.ts', status: 'deleted', staged: false })
})
it('parses renamed files correctly with arrow notation', 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('rev-list')) return Promise.resolve('0 0')
if (args.includes('status')) return Promise.resolve('R old.ts -> new.ts')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.files).toHaveLength(1)
expect(result.files[0]).toEqual({ path: 'new.ts', oldPath: 'old.ts', status: 'renamed', staged: true })
})
it('parses untracked files correctly', 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('rev-list')) return Promise.resolve('0 0')
if (args.includes('status')) return Promise.resolve('?? newfile.ts')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.files).toHaveLength(1)
expect(result.files[0]).toEqual({ path: 'newfile.ts', status: 'untracked', staged: false })
})
it('parses copied files correctly', 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('rev-list')) return Promise.resolve('0 0')
if (args.includes('status')) return Promise.resolve('C original.ts')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.files).toHaveLength(1)
expect(result.files[0]).toEqual({ path: 'original.ts', status: 'copied', staged: true })
})
it('parses mixed status 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('rev-list')) return Promise.resolve('0 0')
if (args.includes('status')) return Promise.resolve('MM file1.ts\nA file2.ts\n?? file3.ts\nD file4.ts')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.files).toHaveLength(4)
expect(result.files).toContainEqual({ path: 'file1.ts', status: 'modified', staged: true })
expect(result.files).toContainEqual({ path: 'file2.ts', status: 'added', staged: true })
expect(result.files).toContainEqual({ path: 'file3.ts', status: 'untracked', staged: false })
expect(result.files).toContainEqual({ path: 'file4.ts', status: 'deleted', staged: true })
})
it('returns branch status 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-branch')
if (args.includes('rev-list')) return Promise.resolve('2 3')
if (args.includes('status')) return Promise.resolve('')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.branch).toBe('feature-branch')
expect(result.ahead).toBe(2)
expect(result.behind).toBe(3)
})
it('handles branch status command 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('No upstream'))
if (args.includes('rev-list')) return Promise.reject(new Error('No upstream'))
if (args.includes('status')) return Promise.resolve('')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.branch).toBe('')
expect(result.ahead).toBe(0)
expect(result.behind).toBe(0)
})
it('throws error when repository not found', async () => {
getRepoByIdMock.mockReturnValue(null)
await expect(service.getStatus(999, database)).rejects.toThrow('Repository not found')
})
it('throws error when status command fails', async () => {
const mockRepo = {
id: 1,
fullPath: '/path/to/repo',
}
getRepoByIdMock.mockReturnValue(mockRepo as any)
executeCommandMock.mockRejectedValue(new Error('Not a git repository'))
await expect(service.getStatus(1, database)).rejects.toThrow('Not a git repository')
})
it('parses copied files correctly with arrow notation', 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('rev-list')) return Promise.resolve('0 0')
if (args.includes('status')) return Promise.resolve('C source.ts -> copy.ts')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.files).toHaveLength(1)
expect(result.files[0]).toEqual({ path: 'copy.ts', oldPath: 'source.ts', status: 'copied', staged: true })
})
it('preserves spaces in filenames without trimming', 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('rev-list')) return Promise.resolve('0 0')
if (args.includes('status')) return Promise.resolve('M path with spaces/file name.ts')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.files).toHaveLength(1)
expect(result.files[0]).toEqual({ path: 'path with spaces/file name.ts', status: 'modified', staged: true })
})
it('handles tab-separated ahead/behind 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('rev-list')) return Promise.resolve('5\t0')
if (args.includes('status')) return Promise.resolve('')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.ahead).toBe(5)
expect(result.behind).toBe(0)
})
it('handles only behind count correctly', 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('rev-list')) return Promise.resolve('0 7')
if (args.includes('status')) return Promise.resolve('')
return Promise.resolve('')
})
const result = await service.getStatus(1, database)
expect(result.ahead).toBe(0)
expect(result.behind).toBe(7)
})
})
})