mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Restore enhanced source control features from PR #138
PR #145 accidentally reverted all source control enhancements from PR #138. This cherry-picks those changes back: discard changes functionality, commit detail view, commit file diffs, diff truncation, and UI improvements.
This commit is contained in:
1 parent
3461f86556
commit
a911a2f759
18 files changed
+1611
-203
No files matched your search
@@ -17,6 +17,8 @@ paths-ignore:
|
||||
- '**/*.spec.tsx'
|
||||
- 'temp/**'
|
||||
- '**/*.md'
|
||||
- '**/test/**'
|
||||
- '**/__tests__/**'
|
||||
|
||||
# Specific files to ignore
|
||||
files-ignore:
|
||||
|
||||
@@ -303,6 +303,98 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/git/discard', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const body = await c.req.json()
|
||||
const { paths, staged } = body
|
||||
|
||||
if (!paths || !Array.isArray(paths)) {
|
||||
return c.json({ error: 'paths is required and must be an array' }, 400)
|
||||
}
|
||||
|
||||
await git.discardChanges(id, paths, staged ?? false, database)
|
||||
|
||||
const status = await git.getStatus(id, database)
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to discard changes:', error)
|
||||
const gitError = parseGitError(error)
|
||||
return c.json(
|
||||
{ error: gitError.summary, detail: gitError.detail, code: gitError.code },
|
||||
gitError.statusCode as ContentfulStatusCode
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/git/commit/:hash', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const hash = c.req.param('hash')
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
if (!hash) {
|
||||
return c.json({ error: 'hash is required' }, 400)
|
||||
}
|
||||
|
||||
const commitDetails = await git.getCommitDetails(id, hash, database)
|
||||
|
||||
if (!commitDetails) {
|
||||
return c.json({ error: 'Commit not found' }, 404)
|
||||
}
|
||||
|
||||
return c.json(commitDetails)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get commit details:', error)
|
||||
const gitError = parseGitError(error)
|
||||
return c.json(
|
||||
{ error: gitError.summary, detail: gitError.detail, code: gitError.code },
|
||||
gitError.statusCode as ContentfulStatusCode
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/git/commit/:hash/diff', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const hash = c.req.param('hash')
|
||||
const filePath = c.req.query('path')
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
if (!hash) {
|
||||
return c.json({ error: 'hash is required' }, 400)
|
||||
}
|
||||
|
||||
if (!filePath) {
|
||||
return c.json({ error: 'path query parameter is required' }, 400)
|
||||
}
|
||||
|
||||
const diff = await git.getCommitDiff(id, hash, filePath, database)
|
||||
return c.json(diff)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get commit diff:', error)
|
||||
const gitError = parseGitError(error)
|
||||
return c.json(
|
||||
{ error: gitError.summary, detail: gitError.detail, code: gitError.code },
|
||||
gitError.statusCode as ContentfulStatusCode
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/git/log', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
|
||||
@@ -7,7 +7,7 @@ import { resolveGitIdentity, createGitIdentityEnv, isSSHUrl } from '../../utils/
|
||||
import { isNoUpstreamError, parseBranchNameFromError } from '../../utils/git-errors'
|
||||
import { SettingsService } from '../settings'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { GitBranch, GitCommit, FileDiffResponse, GitDiffOptions, GitStatusResponse, GitFileStatus, GitFileStatusType } from '../../types/git'
|
||||
import type { GitBranch, GitCommit, FileDiffResponse, GitDiffOptions, GitStatusResponse, GitFileStatus, GitFileStatusType, CommitDetails, CommitFile } from '../../types/git'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
import path from 'path'
|
||||
|
||||
@@ -269,6 +269,252 @@ export class GitService {
|
||||
}
|
||||
}
|
||||
|
||||
async discardChanges(repoId: number, paths: string[], staged: boolean, database: Database): Promise<string> {
|
||||
try {
|
||||
const repo = getRepoById(database, repoId)
|
||||
if (!repo) {
|
||||
throw new Error(`Repository not found`)
|
||||
}
|
||||
|
||||
const repoPath = repo.fullPath
|
||||
const env = this.gitAuthService.getGitEnvironment()
|
||||
|
||||
if (paths.length === 0) {
|
||||
return ''
|
||||
}
|
||||
|
||||
if (staged) {
|
||||
const args = ['git', '-C', repoPath, 'restore', '--staged', '--worktree', '--source', 'HEAD', '--', ...paths]
|
||||
return await executeCommand(args, { env })
|
||||
}
|
||||
|
||||
const statusOutput = await executeCommand(
|
||||
['git', '-C', repoPath, 'status', '--porcelain', '-u', '--', ...paths],
|
||||
{ env }
|
||||
)
|
||||
|
||||
const untrackedPaths: string[] = []
|
||||
const trackedPaths: string[] = []
|
||||
|
||||
for (const line of statusOutput.split('\n')) {
|
||||
if (!line.trim()) continue
|
||||
const statusCode = line.substring(0, 2)
|
||||
const filePath = line.substring(3).trim()
|
||||
|
||||
if (statusCode === '??') {
|
||||
untrackedPaths.push(filePath)
|
||||
} else {
|
||||
trackedPaths.push(filePath)
|
||||
}
|
||||
}
|
||||
|
||||
const results: string[] = []
|
||||
|
||||
if (trackedPaths.length > 0) {
|
||||
const args = ['git', '-C', repoPath, 'checkout', '--', ...trackedPaths]
|
||||
results.push(await executeCommand(args, { env }))
|
||||
}
|
||||
|
||||
if (untrackedPaths.length > 0) {
|
||||
try {
|
||||
const args = ['git', '-C', repoPath, 'clean', '-fd', '--', ...untrackedPaths]
|
||||
results.push(await executeCommand(args, { env }))
|
||||
} catch (error: unknown) {
|
||||
logger.error(`Failed to clean untracked files for repo ${repoId}:`, error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
return results.join('\n')
|
||||
} catch (error: unknown) {
|
||||
logger.error(`Failed to discard changes for repo ${repoId}:`, error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private normalizeRenamePath(path: string): string {
|
||||
const renamePattern = /\{[^=]+=>\s*([^}]+)\}/
|
||||
let normalized = path
|
||||
while (renamePattern.test(normalized)) {
|
||||
normalized = normalized.replace(renamePattern, '$1')
|
||||
}
|
||||
return normalized.trim()
|
||||
}
|
||||
|
||||
private parseNumstatOutput(output: string): Map<string, { additions: number; deletions: number }> {
|
||||
const map = new Map<string, { additions: number; deletions: number }>()
|
||||
const lines = output.trim().split('\n')
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.trim()) continue
|
||||
|
||||
const parts = line.split('\t')
|
||||
if (parts.length >= 3) {
|
||||
const additions = parts[0]
|
||||
const deletions = parts[1]
|
||||
const filePath = parts.slice(2).join('\t')
|
||||
const normalizedPath = this.normalizeRenamePath(filePath)
|
||||
|
||||
if (
|
||||
additions?.match(/^\d+$/) &&
|
||||
deletions?.match(/^\d+$/) &&
|
||||
normalizedPath
|
||||
) {
|
||||
map.set(normalizedPath, {
|
||||
additions: parseInt(additions, 10),
|
||||
deletions: parseInt(deletions, 10)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return map
|
||||
}
|
||||
|
||||
private parseCommitFiles(
|
||||
output: string,
|
||||
numstatMap: Map<string, { additions: number; deletions: number }>
|
||||
): CommitFile[] {
|
||||
const files: CommitFile[] = []
|
||||
const lines = output.trim().split('\n')
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.trim()) continue
|
||||
|
||||
const parts = line.split('\t')
|
||||
if (parts.length >= 2 && parts[0] && parts[0].match(/^[AMDRC]/)) {
|
||||
const statusCode = parts[0]
|
||||
const fromPath = parts[1] || ''
|
||||
const toPath = parts[2] || parts[1] || ''
|
||||
const isRename = statusCode.startsWith('R')
|
||||
const isCopy = statusCode.startsWith('C')
|
||||
|
||||
let status: GitFileStatusType = 'modified'
|
||||
switch (statusCode.charAt(0)) {
|
||||
case 'A':
|
||||
status = 'added'
|
||||
break
|
||||
case 'D':
|
||||
status = 'deleted'
|
||||
break
|
||||
case 'R':
|
||||
status = 'renamed'
|
||||
break
|
||||
case 'C':
|
||||
status = 'copied'
|
||||
break
|
||||
case 'M':
|
||||
status = 'modified'
|
||||
break
|
||||
}
|
||||
|
||||
const numstatData = numstatMap.get(toPath)
|
||||
const additions = numstatData?.additions ?? 0
|
||||
const deletions = numstatData?.deletions ?? 0
|
||||
|
||||
files.push({
|
||||
path: toPath,
|
||||
status,
|
||||
oldPath: isRename || isCopy ? fromPath : undefined,
|
||||
additions,
|
||||
deletions
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
async getCommitDetails(repoId: number, hash: string, database: Database): Promise<CommitDetails | null> {
|
||||
try {
|
||||
const repo = getRepoById(database, repoId)
|
||||
if (!repo) {
|
||||
throw new Error(`Repository not found: ${repoId}`)
|
||||
}
|
||||
|
||||
const repoPath = path.resolve(repo.fullPath)
|
||||
const env = this.gitAuthService.getGitEnvironment(true)
|
||||
|
||||
const commitOutput = await executeCommand(
|
||||
['git', '-C', repoPath, 'log', '-1', '--format=%H%x00%an%x00%ae%x00%at%x00%B', hash],
|
||||
{ env }
|
||||
)
|
||||
|
||||
if (!commitOutput.trim()) {
|
||||
return null
|
||||
}
|
||||
|
||||
const parts = commitOutput.trim().split('\0')
|
||||
const [commitHash, authorName, authorEmail, timestamp, message] = parts
|
||||
|
||||
if (!commitHash) {
|
||||
return null
|
||||
}
|
||||
|
||||
const filesOutput = await executeCommand(
|
||||
['git', '-C', repoPath, 'show', '-M', '--name-status', '--format=', hash],
|
||||
{ env }
|
||||
)
|
||||
|
||||
const numstatOutput = await executeCommand(
|
||||
['git', '-C', repoPath, 'show', '-M', '--numstat', '--format=', hash],
|
||||
{ env }
|
||||
)
|
||||
|
||||
const numstatMap = this.parseNumstatOutput(numstatOutput)
|
||||
const files = this.parseCommitFiles(filesOutput, numstatMap)
|
||||
|
||||
return {
|
||||
hash: commitHash,
|
||||
authorName: authorName || '',
|
||||
authorEmail: authorEmail || '',
|
||||
date: timestamp || '',
|
||||
message: message || '',
|
||||
unpushed: await this.isCommitUnpushed(repoPath, commitHash, env),
|
||||
files
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
logger.error(`Failed to get commit details for repo ${repoId}:`, error)
|
||||
throw new Error(`Failed to get commit details: ${getErrorMessage(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async getCommitDiff(repoId: number, hash: string, filePath: string, database: Database): Promise<FileDiffResponse> {
|
||||
try {
|
||||
const repo = getRepoById(database, repoId)
|
||||
if (!repo) {
|
||||
throw new Error(`Repository not found: ${repoId}`)
|
||||
}
|
||||
|
||||
const repoPath = path.resolve(repo.fullPath)
|
||||
const env = this.gitAuthService.getGitEnvironment(true)
|
||||
|
||||
const diff = await executeCommand(
|
||||
['git', '-C', repoPath, 'show', '--format=', hash, '--', filePath],
|
||||
{ env }
|
||||
)
|
||||
|
||||
const status = this.detectDiffStatus(diff)
|
||||
return this.parseDiffOutput(diff, status, filePath)
|
||||
} catch (error: unknown) {
|
||||
logger.error(`Failed to get commit diff for repo ${repoId}:`, error)
|
||||
throw new Error(`Failed to get commit diff: ${getErrorMessage(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
private detectDiffStatus(diff: string): GitFileStatusType {
|
||||
if (diff.includes('new file mode')) {
|
||||
return 'added'
|
||||
}
|
||||
if (diff.includes('deleted file mode')) {
|
||||
return 'deleted'
|
||||
}
|
||||
if (diff.includes('rename from') || diff.includes('rename to')) {
|
||||
return 'renamed'
|
||||
}
|
||||
return 'modified'
|
||||
}
|
||||
|
||||
private async setupSSHIfNeeded(repoUrl: string | undefined, database: Database): Promise<void> {
|
||||
await this.gitAuthService.setupSSHForRepoUrl(repoUrl, database)
|
||||
}
|
||||
@@ -669,6 +915,7 @@ export class GitService {
|
||||
let additions = 0
|
||||
let deletions = 0
|
||||
let isBinary = false
|
||||
const MAX_DIFF_SIZE = 500 * 1024
|
||||
|
||||
if (typeof diff === 'string') {
|
||||
if (diff.includes('Binary files') || diff.includes('GIT binary patch')) {
|
||||
@@ -682,13 +929,21 @@ export class GitService {
|
||||
}
|
||||
}
|
||||
|
||||
let diffOutput = typeof diff === 'string' ? diff : ''
|
||||
let truncated = false
|
||||
if (diffOutput.length > MAX_DIFF_SIZE) {
|
||||
diffOutput = diffOutput.substring(0, MAX_DIFF_SIZE) + '\n\n... (diff truncated due to size)'
|
||||
truncated = true
|
||||
}
|
||||
|
||||
return {
|
||||
path: filePath || '',
|
||||
status: status as GitFileStatusType,
|
||||
diff: typeof diff === 'string' ? diff : '',
|
||||
diff: diffOutput,
|
||||
additions,
|
||||
deletions,
|
||||
isBinary
|
||||
isBinary,
|
||||
truncated
|
||||
}
|
||||
}
|
||||
|
||||
@@ -701,6 +956,11 @@ export class GitService {
|
||||
}
|
||||
}
|
||||
|
||||
private async isCommitUnpushed(repoPath: string, commitHash: string, env: Record<string, string>): Promise<boolean> {
|
||||
const unpushedHashes = await this.getUnpushedCommitHashes(repoPath, env)
|
||||
return unpushedHashes.has(commitHash)
|
||||
}
|
||||
|
||||
private async getUnpushedCommitHashes(repoPath: string, env: Record<string, string>): Promise<Set<string>> {
|
||||
try {
|
||||
const output = await executeCommand(
|
||||
|
||||
@@ -31,6 +31,7 @@ export interface FileDiffResponse {
|
||||
additions: number
|
||||
deletions: number
|
||||
isBinary: boolean
|
||||
truncated?: boolean
|
||||
}
|
||||
|
||||
export interface GitDiffOptions {
|
||||
@@ -48,3 +49,15 @@ export interface GitBranch {
|
||||
behind?: number
|
||||
isWorktree?: boolean
|
||||
}
|
||||
|
||||
export interface CommitFile {
|
||||
path: string
|
||||
status: GitFileStatusType
|
||||
oldPath?: string
|
||||
additions: number
|
||||
deletions: number
|
||||
}
|
||||
|
||||
export interface CommitDetails extends GitCommit {
|
||||
files: CommitFile[]
|
||||
}
|
||||
@@ -299,4 +299,121 @@ describe('Repo Git Routes', () => {
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:id/git/discard', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue(null)
|
||||
const response = await app.request('/999/git/discard', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths: ['file1.ts'] }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should return 400 when paths is not an array', async () => {
|
||||
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1 } as any)
|
||||
const response = await app.request('/1/git/discard', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths: 'not-an-array' }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'paths is required and must be an array')
|
||||
})
|
||||
|
||||
it('should return 400 when paths is missing', async () => {
|
||||
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1 } as any)
|
||||
const response = await app.request('/1/git/discard', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'paths is required and must be an array')
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails', async () => {
|
||||
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1, fullPath: '/path/to/repo' } as any)
|
||||
const response = await app.request('/1/git/discard', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths: ['file1.ts'], staged: false }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /:id/git/commit/:hash', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue(null)
|
||||
const response = await app.request('/999/git/commit/abc123')
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
const body = await response.json()
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should return 400 when hash is missing', async () => {
|
||||
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1 } as any)
|
||||
const response = await app.request('/1/git/commit/')
|
||||
|
||||
expect(response.status).toBeGreaterThanOrEqual(400)
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails', async () => {
|
||||
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1, fullPath: '/path/to/repo' } as any)
|
||||
const response = await app.request('/1/git/commit/abc123')
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
const body = await response.json()
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /:id/git/commit/:hash/diff', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue(null)
|
||||
const response = await app.request('/999/git/commit/abc123/diff?path=file.ts')
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
const body = await response.json()
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should return 400 when hash is missing', async () => {
|
||||
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1 } as any)
|
||||
const response = await app.request('/1/git/commit//diff?path=file.ts')
|
||||
|
||||
expect(response.status).toBeGreaterThanOrEqual(400)
|
||||
})
|
||||
|
||||
it('should return 400 when path query parameter is missing', async () => {
|
||||
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1 } as any)
|
||||
const response = await app.request('/1/git/commit/abc123/diff')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'path query parameter is required')
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails', async () => {
|
||||
;(db.getRepoById as MockedFunction<typeof db.getRepoById>).mockReturnValue({ id: 1, fullPath: '/path/to/repo' } as any)
|
||||
const response = await app.request('/1/git/commit/abc123/diff?path=file.ts')
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
const body = await response.json()
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -29,6 +29,7 @@ vi.mock('../../../src/utils/git-auth', () => ({
|
||||
resolveGitIdentity: vi.fn().mockResolvedValue(null),
|
||||
createGitIdentityEnv: vi.fn().mockReturnValue({}),
|
||||
createSilentGitEnv: vi.fn(),
|
||||
filterGitCredentials: vi.fn().mockReturnValue([]),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/utils/git-errors', () => ({
|
||||
@@ -775,4 +776,624 @@ describe('GitService', () => {
|
||||
expect(result).toBe("Switched to branch 'main'")
|
||||
})
|
||||
})
|
||||
|
||||
describe('discardChanges', () => {
|
||||
it('discards staged changes using restore --staged --worktree', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('Changes discarded')
|
||||
|
||||
const result = await service.discardChanges(1, ['file.ts', 'dir/file2.ts'], true, database)
|
||||
|
||||
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', mockRepo.fullPath, 'restore', '--staged', '--worktree', '--source', 'HEAD', '--', 'file.ts', 'dir/file2.ts'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toBe('Changes discarded')
|
||||
})
|
||||
|
||||
it('discards unstaged tracked changes using checkout', 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\n')
|
||||
}
|
||||
if (args.includes('checkout')) {
|
||||
return Promise.resolve('Updated 1 path')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.discardChanges(1, ['file.ts'], false, database)
|
||||
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', mockRepo.fullPath, 'status', '--porcelain', '-u', '--', 'file.ts'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', mockRepo.fullPath, 'checkout', '--', 'file.ts'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toBe('Updated 1 path')
|
||||
})
|
||||
|
||||
it('removes unstaged untracked files using git clean', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) {
|
||||
return Promise.resolve('?? untracked.ts\n')
|
||||
}
|
||||
if (args.includes('clean')) {
|
||||
return Promise.resolve('Removed untracked.ts')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.discardChanges(1, ['untracked.ts'], false, database)
|
||||
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', mockRepo.fullPath, 'clean', '-fd', '--', 'untracked.ts'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toContain('Removed untracked.ts')
|
||||
})
|
||||
|
||||
it('handles mixed tracked and untracked files', 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 modified.ts\n?? untracked.ts\n')
|
||||
}
|
||||
if (args.includes('checkout')) {
|
||||
return Promise.resolve('Updated 1 path')
|
||||
}
|
||||
if (args.includes('clean')) {
|
||||
return Promise.resolve('Removed untracked.ts')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.discardChanges(1, ['modified.ts', 'untracked.ts'], false, database)
|
||||
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', mockRepo.fullPath, 'checkout', '--', 'modified.ts'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', mockRepo.fullPath, 'clean', '-fd', '--', 'untracked.ts'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toContain('Updated 1 path')
|
||||
expect(result).toContain('Removed untracked.ts')
|
||||
})
|
||||
|
||||
it('returns early when no paths provided', async () => {
|
||||
const result = await service.discardChanges(1, [], false, database)
|
||||
|
||||
expect(executeCommandMock).not.toHaveBeenCalled()
|
||||
expect(result).toBe('')
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.discardChanges(1, ['file.ts'], false, database)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('logs and throws error on git command failure', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
const error = new Error('Permission denied')
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) {
|
||||
return Promise.resolve('M file.ts\n')
|
||||
}
|
||||
if (args.includes('checkout')) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
await expect(service.discardChanges(1, ['file.ts'], false, database)).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('handles directories in untracked clean operation', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) {
|
||||
return Promise.resolve('?? dir/\n')
|
||||
}
|
||||
if (args.includes('clean')) {
|
||||
return Promise.resolve('Removing dir/')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.discardChanges(1, ['dir/'], false, database)
|
||||
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', mockRepo.fullPath, 'clean', '-fd', '--', 'dir/'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toContain('Removing dir/')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getCommitDetails', () => {
|
||||
it('returns full commit details with files', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('log') && !args.includes('--not')) {
|
||||
return Promise.resolve('abc123\x00John Doe\x00john@example.com\x001609459200\x00Initial commit')
|
||||
}
|
||||
if (args.includes('show') && args.includes('--name-status')) {
|
||||
return Promise.resolve('A\tfile1.ts\nM\tfile2.ts\nD\tfile3.ts\n')
|
||||
}
|
||||
if (args.includes('show') && args.includes('--numstat')) {
|
||||
return Promise.resolve('10\t5\tfile1.ts\n20\t15\tfile2.ts\n0\t30\tfile3.ts\n')
|
||||
}
|
||||
if (args.includes('--not') && args.includes('--remotes')) {
|
||||
return Promise.resolve('')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getCommitDetails(1, 'abc123', database)
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.hash).toBe('abc123')
|
||||
expect(result?.authorName).toBe('John Doe')
|
||||
expect(result?.authorEmail).toBe('john@example.com')
|
||||
expect(result?.date).toBe('1609459200')
|
||||
expect(result?.message).toBe('Initial commit')
|
||||
expect(result?.files).toHaveLength(3)
|
||||
expect(result?.files[0]).toEqual({
|
||||
path: 'file1.ts',
|
||||
status: 'added',
|
||||
additions: 10,
|
||||
deletions: 5
|
||||
})
|
||||
expect(result?.files[1]).toEqual({
|
||||
path: 'file2.ts',
|
||||
status: 'modified',
|
||||
additions: 20,
|
||||
deletions: 15
|
||||
})
|
||||
expect(result?.files[2]).toEqual({
|
||||
path: 'file3.ts',
|
||||
status: 'deleted',
|
||||
oldPath: undefined,
|
||||
additions: 0,
|
||||
deletions: 30
|
||||
})
|
||||
})
|
||||
|
||||
it('handles renamed files in commit details', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('log') && !args.includes('--not')) {
|
||||
return Promise.resolve('abc123\x00John Doe\x00john@example.com\x001609459200\x00Rename file')
|
||||
}
|
||||
if (args.includes('show') && args.includes('--name-status')) {
|
||||
return Promise.resolve('R\told.ts\tnew.ts\n')
|
||||
}
|
||||
if (args.includes('show') && args.includes('--numstat')) {
|
||||
return Promise.resolve('0\t0\tnew.ts\n')
|
||||
}
|
||||
if (args.includes('--not') && args.includes('--remotes')) {
|
||||
return Promise.resolve('')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getCommitDetails(1, 'abc123', database)
|
||||
|
||||
expect(result?.files).toHaveLength(1)
|
||||
expect(result?.files[0]).toEqual({
|
||||
path: 'new.ts',
|
||||
status: 'renamed',
|
||||
oldPath: 'old.ts',
|
||||
additions: 0,
|
||||
deletions: 0
|
||||
})
|
||||
})
|
||||
|
||||
it('handles copied files in commit details', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('log') && !args.includes('--not')) {
|
||||
return Promise.resolve('abc123\x00John Doe\x00john@example.com\x001609459200\x00Copy file')
|
||||
}
|
||||
if (args.includes('show') && args.includes('--name-status')) {
|
||||
return Promise.resolve('C\toriginal.ts\tcopy.ts\n')
|
||||
}
|
||||
if (args.includes('show') && args.includes('--numstat')) {
|
||||
return Promise.resolve('0\t0\tcopy.ts\n')
|
||||
}
|
||||
if (args.includes('--not') && args.includes('--remotes')) {
|
||||
return Promise.resolve('')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getCommitDetails(1, 'abc123', database)
|
||||
|
||||
expect(result?.files).toHaveLength(1)
|
||||
expect(result?.files[0]).toEqual({
|
||||
path: 'copy.ts',
|
||||
status: 'copied',
|
||||
oldPath: 'original.ts',
|
||||
additions: 0,
|
||||
deletions: 0
|
||||
})
|
||||
})
|
||||
|
||||
it('returns empty files array for empty commit', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('log') && !args.includes('--not')) {
|
||||
return Promise.resolve('abc123\x00John Doe\x00john@example.com\x001609459200\x00Empty commit')
|
||||
}
|
||||
if (args.includes('show') && args.includes('--name-status')) {
|
||||
return Promise.resolve('')
|
||||
}
|
||||
if (args.includes('show') && args.includes('--numstat')) {
|
||||
return Promise.resolve('')
|
||||
}
|
||||
if (args.includes('--not') && args.includes('--remotes')) {
|
||||
return Promise.resolve('')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getCommitDetails(1, 'abc123', database)
|
||||
|
||||
expect(result?.files).toHaveLength(0)
|
||||
})
|
||||
|
||||
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.getCommitDetails(1, 'nonexistent', database)
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.getCommitDetails(1, 'abc123', database)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('marks unpushed commits correctly', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('log') && !args.includes('--not')) {
|
||||
return Promise.resolve('abc123\x00John Doe\x00john@example.com\x001609459200\x00Local commit')
|
||||
}
|
||||
if (args.includes('show') && args.includes('--name-status')) {
|
||||
return Promise.resolve('M\tfile.ts\n')
|
||||
}
|
||||
if (args.includes('show') && args.includes('--numstat')) {
|
||||
return Promise.resolve('1\t1\tfile.ts\n')
|
||||
}
|
||||
if (args.includes('--not') && args.includes('--remotes')) {
|
||||
return Promise.resolve('abc123\n')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getCommitDetails(1, 'abc123', database)
|
||||
|
||||
expect(result?.unpushed).toBe(true)
|
||||
})
|
||||
|
||||
it('handles commit message with pipes correctly', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('log') && !args.includes('--not')) {
|
||||
return Promise.resolve('abc123\x00John Doe\x00john@example.com\x001609459200\x00Fix: merge|conflict|handling')
|
||||
}
|
||||
if (args.includes('show') && args.includes('--name-status')) {
|
||||
return Promise.resolve('')
|
||||
}
|
||||
if (args.includes('show') && args.includes('--numstat')) {
|
||||
return Promise.resolve('')
|
||||
}
|
||||
if (args.includes('--not') && args.includes('--remotes')) {
|
||||
return Promise.resolve('')
|
||||
}
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getCommitDetails(1, 'abc123', database)
|
||||
|
||||
expect(result?.message).toBe('Fix: merge|conflict|handling')
|
||||
})
|
||||
|
||||
it('throws error on git command failure', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
const error = new Error('Git error')
|
||||
executeCommandMock.mockRejectedValue(error)
|
||||
|
||||
await expect(service.getCommitDetails(1, 'abc123', database)).rejects.toThrow('Failed to get commit details')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getCommitDiff', () => {
|
||||
it('returns diff for specific file in commit', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
const diffOutput = `diff --git a/file.ts b/file.ts
|
||||
index abc123..def456 100644
|
||||
--- a/file.ts
|
||||
+++ b/file.ts
|
||||
@@ -1,3 +1,4 @@
|
||||
+new line
|
||||
existing line 1
|
||||
existing line 2
|
||||
existing line 3`
|
||||
executeCommandMock.mockResolvedValue(diffOutput)
|
||||
|
||||
const result = await service.getCommitDiff(1, 'abc123', 'file.ts', database)
|
||||
|
||||
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', expect.stringContaining('/path/to/repo'), 'show', '--format=', 'abc123', '--', 'file.ts'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result.path).toBe('file.ts')
|
||||
expect(result.status).toBe('modified')
|
||||
expect(result.diff).toContain('new line')
|
||||
expect(result.additions).toBe(1)
|
||||
expect(result.deletions).toBe(0)
|
||||
expect(result.isBinary).toBe(false)
|
||||
})
|
||||
|
||||
it('detects binary files', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('Binary files a/image.png and b/image.png differ')
|
||||
|
||||
const result = await service.getCommitDiff(1, 'abc123', 'image.png', database)
|
||||
|
||||
expect(result.isBinary).toBe(true)
|
||||
expect(result.diff).toContain('Binary files')
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.getCommitDiff(1, 'abc123', 'file.ts', database)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('handles deleted files in commit', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
const diffOutput = `diff --git a/deleted.ts b/deleted.ts
|
||||
deleted file mode 100644
|
||||
index abc123..0000000
|
||||
--- a/deleted.ts
|
||||
+++ /dev/null
|
||||
@@ -1,3 +0,0 @@
|
||||
-line 1
|
||||
-line 2
|
||||
-line 3`
|
||||
executeCommandMock.mockResolvedValue(diffOutput)
|
||||
|
||||
const result = await service.getCommitDiff(1, 'abc123', 'deleted.ts', database)
|
||||
|
||||
expect(result.deletions).toBe(3)
|
||||
expect(result.additions).toBe(0)
|
||||
})
|
||||
|
||||
it('throws error on git command failure', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
const error = new Error('Fatal error')
|
||||
executeCommandMock.mockRejectedValue(error)
|
||||
|
||||
await expect(service.getCommitDiff(1, 'abc123', 'file.ts', database)).rejects.toThrow('Failed to get commit diff')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseDiffOutput', () => {
|
||||
it('parses small diff and counts additions/deletions', () => {
|
||||
const diffOutput = `diff --git a/file.ts b/file.ts
|
||||
index abc123..def456 100644
|
||||
--- a/file.ts
|
||||
+++ b/file.ts
|
||||
@@ -1,3 +1,4 @@
|
||||
+added line
|
||||
existing line 1
|
||||
existing line 2
|
||||
-removed line
|
||||
existing line 3`
|
||||
|
||||
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'file.ts')
|
||||
|
||||
expect(result).toEqual({
|
||||
path: 'file.ts',
|
||||
status: 'modified',
|
||||
diff: diffOutput,
|
||||
additions: 1,
|
||||
deletions: 1,
|
||||
isBinary: false,
|
||||
truncated: false
|
||||
})
|
||||
})
|
||||
|
||||
it('detects binary files correctly', () => {
|
||||
const diffOutput = 'GIT binary patch\nliteral 1234\nzcmeAS@N?(olHy`uVBq!ia0vp0{ow;2j9U=!1jd#uLplI'
|
||||
|
||||
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'binary.bin')
|
||||
|
||||
expect(result.isBinary).toBe(true)
|
||||
})
|
||||
|
||||
it('detects "Binary files" indicator', () => {
|
||||
const diffOutput = 'Binary files a/image.png and b/image.png differ'
|
||||
|
||||
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'image.png')
|
||||
|
||||
expect(result.isBinary).toBe(true)
|
||||
})
|
||||
|
||||
it('truncates diff when exceeding MAX_DIFF_SIZE (500KB)', () => {
|
||||
const largeContent = '+' + 'x'.repeat(500 * 1024 + 1000)
|
||||
const diffOutput = `diff --git a/large.ts b/large.ts\n${largeContent}`
|
||||
|
||||
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'large.ts')
|
||||
|
||||
expect(result.truncated).toBe(true)
|
||||
expect(result.diff.length).toBe(500 * 1024 + '\n\n... (diff truncated due to size)'.length)
|
||||
expect(result.diff).toContain('... (diff truncated due to size)')
|
||||
})
|
||||
|
||||
it('does not truncate diff under MAX_DIFF_SIZE', () => {
|
||||
const diffOutput = '+' + 'x'.repeat(100 * 1024)
|
||||
|
||||
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'file.ts')
|
||||
|
||||
expect(result.truncated).toBe(false)
|
||||
expect(result.diff.length).toBeLessThan(500 * 1024)
|
||||
})
|
||||
|
||||
it('handles empty diff', () => {
|
||||
const diffOutput = ''
|
||||
|
||||
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'file.ts')
|
||||
|
||||
expect(result).toEqual({
|
||||
path: 'file.ts',
|
||||
status: 'modified',
|
||||
diff: '',
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
isBinary: false,
|
||||
truncated: false
|
||||
})
|
||||
})
|
||||
|
||||
it('correctly counts multiple additions and deletions', () => {
|
||||
const diffOutput = `diff --git a/file.ts b/file.ts
|
||||
@@ -1,5 +1,7 @@
|
||||
+added 1
|
||||
context
|
||||
+added 2
|
||||
-removed 1
|
||||
context
|
||||
+added 3
|
||||
-removed 2
|
||||
-removed 3`
|
||||
|
||||
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'file.ts')
|
||||
|
||||
expect(result.additions).toBe(3)
|
||||
expect(result.deletions).toBe(3)
|
||||
})
|
||||
|
||||
it('ignores diff headers (+++/---) when counting', () => {
|
||||
const diffOutput = `diff --git a/file.ts b/file.ts
|
||||
--- a/file.ts
|
||||
+++ b/file.ts
|
||||
@@ -1,1 +1,2 @@
|
||||
+added`
|
||||
|
||||
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'file.ts')
|
||||
|
||||
expect(result.additions).toBe(1)
|
||||
expect(result.deletions).toBe(0)
|
||||
})
|
||||
|
||||
it('handles different status types in parseDiffOutput', () => {
|
||||
const diffOutput = '+new line'
|
||||
|
||||
const resultAdded = (service as any).parseDiffOutput(diffOutput, 'added', 'new.ts')
|
||||
const resultDeleted = (service as any).parseDiffOutput(diffOutput, 'deleted', 'old.ts')
|
||||
const resultRenamed = (service as any).parseDiffOutput(diffOutput, 'renamed', 'moved.ts')
|
||||
|
||||
expect(resultAdded.status).toBe('added')
|
||||
expect(resultDeleted.status).toBe('deleted')
|
||||
expect(resultRenamed.status).toBe('renamed')
|
||||
})
|
||||
|
||||
it('handles diff with large change counts at truncation', () => {
|
||||
const addedLines = '+' + 'x'.repeat(501 * 1024)
|
||||
const diffOutput = `diff --git a/file.ts b/file.ts\n${addedLines}`
|
||||
|
||||
const result = (service as any).parseDiffOutput(diffOutput, 'modified', 'file.ts')
|
||||
|
||||
expect(result.truncated).toBe(true)
|
||||
expect(result.diff).toContain('... (diff truncated due to size)')
|
||||
})
|
||||
})
|
||||
})
|
||||
+35
-1
@@ -1,7 +1,7 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { fetchWrapper, FetchError } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type { GitStatusResponse, FileDiffResponse, GitCommit } from '@/types/git'
|
||||
import type { GitStatusResponse, FileDiffResponse, GitCommit, CommitDetails } from '@/types/git'
|
||||
|
||||
export async function fetchGitStatus(repoId: number): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/status`)
|
||||
@@ -22,6 +22,12 @@ export async function fetchFileDiff(repoId: number, path: string, includeStaged?
|
||||
})
|
||||
}
|
||||
|
||||
export async function fetchCommitFileDiff(repoId: number, commitHash: string, path: string): Promise<FileDiffResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit/${commitHash}/diff`, {
|
||||
params: { path },
|
||||
})
|
||||
}
|
||||
|
||||
export async function fetchGitDiff(repoId: number, path: string): Promise<{ diff: string }> {
|
||||
const data = await fetchWrapper<string>(`${API_BASE_URL}/api/repos/${repoId}/git/diff`, {
|
||||
params: { path },
|
||||
@@ -35,6 +41,10 @@ export async function fetchGitLog(repoId: number, limit?: number): Promise<{ com
|
||||
})
|
||||
}
|
||||
|
||||
export async function fetchCommitDetails(repoId: number, hash: string): Promise<CommitDetails> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit/${hash}`)
|
||||
}
|
||||
|
||||
export async function gitFetch(repoId: number): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/fetch`, {
|
||||
method: 'POST',
|
||||
@@ -79,6 +89,14 @@ export async function gitUnstageFiles(repoId: number, paths: string[]): Promise<
|
||||
})
|
||||
}
|
||||
|
||||
export async function gitDiscardFiles(repoId: number, paths: string[], staged: boolean): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/discard`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths, staged }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function gitReset(repoId: number, commitHash: string): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/reset`, {
|
||||
method: 'POST',
|
||||
@@ -104,6 +122,14 @@ export function useFileDiff(repoId: number | undefined, path: string | undefined
|
||||
})
|
||||
}
|
||||
|
||||
export function useCommitFileDiff(repoId: number | undefined, commitHash: string | undefined, path: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['commitFileDiff', repoId, commitHash, path],
|
||||
queryFn: () => (repoId && commitHash && path) ? fetchCommitFileDiff(repoId, commitHash, path) : Promise.reject(new Error('Missing params')),
|
||||
enabled: !!repoId && !!commitHash && !!path,
|
||||
})
|
||||
}
|
||||
|
||||
export function useGitLog(repoId: number | undefined, limit?: number) {
|
||||
return useQuery({
|
||||
queryKey: ['gitLog', repoId, limit],
|
||||
@@ -112,6 +138,14 @@ export function useGitLog(repoId: number | undefined, limit?: number) {
|
||||
})
|
||||
}
|
||||
|
||||
export function useCommitDetails(repoId: number | undefined, hash: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['commitDetails', repoId, hash],
|
||||
queryFn: () => (repoId && hash) ? fetchCommitDetails(repoId, hash) : Promise.reject(new Error('Missing params')),
|
||||
enabled: !!repoId && !!hash,
|
||||
})
|
||||
}
|
||||
|
||||
function parseGitErrorMessage(message: string): string {
|
||||
if (message.includes('no upstream') || message.includes('does not have any commits yet')) {
|
||||
return 'No upstream branch configured. Push with --set-upstream or create commits first.'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useFileDiff } from "@/api/git";
|
||||
import { useFileDiff, useCommitFileDiff } from "@/api/git";
|
||||
import {
|
||||
Loader2,
|
||||
FileText,
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Minus,
|
||||
ArrowLeft,
|
||||
ExternalLink,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CopyButton } from "@/components/ui/copy-button";
|
||||
@@ -21,7 +22,9 @@ interface FileDiffViewProps {
|
||||
repoId: number;
|
||||
filePath: string;
|
||||
includeStaged?: boolean;
|
||||
commitHash?: string;
|
||||
onBack?: () => void;
|
||||
onClose?: () => void;
|
||||
onOpenFile?: (path: string, lineNumber?: number) => void;
|
||||
isMobile?: boolean;
|
||||
}
|
||||
@@ -136,7 +139,7 @@ function DiffLineComponent({
|
||||
}) {
|
||||
if (line.type === "header") {
|
||||
return (
|
||||
<div className="px-4 py-1 bg-muted/50 text-muted-foreground text-xs font-mono truncate border-b border-border/30">
|
||||
<div className="px-4 py-1 bg-muted/50 text-muted-foreground text-xs font-mono break-all border-b border-border/30">
|
||||
{line.content}
|
||||
</div>
|
||||
);
|
||||
@@ -144,7 +147,7 @@ function DiffLineComponent({
|
||||
|
||||
if (line.type === "hunk") {
|
||||
return (
|
||||
<div className="px-4 py-1 bg-accent/20 text-accent-foreground text-xs font-mono border-b border-border/20">
|
||||
<div className="px-4 py-1 bg-accent/20 text-accent-foreground text-xs font-mono break-all border-b border-border/20">
|
||||
{line.content}
|
||||
</div>
|
||||
);
|
||||
@@ -170,7 +173,7 @@ function DiffLineComponent({
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex font-mono text-sm border-l-2 transition-colors",
|
||||
"flex font-mono text-sm border-l-2 transition-colors min-w-0",
|
||||
bgClass,
|
||||
line.type === "add" && "border-l-emerald-500",
|
||||
line.type === "remove" && "border-l-rose-500",
|
||||
@@ -201,7 +204,7 @@ function DiffLineComponent({
|
||||
</div>
|
||||
<pre
|
||||
className={cn(
|
||||
"flex-1 px-2 py-0.5 whitespace-pre-wrap break-words",
|
||||
"flex-1 min-w-0 px-2 py-0.5 whitespace-pre-wrap break-words overflow-hidden",
|
||||
textClass,
|
||||
)}
|
||||
>
|
||||
@@ -215,11 +218,15 @@ export function FileDiffView({
|
||||
repoId,
|
||||
filePath,
|
||||
includeStaged,
|
||||
commitHash,
|
||||
onBack,
|
||||
onClose,
|
||||
onOpenFile,
|
||||
isMobile = false,
|
||||
}: FileDiffViewProps) {
|
||||
const { data: diffData, isLoading, error } = useFileDiff(repoId, filePath, includeStaged);
|
||||
const workingDiff = useFileDiff(repoId, filePath, includeStaged);
|
||||
const commitDiff = useCommitFileDiff(repoId, commitHash, filePath);
|
||||
const { data: diffData, isLoading, error } = commitHash ? commitDiff : workingDiff;
|
||||
|
||||
const fileName = filePath.split("/").pop() || filePath;
|
||||
const dirPath = filePath.includes("/")
|
||||
@@ -259,7 +266,7 @@ export function FileDiffView({
|
||||
const diffLines = diffData.diff ? parseDiff(diffData.diff) : [];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full bg-background">
|
||||
<div className="flex flex-col h-full bg-background overflow-hidden">
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-2 px-3 py-2 border-b border-border flex-shrink-0",
|
||||
@@ -331,10 +338,20 @@ export function FileDiffView({
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
)}
|
||||
{onClose && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 flex-shrink-0"
|
||||
onClick={onClose}
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto min-h-0">
|
||||
<div className="flex-1 overflow-y-auto overflow-x-hidden min-h-0">
|
||||
{diffData.isBinary ? (
|
||||
<div className="flex items-center justify-center h-full text-muted-foreground bg-muted/20">
|
||||
<p className="text-sm">Binary file - cannot display diff</p>
|
||||
|
||||
@@ -4,23 +4,28 @@ import { useGit } from '@/hooks/useGit'
|
||||
import { GitFlatFileList } from './GitFlatFileList'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { FileDiffView } from '@/components/file-browser/FileDiffView'
|
||||
import { DiscardDialog } from '@/components/ui/discard-dialog'
|
||||
import { Loader2, GitCommit, FileText, AlertCircle } from 'lucide-react'
|
||||
|
||||
interface ChangesTabProps {
|
||||
repoId: number
|
||||
onFileSelect: (path: string, staged: boolean) => void
|
||||
onClearFileSelection?: () => void
|
||||
selectedFile?: {path: string, staged: boolean}
|
||||
isMobile: boolean
|
||||
onError?: (error: unknown) => void
|
||||
}
|
||||
|
||||
export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile, onError }: ChangesTabProps) {
|
||||
export function ChangesTab({ repoId, onFileSelect, onClearFileSelection, selectedFile, isMobile, onError }: ChangesTabProps) {
|
||||
const { data: status, isLoading, error } = useGitStatus(repoId)
|
||||
const git = useGit(repoId, onError)
|
||||
const [commitMessage, setCommitMessage] = useState('')
|
||||
|
||||
const [discardDialogOpen, setDiscardDialogOpen] = useState(false)
|
||||
const [discardPaths, setDiscardPaths] = useState<string[]>([])
|
||||
const [discardStaged, setDiscardStaged] = useState(false)
|
||||
|
||||
const stagedFiles = status?.files.filter(f => f.staged) || []
|
||||
const unstagedFiles = status?.files.filter(f => !f.staged) || []
|
||||
const canCommit = commitMessage.trim() && stagedFiles.length > 0 && !git.commit.isPending
|
||||
@@ -33,6 +38,23 @@ export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile, onErr
|
||||
git.unstageFiles.mutate(paths)
|
||||
}
|
||||
|
||||
const handleDiscard = (paths: string[], staged: boolean) => {
|
||||
setDiscardPaths(paths)
|
||||
setDiscardStaged(staged)
|
||||
setDiscardDialogOpen(true)
|
||||
}
|
||||
|
||||
const confirmDiscard = () => {
|
||||
git.discardFiles.mutate({ paths: discardPaths, staged: discardStaged })
|
||||
setDiscardDialogOpen(false)
|
||||
setDiscardPaths([])
|
||||
}
|
||||
|
||||
const cancelDiscard = () => {
|
||||
setDiscardDialogOpen(false)
|
||||
setDiscardPaths([])
|
||||
}
|
||||
|
||||
const handleCommit = () => {
|
||||
git.commit.mutate({ message: commitMessage.trim() })
|
||||
setCommitMessage('')
|
||||
@@ -60,83 +82,13 @@ export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile, onErr
|
||||
|
||||
if (isMobile && selectedFile) {
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<Tabs defaultValue="files" className="flex flex-col h-full">
|
||||
<TabsList className="flex-shrink-0">
|
||||
<TabsTrigger value="files">Files ({stagedFiles.length + unstagedFiles.length})</TabsTrigger>
|
||||
<TabsTrigger value="diff">{selectedFile.path.split('/').pop() || selectedFile.path}</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="files" className="flex-1 overflow-hidden mt-0">
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex-1 overflow-y-auto p-3 space-y-4">
|
||||
{status.hasChanges ? (
|
||||
<>
|
||||
{stagedFiles.length > 0 && (
|
||||
<GitFlatFileList
|
||||
files={stagedFiles}
|
||||
staged={true}
|
||||
onSelect={onFileSelect}
|
||||
onUnstage={handleUnstage}
|
||||
selectedFile={selectedFile?.path}
|
||||
/>
|
||||
)}
|
||||
|
||||
{unstagedFiles.length > 0 && (
|
||||
<GitFlatFileList
|
||||
files={unstagedFiles}
|
||||
staged={false}
|
||||
onSelect={onFileSelect}
|
||||
onStage={handleStage}
|
||||
selectedFile={selectedFile?.path}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<FileText className="w-8 h-8 mx-auto mb-2 opacity-50" />
|
||||
<p className="text-sm">No uncommitted changes</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{status.hasChanges && (
|
||||
<div className="p-3 border-t border-border space-y-2 flex-shrink-0">
|
||||
<Textarea
|
||||
placeholder="Commit message..."
|
||||
value={commitMessage}
|
||||
onChange={(e) => setCommitMessage(e.target.value)}
|
||||
className="min-h-[80px] md:text-sm resize-none"
|
||||
onKeyDown={(e) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && canCommit) {
|
||||
handleCommit()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleCommit}
|
||||
disabled={!canCommit}
|
||||
className="w-full h-9"
|
||||
>
|
||||
{git.commit.isPending ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin mr-2" />
|
||||
) : (
|
||||
<GitCommit className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
Commit {stagedFiles.length > 0 && `(${stagedFiles.length} staged)`}
|
||||
</Button>
|
||||
<p className="text-[10px] text-muted-foreground text-center">
|
||||
{navigator.platform.includes('Mac') ? '⌘' : 'Ctrl'}+Enter to commit
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="diff" className="flex-1 overflow-hidden mt-0">
|
||||
<FileDiffView repoId={repoId} filePath={selectedFile.path} includeStaged={selectedFile.staged} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<div className="flex flex-col h-full min-h-0 overflow-hidden">
|
||||
<FileDiffView
|
||||
repoId={repoId}
|
||||
filePath={selectedFile.path}
|
||||
includeStaged={selectedFile.staged}
|
||||
onBack={onClearFileSelection}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
} else {
|
||||
@@ -151,6 +103,7 @@ export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile, onErr
|
||||
staged={true}
|
||||
onSelect={onFileSelect}
|
||||
onUnstage={handleUnstage}
|
||||
onDiscard={handleDiscard}
|
||||
selectedFile={selectedFile?.path}
|
||||
/>
|
||||
)}
|
||||
@@ -161,6 +114,7 @@ export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile, onErr
|
||||
staged={false}
|
||||
onSelect={onFileSelect}
|
||||
onStage={handleStage}
|
||||
onDiscard={handleDiscard}
|
||||
selectedFile={selectedFile?.path}
|
||||
/>
|
||||
)}
|
||||
@@ -203,6 +157,15 @@ export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile, onErr
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DiscardDialog
|
||||
open={discardDialogOpen}
|
||||
onOpenChange={setDiscardDialogOpen}
|
||||
onConfirm={confirmDiscard}
|
||||
onCancel={cancelDiscard}
|
||||
fileCount={discardPaths.length}
|
||||
isDiscarding={git.discardFiles.isPending}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useCommitDetails } from '@/api/git'
|
||||
import { Loader2, GitCommit, ArrowLeft } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { GitFlatFileList } from './GitFlatFileList'
|
||||
import { FileDiffView } from '@/components/file-browser/FileDiffView'
|
||||
|
||||
interface CommitDetailViewProps {
|
||||
repoId: number
|
||||
commitHash: string
|
||||
onBack: () => void
|
||||
onFileSelect: (path: string) => void
|
||||
selectedFile?: string
|
||||
}
|
||||
|
||||
export function CommitDetailView({ repoId, commitHash, onBack, onFileSelect, selectedFile }: CommitDetailViewProps) {
|
||||
const { data: commit, isLoading, error } = useCommitDetails(repoId, commitHash)
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full py-12">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error || !commit) {
|
||||
return (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<GitCommit className="w-8 h-8 mx-auto mb-2 opacity-50" />
|
||||
<p className="text-sm">Failed to load commit details</p>
|
||||
<p className="text-xs mt-1">{error?.message}</p>
|
||||
<Button variant="outline" size="sm" onClick={onBack} className="mt-4">
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to commits
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const commitFiles = commit.files.map(f => ({
|
||||
path: f.path,
|
||||
status: f.status,
|
||||
staged: false,
|
||||
oldPath: f.oldPath,
|
||||
additions: f.additions,
|
||||
deletions: f.deletions
|
||||
}))
|
||||
|
||||
const totalAdditions = commit.files.reduce((sum, f) => sum + (f.additions || 0), 0)
|
||||
const totalDeletions = commit.files.reduce((sum, f) => sum + (f.deletions || 0), 0)
|
||||
|
||||
if (selectedFile) {
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0 overflow-hidden">
|
||||
<FileDiffView
|
||||
repoId={repoId}
|
||||
filePath={selectedFile}
|
||||
includeStaged={false}
|
||||
commitHash={commitHash}
|
||||
onBack={() => onFileSelect('')}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="px-3 py-3 border-b border-border flex-shrink-0 space-y-2">
|
||||
<div className="flex items-start gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onBack}
|
||||
className="h-7 w-7 p-0 flex-shrink-0 mt-0.5"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
</Button>
|
||||
<p className="text-sm font-medium leading-snug">{commit.message}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground pl-9">
|
||||
<span className="font-mono">{commit.hash.substring(0, 7)}</span>
|
||||
<span>·</span>
|
||||
<span className="truncate">{commit.authorName}</span>
|
||||
<span>·</span>
|
||||
<span className="flex-shrink-0">{new Date(parseInt(commit.date, 10) * 1000).toLocaleDateString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto px-1 pt-1">
|
||||
<GitFlatFileList
|
||||
files={commitFiles}
|
||||
staged={false}
|
||||
onSelect={(path) => onFileSelect(path)}
|
||||
selectedFile={selectedFile}
|
||||
readOnly={true}
|
||||
totalAdditions={totalAdditions}
|
||||
totalDeletions={totalDeletions}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -59,34 +59,41 @@ export function CommitsTab({ repoId, onSelectCommit }: CommitsTabProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full overflow-y-auto">
|
||||
{data.commits.map((commit) => (
|
||||
<button
|
||||
key={commit.hash}
|
||||
className="flex items-start gap-3 px-3 py-2 text-left hover:bg-accent/50 transition-colors border-b border-border last:border-0"
|
||||
onClick={() => onSelectCommit?.(commit.hash)}
|
||||
>
|
||||
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-accent flex items-center justify-center mt-0.5">
|
||||
<GitCommit className="w-4 h-4 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{commit.message}</p>
|
||||
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
|
||||
<span className="font-mono">{commit.hash.substring(0, 7)}</span>
|
||||
<span>·</span>
|
||||
<span className="truncate">{commit.authorName}</span>
|
||||
<span>·</span>
|
||||
<span className="flex-shrink-0">{formatRelativeTime(commit.date)}</span>
|
||||
{commit.unpushed && (
|
||||
<span className={cn('flex items-center gap-0.5 px-1 rounded', GIT_UI_COLORS.unpushed)}>
|
||||
<ArrowUp className="w-3 h-3" />
|
||||
Local
|
||||
</span>
|
||||
)}
|
||||
<div className="flex flex-col h-full overflow-x-hidden">
|
||||
<div className="flex-1 overflow-y-auto overflow-x-hidden">
|
||||
{data.commits.map((commit) => (
|
||||
<button
|
||||
key={commit.hash}
|
||||
className="flex items-start gap-3 px-3 py-2 text-left hover:bg-accent/50 transition-colors border-b border-border last:border-0"
|
||||
onClick={() => onSelectCommit?.(commit.hash)}
|
||||
>
|
||||
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-accent flex items-center justify-center mt-0.5">
|
||||
<GitCommit className="w-4 h-4 text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium line-clamp-2">{commit.message}</p>
|
||||
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground overflow-hidden">
|
||||
<span className="font-mono">{commit.hash.substring(0, 7)}</span>
|
||||
<span>·</span>
|
||||
<span className="truncate">{commit.authorName}</span>
|
||||
<span>·</span>
|
||||
<span className="flex-shrink-0">{formatRelativeTime(commit.date)}</span>
|
||||
{commit.unpushed && (
|
||||
<span className={cn('flex items-center gap-0.5 px-1 rounded', GIT_UI_COLORS.unpushed)}>
|
||||
<ArrowUp className="w-3 h-3" />
|
||||
Local
|
||||
</span>
|
||||
)}
|
||||
{!commit.unpushed && (
|
||||
<span className={cn('flex items-center gap-0.5 px-1 rounded', GIT_UI_COLORS.pushed)}>
|
||||
Remote
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Plus, Minus, FileText, FilePlus, FileX, FileSearch, CircleDot } from 'lucide-react'
|
||||
import { Plus, Minus, FileText, FilePlus, FileX, FileSearch, CircleDot, RotateCcw } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { GitFileStatus } from '@/types/git'
|
||||
import { GIT_STATUS_COLORS, GIT_UI_COLORS } from '@/lib/git-status-styles'
|
||||
@@ -10,6 +10,7 @@ interface GitFlatFileItemProps {
|
||||
onSelect: (path: string, staged: boolean) => void
|
||||
onStage?: (path: string) => void
|
||||
onUnstage?: (path: string) => void
|
||||
onDiscard?: (path: string, staged: boolean) => void
|
||||
}
|
||||
|
||||
const statusIcons = {
|
||||
@@ -21,7 +22,7 @@ const statusIcons = {
|
||||
copied: FilePlus,
|
||||
}
|
||||
|
||||
export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage }: GitFlatFileItemProps) {
|
||||
export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage, onDiscard }: GitFlatFileItemProps) {
|
||||
const StatusIcon = statusIcons[file.status] || FileText
|
||||
const statusColor = GIT_STATUS_COLORS[file.status] || 'text-muted-foreground'
|
||||
|
||||
@@ -37,6 +38,13 @@ export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage
|
||||
}
|
||||
}
|
||||
|
||||
const handleDiscard = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (onDiscard) {
|
||||
onDiscard(file.path, file.staged)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -59,18 +67,41 @@ export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage
|
||||
staged
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
|
||||
onClick={handleAction}
|
||||
>
|
||||
{file.staged ? (
|
||||
<Minus className={cn('w-3 h-3', GIT_UI_COLORS.unstage)} />
|
||||
) : (
|
||||
<Plus className={cn('w-3 h-3', GIT_UI_COLORS.stage)} />
|
||||
)}
|
||||
</Button>
|
||||
{(file.additions !== undefined || file.deletions !== undefined) && (
|
||||
<div className="flex items-center gap-1 text-xs flex-shrink-0">
|
||||
{file.additions !== undefined && file.additions > 0 && (
|
||||
<span className="text-green-500">+{file.additions}</span>
|
||||
)}
|
||||
{file.deletions !== undefined && file.deletions > 0 && (
|
||||
<span className="text-red-500">-{file.deletions}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{(onStage || onUnstage) && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
|
||||
onClick={handleAction}
|
||||
>
|
||||
{file.staged ? (
|
||||
<Minus className={cn('w-3 h-3', GIT_UI_COLORS.unstage)} />
|
||||
) : (
|
||||
<Plus className={cn('w-3 h-3', GIT_UI_COLORS.stage)} />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{onDiscard && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
|
||||
onClick={handleDiscard}
|
||||
title="Discard changes"
|
||||
>
|
||||
<RotateCcw className="w-3 h-3 text-rose-500" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -12,7 +12,11 @@ interface GitFlatFileListProps {
|
||||
onSelect: (path: string, staged: boolean) => void
|
||||
onStage?: (paths: string[]) => void
|
||||
onUnstage?: (paths: string[]) => void
|
||||
onDiscard?: (paths: string[], staged: boolean) => void
|
||||
selectedFile?: string
|
||||
readOnly?: boolean
|
||||
totalAdditions?: number
|
||||
totalDeletions?: number
|
||||
}
|
||||
|
||||
interface GroupedFiles {
|
||||
@@ -28,7 +32,11 @@ export function GitFlatFileList({
|
||||
onSelect,
|
||||
onStage,
|
||||
onUnstage,
|
||||
onDiscard,
|
||||
selectedFile,
|
||||
readOnly = false,
|
||||
totalAdditions,
|
||||
totalDeletions,
|
||||
}: GitFlatFileListProps) {
|
||||
const [collapsedGroups, setCollapsedGroups] = useState<Set<GitFileStatusType>>(new Set())
|
||||
|
||||
@@ -83,6 +91,13 @@ export function GitFlatFileList({
|
||||
}
|
||||
}
|
||||
|
||||
const handleDiscardAll = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (onDiscard) {
|
||||
onDiscard(filteredFiles.map(f => f.path), staged)
|
||||
}
|
||||
}
|
||||
|
||||
if (filteredFiles.length === 0) {
|
||||
return null
|
||||
}
|
||||
@@ -93,24 +108,44 @@ export function GitFlatFileList({
|
||||
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
|
||||
{staged ? 'Staged Changes' : 'Changes'} ({filteredFiles.length})
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-2 text-xs"
|
||||
onClick={staged ? handleUnstageAll : handleStageAll}
|
||||
>
|
||||
{staged ? (
|
||||
<>
|
||||
<Minus className="w-3 h-3 mr-1" />
|
||||
Unstage All
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Plus className="w-3 h-3 mr-1" />
|
||||
Stage All
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{(totalAdditions !== undefined && totalAdditions > 0 || totalDeletions !== undefined && totalDeletions > 0) && (
|
||||
<div className="flex items-center gap-1 text-xs">
|
||||
{totalAdditions !== undefined && totalAdditions > 0 && <span className="text-green-500">+{totalAdditions}</span>}
|
||||
{totalDeletions !== undefined && totalDeletions > 0 && <span className="text-red-500">-{totalDeletions}</span>}
|
||||
</div>
|
||||
)}
|
||||
{!readOnly && (
|
||||
<div className="flex items-center gap-1">
|
||||
{onDiscard && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-2 text-xs text-rose-500 hover:text-rose-600"
|
||||
onClick={handleDiscardAll}
|
||||
>
|
||||
Discard All
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-2 text-xs"
|
||||
onClick={staged ? handleUnstageAll : handleStageAll}
|
||||
>
|
||||
{staged ? (
|
||||
<>
|
||||
<Minus className="w-3 h-3 mr-1" />
|
||||
Unstage All
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Plus className="w-3 h-3 mr-1" />
|
||||
Stage All
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{groupedFiles.map(({ status, files: groupFiles }) => {
|
||||
@@ -143,8 +178,9 @@ export function GitFlatFileList({
|
||||
file={file}
|
||||
isSelected={selectedFile === file.path}
|
||||
onSelect={onSelect}
|
||||
onStage={handleStageFile}
|
||||
onUnstage={handleUnstageFile}
|
||||
onStage={readOnly ? undefined : handleStageFile}
|
||||
onUnstage={readOnly ? undefined : handleUnstageFile}
|
||||
onDiscard={readOnly ? undefined : onDiscard ? ((path: string, staged: boolean) => onDiscard([path], staged)) : undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useGit } from '@/hooks/useGit'
|
||||
import { ChangesTab } from './ChangesTab'
|
||||
import { CommitsTab } from './CommitsTab'
|
||||
import { BranchesTab } from './BranchesTab'
|
||||
import { CommitDetailView } from './CommitDetailView'
|
||||
import { GitErrorBanner } from './GitErrorBanner'
|
||||
import { FileDiffView } from '@/components/file-browser/FileDiffView'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -37,6 +38,7 @@ interface SourceControlPanelProps {
|
||||
}
|
||||
|
||||
type Tab = 'changes' | 'commits' | 'branches'
|
||||
type View = 'default' | 'commit-detail'
|
||||
|
||||
export function SourceControlPanel({
|
||||
repoId,
|
||||
@@ -49,6 +51,9 @@ export function SourceControlPanel({
|
||||
}: SourceControlPanelProps) {
|
||||
const [activeTab, setActiveTab] = useState<Tab>('changes')
|
||||
const [selectedFile, setSelectedFile] = useState<{path: string, staged: boolean} | undefined>()
|
||||
const [currentView, setCurrentView] = useState<View>('default')
|
||||
const [selectedCommit, setSelectedCommit] = useState<string | undefined>()
|
||||
const [selectedCommitFile, setSelectedCommitFile] = useState<string | undefined>()
|
||||
const [gitError, setGitError] = useState<{ summary: string; detail?: string } | null>(null)
|
||||
const { data: status } = useGitStatus(repoId)
|
||||
const isMobile = useMobile()
|
||||
@@ -72,6 +77,18 @@ export function SourceControlPanel({
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectCommit = (hash: string) => {
|
||||
setSelectedCommit(hash)
|
||||
setCurrentView('commit-detail')
|
||||
}
|
||||
|
||||
const handleBackToCommits = () => {
|
||||
setSelectedCommit(undefined)
|
||||
setSelectedCommitFile(undefined)
|
||||
setCurrentView('default')
|
||||
setActiveTab('commits')
|
||||
}
|
||||
|
||||
const tabs: { id: Tab; label: string; icon: React.ElementType }[] = [
|
||||
{ id: 'changes', label: 'Changes', icon: FileCode },
|
||||
{ id: 'commits', label: 'Commits', icon: History },
|
||||
@@ -82,7 +99,7 @@ export function SourceControlPanel({
|
||||
const stagedCount = status?.files.filter(f => f.staged).length || 0
|
||||
|
||||
const content = (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex flex-col h-full gap-0">
|
||||
<div className="flex items-center justify-between px-3 py-2 border-b border-border flex-shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -154,69 +171,79 @@ export function SourceControlPanel({
|
||||
<GitErrorBanner error={gitError} onDismiss={() => setGitError(null)} />
|
||||
)}
|
||||
|
||||
<div className="flex border-b border-border flex-shrink-0">
|
||||
{tabs.map((tab) => {
|
||||
const Icon = tab.icon
|
||||
return (
|
||||
<button
|
||||
key={tab.id}
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 px-3 py-2 text-sm transition-colors border-b-2 -mb-px',
|
||||
activeTab === tab.id
|
||||
? 'border-primary text-foreground'
|
||||
: 'border-transparent text-muted-foreground hover:text-foreground hover:bg-accent'
|
||||
)}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
>
|
||||
<Icon className="w-4 h-4" />
|
||||
<span>{tab.label}</span>
|
||||
{tab.id === 'changes' && changesCount > 0 && (
|
||||
<span className="text-xs px-1.5 py-0.5 rounded-full bg-accent">
|
||||
{stagedCount > 0 ? `${stagedCount}/${changesCount}` : changesCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{!((currentView === 'commit-detail' && selectedCommitFile) || (isMobile && selectedFile && activeTab === 'changes')) && (
|
||||
<div className="flex border-b border-border flex-shrink-0">
|
||||
{tabs.map((tab) => {
|
||||
const Icon = tab.icon
|
||||
return (
|
||||
<button
|
||||
key={tab.id}
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 px-3 py-2 text-sm transition-colors border-b-2 -mb-px',
|
||||
activeTab === tab.id
|
||||
? 'border-primary text-foreground'
|
||||
: 'border-transparent text-muted-foreground hover:text-foreground hover:bg-accent'
|
||||
)}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
>
|
||||
<Icon className="w-4 h-4" />
|
||||
<span>{tab.label}</span>
|
||||
{tab.id === 'changes' && changesCount > 0 && (
|
||||
<span className="text-xs px-1.5 py-0.5 rounded-full bg-accent">
|
||||
{stagedCount > 0 ? `${stagedCount}/${changesCount}` : changesCount}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={cn('flex-1 min-h-0', isMobile ? 'flex flex-col' : 'flex')}>
|
||||
<div className={cn('flex-1 min-h-0', isMobile ? 'flex flex-col gap-0' : 'flex')}>
|
||||
<div className={cn(
|
||||
'overflow-hidden',
|
||||
isMobile ? 'flex-1' : selectedFile ? 'w-[35%] border-r border-border' : 'flex-1'
|
||||
'overflow-hidden min-h-0 h-full flex flex-col',
|
||||
isMobile
|
||||
? 'flex-1'
|
||||
: currentView === 'commit-detail'
|
||||
? 'flex-1'
|
||||
: selectedFile
|
||||
? 'w-[35%] border-r border-border'
|
||||
: 'flex-1'
|
||||
)}>
|
||||
{activeTab === 'changes' && (
|
||||
<ChangesTab
|
||||
repoId={repoId}
|
||||
onFileSelect={(path, staged) => setSelectedFile({ path, staged })}
|
||||
onClearFileSelection={() => setSelectedFile(undefined)}
|
||||
selectedFile={selectedFile}
|
||||
isMobile={isMobile}
|
||||
onError={handleGitError}
|
||||
/>
|
||||
)}
|
||||
{activeTab === 'commits' && (
|
||||
<CommitsTab repoId={repoId} />
|
||||
{activeTab === 'commits' && currentView === 'default' && (
|
||||
<CommitsTab repoId={repoId} onSelectCommit={handleSelectCommit} />
|
||||
)}
|
||||
{activeTab === 'branches' && (
|
||||
{activeTab === 'branches' && currentView === 'default' && (
|
||||
<BranchesTab repoId={repoId} currentBranch={currentBranch} repoUrl={repoUrl} isRepoWorktree={isRepoWorktree} />
|
||||
)}
|
||||
|
||||
{currentView === 'commit-detail' && selectedCommit && (
|
||||
<div className="flex flex-1 min-h-0 overflow-hidden flex-col">
|
||||
<CommitDetailView
|
||||
repoId={repoId}
|
||||
commitHash={selectedCommit}
|
||||
onBack={handleBackToCommits}
|
||||
onFileSelect={setSelectedCommitFile}
|
||||
selectedFile={selectedCommitFile}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{selectedFile && !isMobile && (
|
||||
{selectedFile && !isMobile && currentView === 'default' && (
|
||||
<div className="flex-1 overflow-hidden flex flex-col">
|
||||
<div className="flex items-center justify-between px-3 py-2 border-b border-border">
|
||||
<span className="text-sm font-medium truncate">{selectedFile.path}</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0"
|
||||
onClick={() => setSelectedFile(undefined)}
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-auto">
|
||||
<FileDiffView repoId={repoId} filePath={selectedFile.path} includeStaged={selectedFile.staged} />
|
||||
<FileDiffView repoId={repoId} filePath={selectedFile.path} includeStaged={selectedFile.staged} onClose={() => setSelectedFile(undefined)} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -230,12 +257,12 @@ export function SourceControlPanel({
|
||||
mobileFullscreen
|
||||
hideCloseButton={isMobile}
|
||||
className={cn(
|
||||
'p-0 flex flex-col bg-card border-border',
|
||||
isMobile ? 'h-full' : 'w-[90vw] sm:max-w-6xl h-[90vh]'
|
||||
'p-0 flex flex-col bg-card border-border gap-0',
|
||||
isMobile ? 'h-full' : 'w-[90vw] sm:max-w-6xl h-[90vh] sm:pb-0'
|
||||
)}
|
||||
>
|
||||
<DialogHeader className={cn(
|
||||
'px-4 py-3 border-b border-border flex-shrink-0',
|
||||
'px-4 py-2 border-b border-border flex-shrink-0',
|
||||
isMobile && 'relative'
|
||||
)}>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
@@ -253,7 +280,7 @@ export function SourceControlPanel({
|
||||
</Button>
|
||||
)}
|
||||
</DialogHeader>
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<div className="flex-1 overflow-hidden pb-0">
|
||||
{content}
|
||||
</div>
|
||||
</DialogContent>
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
|
||||
interface DiscardDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
fileCount: number
|
||||
isDiscarding?: boolean
|
||||
}
|
||||
|
||||
export function DiscardDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
fileCount,
|
||||
isDiscarding = false
|
||||
}: DiscardDialogProps) {
|
||||
const itemText = fileCount === 1 ? '1 file' : `${fileCount} files`
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className='max-w-[90%] sm:max-w-sm'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Discard Changes</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to discard changes to {itemText}? This action cannot be undone.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Alert className="overflow-hidden">
|
||||
<AlertTriangle className="h-4 w-4 flex-shrink-0" />
|
||||
<AlertDescription>
|
||||
This will permanently delete your uncommitted changes to {itemText}. If these changes exist in the staging area, they will also be removed.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<DialogFooter className='gap-2'>
|
||||
<Button variant="outline" onClick={onCancel} disabled={isDiscarding}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={onConfirm}
|
||||
disabled={isDiscarding}
|
||||
className="bg-red-600 hover:bg-red-700 text-white font-semibold border-red-600"
|
||||
>
|
||||
{isDiscarding && 'Discarding...'}
|
||||
{!isDiscarding && 'Discard'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { gitFetch, gitPull, gitPush, gitCommit, gitStageFiles, gitUnstageFiles, fetchGitLog, fetchGitDiff, gitReset, getApiErrorMessage } from '@/api/git'
|
||||
import { gitFetch, gitPull, gitPush, gitCommit, gitStageFiles, gitUnstageFiles, gitDiscardFiles, fetchGitLog, fetchGitDiff, gitReset, getApiErrorMessage } from '@/api/git'
|
||||
import { createBranch, switchBranch } from '@/api/repos'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
@@ -94,6 +94,17 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
onError: handleError,
|
||||
})
|
||||
|
||||
const discardFilesMutation = useMutation({
|
||||
mutationFn: ({ paths, staged }: { paths: string[]; staged: boolean }) => {
|
||||
if (!repoId) throw new Error('No repo ID')
|
||||
return gitDiscardFiles(repoId, paths, staged)
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateCache()
|
||||
},
|
||||
onError: handleError,
|
||||
})
|
||||
|
||||
const log = useMutation({
|
||||
mutationFn: ({ limit }: { limit?: number }) => {
|
||||
if (!repoId) throw new Error('No repo ID')
|
||||
@@ -153,6 +164,7 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
commit,
|
||||
stageFiles: stageFilesMutation,
|
||||
unstageFiles: unstageFilesMutation,
|
||||
discardFiles: discardFilesMutation,
|
||||
log,
|
||||
diff,
|
||||
createBranch: createBranchMutation,
|
||||
|
||||
@@ -15,7 +15,8 @@ export const GIT_UI_COLORS = {
|
||||
stage: 'text-emerald-600 dark:text-emerald-400',
|
||||
unstage: 'text-rose-600 dark:text-rose-400',
|
||||
stagedBadge: 'bg-emerald-500/10 text-emerald-600 dark:bg-emerald-500/20 dark:text-emerald-400',
|
||||
unpushed: 'bg-amber-500/10 text-amber-600 dark:bg-amber-500/20 dark:text-amber-400',
|
||||
unpushed: 'bg-blue-500/10 text-blue-600 dark:bg-blue-500/20 dark:text-blue-400',
|
||||
pushed: 'bg-purple-500/10 text-purple-600 dark:bg-purple-500/20 dark:text-purple-400',
|
||||
} as const
|
||||
|
||||
export const GIT_STATUS_LABELS = {
|
||||
|
||||
@@ -5,6 +5,8 @@ export interface GitFileStatus {
|
||||
status: GitFileStatusType
|
||||
staged: boolean
|
||||
oldPath?: string
|
||||
additions?: number
|
||||
deletions?: number
|
||||
}
|
||||
|
||||
export interface GitCommit {
|
||||
@@ -16,6 +18,18 @@ export interface GitCommit {
|
||||
unpushed?: boolean
|
||||
}
|
||||
|
||||
export interface CommitFile {
|
||||
path: string
|
||||
status: GitFileStatusType
|
||||
oldPath?: string
|
||||
additions: number
|
||||
deletions: number
|
||||
}
|
||||
|
||||
export interface CommitDetails extends GitCommit {
|
||||
files: CommitFile[]
|
||||
}
|
||||
|
||||
export interface GitStatusResponse {
|
||||
branch: string
|
||||
ahead: number
|
||||
|
||||
Reference in new issue
Block a user