Git Source Control Integration (#74)

* feat(source-control): add commits and file management components

- Introduced `CommitsTab` for displaying commit history with relative time formatting.
- Added `GitFlatFileItem` and `GitFlatFileList` for managing file statuses in the source control panel.
- Implemented `SourceControlPanel` to encapsulate source control functionalities including changes, commits, and branches.
- Enhanced `useGit` hook to manage git operations such as fetch, pull, push, commit, stage, and unstage files with appropriate error handling and toast notifications.
- Updated `RepoDetail` to integrate the new source control panel and provide a user interface for source control actions.
- Defined `GitCommit` type for better type safety in commit-related operations.

* refactor: streamline error handling in Git operations and update error imports

* feat: enhance Git services and ESLint configuration for improved functionality

* refactor: update method signatures for consistency and clarity in Git services

* feat: refactor git services and improve error handling

- Remove unused imports and clean up code in repos.ts and git-operations.ts.
- Simplify error handling in repo.ts by enforcing message property in ErrorWithMessage interface.
- Update GitPushService to remove unnecessary database parameter in methods.
- Enhance executeCommand function to better handle command execution results.
- Update tests to use mocked functions for better isolation and clarity.
- Add specific ESLint rules for test files to accommodate common testing patterns.
- Introduce tsconfig.test.json for better TypeScript configuration in tests.
- Update vitest.config.ts to use the new test TypeScript configuration.

* refactor: remove esbuild configuration from Vitest setup

* feat: enhance Source Control Panel with branch management and integrate into RepoDetail and SessionDetail pages

* feat: implement Git authentication service and refactor related services

- Add GitAuthService to handle Git environment setup with credentials.
- Refactor GitBranchService, GitCommitService, GitFetchPullService, GitPushService, GitStatusService, and GitLogService to utilize the new GitAuthService.
- Remove GitCommandUtils and related error handling for Git operations.
- Delete git-operations.ts and associated tests as functionality is now integrated into other services.
- Update TypeScript configuration to enable composite projects for better build management.

* feat: refactor Git services to improve structure and update imports

* refactor: simplify error utility functions and update test cases for Git services

* feat: refactor GitAuthService and update related tests for improved credential handling

* feat: implement GitDiffService and related endpoints for file diff functionality

* feat: add emitDeclarationOnly option to TypeScript configuration files

* feat: enhance GitLogService to fetch remote branches and improve error handling in repo commands

* feat: update Git command execution to remove fallback and enhance environment variable handling

* feat: add repository authentication tracking

- Add `requires_auth` column to repos table
- Implement auth check in GitAuthService
- Update cloneRepo to detect public/private repos
- Add test coverage for auth-related functionality
- Improve UI styling for auth-related indicators

* feat(git): implement interactive Git authentication with askpass

- Add GitAskpassService to handle credential requests from Git
- Implement askpass script that communicates with backend
- Update GitAuthService to use askpass instead of direct credential
  injection
- Add new endpoint for branch listing and status
- Improve branch name handling in GitBranchService
- Enhance error handling in GitDiffService for untracked files
- Add upstream branch checking and setup in GitFetchPullService
- Update UI components for better visual consistency
- Fix various minor UI styling issues

* feat(git): enhance Git authentication with improved askpass support

- Update askpass endpoint to handle hostname parameter and return full
  credential object
- Replace `createNoPromptGitEnv` with `createSilentGitEnv` for better
  VSCode compatibility
- Add compiled Node.js askpass script for broader compatibility
- Enhance GitBranchService to return detailed branch information with
  upstream tracking
- Improve branch listing UI with better sorting and display
- Update GitAuthService to use askpass for all operations with proper
  credential handling
- Fix various UI styling issues in diff view and source control panel
- Update test mocks to use new silent environment function
- Add proper error handling and credential caching in GitAskpassService

* feat(git-auth): implement IPC-based Git authentication system

- Add new IPC server infrastructure for handling Git credential requests
- Implement AskpassHandler to manage Git authentication through IPC
- Replace previous HTTP-based askpass system with local IPC
  communication
- Remove deprecated GitAskpassService and related HTTP endpoints
- Update GitAuthService to use IPC-based authentication flow
- Add new shell scripts for Git askpass integration (askpass.sh,
  askpass-main.js)
- Remove database column 'requires_auth' as it's no longer needed
- Update all Git service classes to use new authentication approach
- Improve error handling and credential caching
- Add proper cleanup for IPC server on shutdown

* fix(frontend): correct GitBranch type usage in BranchesTab and BranchSwitcher

* fix(ipc): handle empty responses and add logging for askpass handler

- Handle empty response bodies in askpass-main.ts to prevent JSON parse errors
- Add logging to IPC server for debugging request/response issues
- Add logging to AskpassHandler for credential lookup visibility

* fix(ipc): return empty credentials for silent fetches instead of failing

Silent fetch operations (used when fetching commit history on repo open)
should return empty credentials gracefully rather than failing, allowing
git to proceed without credentials for public repos or cached credentials.

* chore(ipc): add detailed logging for debugging askpass requests

- Log handler registration and lookup paths
- Log incoming request details
- Log handler response results

* chore(askpass): add comprehensive debugging to trace IPC communication

- Add detailed stderr logging to askpass-main.ts for all steps
- Log environment variables and paths at initialization
- Log IPC connection attempts and responses
- Log JSON parsing results

This will help trace where the IPC communication fails.

* chore(debug): add comprehensive logging to trace git environment and IPC requests

- Log GIT_ASKPASS, VSCODE_GIT_IPC_HANDLE, GIT_TERMINAL_PROMPT env vars when executing git
- Log all incoming IPC requests with URL and body
- Log handler registration status

* Integrate GitAuthService throughout repo operations

- Add GitAuthService parameter to all repo service functions
- Replace direct git env creation with GitAuthService.getGitEnvironment()
- Update route handlers to pass GitAuthService to service calls
- Remove createSilentGitEnv utility in favor of centralized auth
- Ensure consistent git authentication across all operations

* refactor: consolidate git services and remove duplicate fetch service

- Remove GitFetchService and consolidate into GitFetchPullService
- Clean up duplicate git authentication logic across services
- Simplify repo service by removing redundant environment handling
- Update tests to reflect consolidated service structure
- Remove unused imports and streamline API endpoints
- Reduce codebase complexity by eliminating service duplication

* refactor: clean up unnecessary config changes and improve git API types

* feat(git): add GitCommit interface and fix push mutation

* feat(git): fix source control panel issues

- Fix unstaged file diff showing all changes instead of working directory only
- Remove auto-refresh (10s) to reduce git command spam
- Add reset/revert mutation for unpushed local commits
- Fix branch creation/switching to update database
- Add unpushed commit detection and visual indicator in commits tab
- Handle no-upstream branch status gracefully

* fix(git): improve branch listing and remove regex parsing issue

- Fix branch name parsing to use full name instead of regex capturing only first word
- Add refresh button for branches
- Show remote branches with Globe icon and make them non-clickable
- Add 'local' label for branches without upstream tracking
- Handle remotes/ prefix properly in branch detection

* fix(git): remove duplicate refresh button

* fix(git): properly extract branch name from git output

- Extract branch name before whitespace/bracket in git branch -vv -a output
- When clicking remote branch, checkout local tracking branch instead of remote reference

* fix(git): remove duplicate refresh button from branches tab

* fix: improve source control panel mobile layout

- Set full height on mobile for better screen utilization
- Add larger centered close button on mobile
- Hide default close button when custom one is shown on mobile

* Remove git credential test feature

The test credential button in settings was broken because it tried to test
authentication against just the host URL (e.g., https://github.com/) instead
of a repository path. Since git credentials are already handled correctly
through the askpass mechanism when cloning repositories, the test button
was redundant and has been removed.

Changes:
- Remove /test-credential endpoint from settings routes
- Remove testGitCredential API from frontend
- Remove TestCredentialRequest/Response types
- Remove test button and related state from GitSettings component

* fix: resolve Copilot review issues

- Remove duplicate GitCommit interface definition
- Fix CSS typos: bg-linear-to-br -> bg-gradient-to-br
- Fix typo: /sessflex-shrink-0 -> flex-shrink-0
- Add *.test.js to .gitignore and remove compiled test files
- Fix missing closing brace in useGit.test.tsx
- Remove unused maskToken function

* fix(git): correct ahead/behind count order and add renamed file path parsing

- Fix git rev-list output parsing: ahead comes first, behind second
- Add oldPath extraction for renamed (R) and copied (C) files in status
- Refactor git service tests to use consistent mocking patterns
- Add missing Database and SettingsService mocks to prevent test failures

---------

Co-authored-by: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
This commit is contained in:
theepicsaxguyandChris Scott authored and GitHub committed 2026-01-19 22:03:42 -05:00
1 parent 524ce018dc
commit e91c54ba20
64 files changed
+6214 -1915

No files matched your search

-9
View File
@@ -340,15 +340,6 @@ export async function getFileRange(userPath: string, startLine: number, endLine:
}
}
export async function getFileTotalLines(userPath: string): Promise<number> {
const validatedPath = validatePath(userPath)
const exists = await fileExists(validatedPath)
if (!exists) {
throw { message: 'File does not exist', statusCode: 404 }
}
return countFileLines(validatedPath)
}
export async function applyFilePatches(userPath: string, patches: PatchOperation[]): Promise<{ success: boolean; totalLines: number }> {
const validatedPath = validatePath(userPath)
logger.info(`Applying ${patches.length} patches to: ${userPath}`)
+29
View File
@@ -0,0 +1,29 @@
import type { IPCServer } from '../ipc/ipcServer'
import type { Database } from 'bun:sqlite'
import { AskpassHandler } from '../ipc/askpassHandler'
export class GitAuthService {
private askpassHandler: AskpassHandler | null = null
initialize(ipcServer: IPCServer | undefined, database: Database): void {
this.askpassHandler = new AskpassHandler(ipcServer, database)
}
getGitEnvironment(silent: boolean = false): Record<string, string> {
const env: Record<string, string> = {
GIT_TERMINAL_PROMPT: '0',
LANG: 'en_US.UTF-8',
LC_ALL: 'en_US.UTF-8',
}
if (silent) {
env.VSCODE_GIT_FETCH_SILENT = 'true'
}
if (this.askpassHandler) {
Object.assign(env, this.askpassHandler.getEnv())
}
return env
}
}
-288
View File
@@ -1,288 +0,0 @@
import { executeCommand } from '../utils/process'
import { logger } from '../utils/logger'
import { getErrorMessage } from '../utils/error-utils'
import { SettingsService } from './settings'
import type { Database } from 'bun:sqlite'
import path from 'path'
import fs from 'fs/promises'
import { createGitEnv, createNoPromptGitEnv } from '../utils/git-auth'
async function hasCommits(repoPath: string): Promise<boolean> {
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', 'HEAD'], { silent: true })
return true
} catch {
return false
}
}
function getGitEnvironment(database: Database): Record<string, string> {
try {
const settingsService = new SettingsService(database)
const settings = settingsService.getSettings('default')
const gitCredentials = settings.preferences.gitCredentials || []
return createGitEnv(gitCredentials)
} catch (error) {
logger.warn('Failed to get git credentials from settings:', error)
return createNoPromptGitEnv()
}
}
export type GitFileStatusType = 'modified' | 'added' | 'deleted' | 'renamed' | 'untracked' | 'copied'
export interface GitFileStatus {
path: string
status: GitFileStatusType
staged: boolean
oldPath?: string
}
export interface GitStatusResponse {
branch: string
ahead: number
behind: number
files: GitFileStatus[]
hasChanges: boolean
}
export interface FileDiffResponse {
path: string
status: GitFileStatusType
diff: string | null
additions: number
deletions: number
isBinary: boolean
}
function parseStatusCode(code: string): GitFileStatusType {
switch (code) {
case 'M': return 'modified'
case 'A': return 'added'
case 'D': return 'deleted'
case 'R': return 'renamed'
case 'C': return 'copied'
case '?': return 'untracked'
default: return 'modified'
}
}
function parsePorcelainV2(output: string): { branch: string; ahead: number; behind: number; files: GitFileStatus[] } {
const lines = output.split('\n').filter(line => line.trim())
let branch = 'HEAD'
let ahead = 0
let behind = 0
const files: GitFileStatus[] = []
for (const line of lines) {
if (line.startsWith('# branch.head ')) {
branch = line.replace('# branch.head ', '')
} else if (line.startsWith('# branch.ab ')) {
const match = line.match(/# branch\.ab \+(\d+) -(\d+)/)
if (match && match[1] && match[2]) {
ahead = parseInt(match[1], 10)
behind = parseInt(match[2], 10)
}
} else if (line.startsWith('1 ') || line.startsWith('2 ')) {
const parts = line.split(' ')
const xy = parts[1]
if (!xy || xy.length < 2) continue
const stagedStatus = xy[0] as string
const unstagedStatus = xy[1] as string
if (line.startsWith('2 ')) {
const pathParts = parts.slice(8).join(' ').split('\t')
const filePath = pathParts[1] || pathParts[0] || ''
const oldPath = pathParts[0] || ''
if (stagedStatus !== '.') {
files.push({
path: filePath,
status: parseStatusCode(stagedStatus),
staged: true,
oldPath: stagedStatus === 'R' || stagedStatus === 'C' ? oldPath : undefined
})
}
if (unstagedStatus !== '.') {
files.push({
path: filePath,
status: parseStatusCode(unstagedStatus),
staged: false
})
}
} else {
const filePath = parts.slice(8).join(' ') || ''
if (stagedStatus !== '.') {
files.push({
path: filePath,
status: parseStatusCode(stagedStatus),
staged: true
})
}
if (unstagedStatus !== '.') {
files.push({
path: filePath,
status: parseStatusCode(unstagedStatus),
staged: false
})
}
}
} else if (line.startsWith('? ')) {
const filePath = line.substring(2)
files.push({
path: filePath,
status: 'untracked',
staged: false
})
}
}
return { branch, ahead, behind, files }
}
async function expandUntrackedDirectory(repoPath: string, dirPath: string): Promise<GitFileStatus[]> {
const cleanDirPath = dirPath.endsWith('/') ? dirPath.slice(0, -1) : dirPath
const fullDirPath = path.join(repoPath, cleanDirPath)
const files: GitFileStatus[] = []
async function walkDir(currentPath: string, relativePath: string): Promise<void> {
try {
const entries = await fs.readdir(currentPath, { withFileTypes: true })
for (const entry of entries) {
const entryRelPath = relativePath ? `${relativePath}/${entry.name}` : entry.name
const entryFullPath = path.join(currentPath, entry.name)
if (entry.isDirectory()) {
await walkDir(entryFullPath, entryRelPath)
} else {
files.push({
path: `${cleanDirPath}/${entryRelPath}`,
status: 'untracked',
staged: false
})
}
}
} catch {
// Ignore errors reading directory
}
}
await walkDir(fullDirPath, '')
return files
}
export async function getGitStatus(repoPath: string, database?: Database): Promise<GitStatusResponse> {
try {
const fullPath = path.resolve(repoPath)
const env = database ? getGitEnvironment(database) : undefined
const output = await executeCommand(['git', '-C', fullPath, 'status', '--porcelain=v2', '--branch'], { env })
const { branch, ahead, behind, files } = parsePorcelainV2(output)
const expandedFiles: GitFileStatus[] = []
for (const file of files) {
if (file.status === 'untracked' && file.path.endsWith('/')) {
const dirFiles = await expandUntrackedDirectory(fullPath, file.path)
if (dirFiles.length > 0) {
expandedFiles.push(...dirFiles)
} else {
expandedFiles.push(file)
}
} else {
expandedFiles.push(file)
}
}
return {
branch,
ahead,
behind,
files: expandedFiles,
hasChanges: expandedFiles.length > 0
}
} catch (error: unknown) {
logger.error(`Failed to get git status for ${repoPath}:`, error)
throw new Error(`Failed to get git status: ${getErrorMessage(error)}`)
}
}
export async function getFileDiff(repoPath: string, filePath: string, database?: Database): Promise<FileDiffResponse> {
try {
const fullRepoPath = path.resolve(repoPath)
const status = await getGitStatus(repoPath, database)
const fileStatus = status.files.find(f => f.path === filePath)
if (!fileStatus) {
return {
path: filePath,
status: 'modified',
diff: null,
additions: 0,
deletions: 0,
isBinary: false
}
}
let diff: string | null = null
let additions = 0
let deletions = 0
let isBinary = false
const env = database ? getGitEnvironment(database) : undefined
if (fileStatus.status === 'untracked') {
try {
const content = await executeCommand(['git', '-C', fullRepoPath, 'diff', '--no-index', '--', '/dev/null', filePath], { env, silent: true })
diff = content
} catch (error: unknown) {
const errorMessage = getErrorMessage(error)
if (errorMessage?.includes('exit code 1') || errorMessage?.includes('Command failed with code 1')) {
const output = errorMessage || ''
const diffMatch = output.match(/diff --git[\s\S]*(?=\n\n No newline|$)/)
diff = diffMatch ? diffMatch[0] : output.substring(output.indexOf('diff --git'))
} else {
diff = `New file: ${filePath}`
}
}
} else {
try {
const repoHasCommits = await hasCommits(fullRepoPath)
if (repoHasCommits) {
diff = await executeCommand(['git', '-C', fullRepoPath, 'diff', 'HEAD', '--', filePath], { env })
} else {
diff = `New file (no commits yet): ${filePath}`
}
} catch (error: unknown) {
logger.warn(`Failed to get diff for ${filePath}:`, getErrorMessage(error))
diff = null
}
}
if (diff) {
if (diff.includes('Binary files') || diff.includes('GIT binary patch')) {
isBinary = true
} else {
const lines = diff.split('\n')
for (const line of lines) {
if (line.startsWith('+') && !line.startsWith('+++')) {
additions++
} else if (line.startsWith('-') && !line.startsWith('---')) {
deletions++
}
}
}
}
return {
path: filePath,
status: fileStatus.status,
diff,
additions,
deletions,
isBinary
}
} catch (error: unknown) {
logger.error(`Failed to get file diff for ${filePath}:`, error)
throw new Error(`Failed to get file diff: ${getErrorMessage(error)}`)
}
}
@@ -0,0 +1,147 @@
import { GitAuthService } from '../git-auth'
import { executeCommand } from '../../utils/process'
import { getRepoById } from '../../db/queries'
import type { Database } from 'bun:sqlite'
import path from 'path'
import { logger } from '../../utils/logger'
interface GitBranch {
name: string
type: 'local' | 'remote'
current: boolean
upstream?: string
ahead?: number
behind?: number
}
export class GitBranchService {
constructor(private gitAuthService: GitAuthService) {}
async getBranches(repoId: number, database: Database): Promise<GitBranch[]> {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found`)
}
const fullPath = path.resolve(repo.fullPath)
const env = this.gitAuthService.getGitEnvironment()
let currentBranch = ''
try {
const currentStdout = await executeCommand(['git', '-C', fullPath, 'rev-parse', '--abbrev-ref', 'HEAD'], { env, silent: true })
currentBranch = currentStdout.trim()
} catch {
}
const stdout = await executeCommand(['git', '-C', fullPath, 'branch', '-vv', '-a'], { env, silent: true })
const lines = stdout.split('\n').filter(line => line.trim())
const branches: GitBranch[] = []
const seenNames = new Set<string>()
for (const line of lines) {
const trimmed = line.trim()
if (!trimmed) continue
const isCurrent = trimmed.startsWith('*')
const namePart = trimmed.replace(/^\*?\s*/, '')
const firstSpace = namePart.indexOf(' ')
const firstBracket = namePart.indexOf('[')
const cutIndex = firstSpace === -1 ? (firstBracket === -1 ? namePart.length : firstBracket) : (firstBracket === -1 ? firstSpace : Math.min(firstSpace, firstBracket))
const branchName = namePart.slice(0, cutIndex)
if (!branchName) continue
const branch: GitBranch = {
name: branchName,
type: branchName.startsWith('remotes/') ? 'remote' : 'local',
current: isCurrent && (branchName === currentBranch || branchName === `remotes/${currentBranch}`)
}
if (seenNames.has(branch.name)) continue
seenNames.add(branch.name)
const upstreamMatch = namePart.match(/\[([^:]+):?\s*(ahead\s+(\d+))?,?\s*(behind\s+(\d+))?\]/)
if (upstreamMatch) {
branch.upstream = upstreamMatch[1]
branch.ahead = upstreamMatch[3] ? parseInt(upstreamMatch[3]) : 0
branch.behind = upstreamMatch[5] ? parseInt(upstreamMatch[5]) : 0
}
if (branch.current && (!branch.ahead || !branch.behind)) {
try {
const status = await this.getBranchStatus(repoId, database)
branch.ahead = status.ahead
branch.behind = status.behind
} catch {
}
}
branches.push(branch)
}
return branches.sort((a, b) => {
if (a.current !== b.current) return b.current ? 1 : -1
if (a.type !== b.type) return a.type === 'local' ? -1 : 1
return a.name.localeCompare(b.name)
})
}
async getBranchStatus(repoId: number, database: Database): Promise<{ ahead: number; behind: number }> {
try {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found`)
}
const fullPath = path.resolve(repo.fullPath)
const env = this.gitAuthService.getGitEnvironment()
const stdout = await executeCommand(['git', '-C', fullPath, 'rev-list', '--left-right', '--count', 'HEAD...@{upstream}'], { env, silent: true })
const [ahead, behind] = stdout.trim().split(/\s+/).map(Number)
return { ahead: ahead || 0, behind: behind || 0 }
} catch (error) {
logger.warn(`Could not get branch status for repo ${repoId}, returning zeros:`, error)
return { ahead: 0, behind: 0 }
}
}
async createBranch(repoId: number, branchName: string, database: Database): Promise<string> {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found`)
}
const fullPath = path.resolve(repo.fullPath)
const env = this.gitAuthService.getGitEnvironment()
const result = await executeCommand(['git', '-C', fullPath, 'checkout', '-b', branchName], { env })
return result
}
async switchBranch(repoId: number, branchName: string, database: Database): Promise<string> {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found`)
}
const fullPath = path.resolve(repo.fullPath)
const env = this.gitAuthService.getGitEnvironment()
const result = await executeCommand(['git', '-C', fullPath, 'checkout', branchName], { env })
return result
}
async hasCommits(repoPath: string): Promise<boolean> {
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', 'HEAD'], { silent: true })
return true
} catch {
return false
}
}
}
@@ -0,0 +1,116 @@
import { GitAuthService } from '../git-auth'
import { logger } from '../../utils/logger'
import * as db from '../../db/queries'
import type { Database } from 'bun:sqlite'
import { executeCommand } from '../../utils/process'
import { SettingsService } from '../settings'
import { resolveGitIdentity, createGitIdentityEnv } from '../../utils/git-auth'
export class GitCommitService {
constructor(private gitAuthService: GitAuthService) {}
async commit(repoId: number, message: string, database: Database, stagedPaths?: string[]): Promise<string> {
try {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found`)
}
const repoPath = repo.fullPath
const authEnv = this.gitAuthService.getGitEnvironment()
// Get identity env
const settingsService = new SettingsService(database)
const settings = settingsService.getSettings('default')
const gitCredentials = settings.preferences.gitCredentials || []
const identity = await resolveGitIdentity(settings.preferences.gitIdentity, gitCredentials)
const identityEnv = identity ? createGitIdentityEnv(identity) : {}
const env = { ...authEnv, ...identityEnv }
const args = ['git', '-C', repoPath, 'commit', '-m', message]
if (stagedPaths && stagedPaths.length > 0) {
args.push('--')
args.push(...stagedPaths)
}
const result = await executeCommand(args, { env })
return result
} catch (error: unknown) {
logger.error(`Failed to commit changes for repo ${repoId}:`, error)
throw error
}
}
async stageFiles(repoId: number, paths: string[], database: Database): Promise<string> {
try {
const repo = db.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 ''
}
const args = ['git', '-C', repoPath, 'add', '--', ...paths]
const result = await executeCommand(args, { env })
return result
} catch (error: unknown) {
logger.error(`Failed to stage files for repo ${repoId}:`, error)
throw error
}
}
async unstageFiles(repoId: number, paths: string[], database: Database): Promise<string> {
try {
const repo = db.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 ''
}
const args = ['git', '-C', repoPath, 'restore', '--staged', '--', ...paths]
const result = await executeCommand(args, { env })
return result
} catch (error: unknown) {
logger.error(`Failed to unstage files for repo ${repoId}:`, error)
throw error
}
}
async resetToCommit(repoId: number, commitHash: string, database: Database): Promise<string> {
try {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found`)
}
const repoPath = repo.fullPath
const env = this.gitAuthService.getGitEnvironment()
const args = ['git', '-C', repoPath, 'reset', '--hard', commitHash]
const result = await executeCommand(args, { env })
return result
} catch (error: unknown) {
logger.error(`Failed to reset to commit ${commitHash} for repo ${repoId}:`, error)
throw error
}
}
}
+145
View File
@@ -0,0 +1,145 @@
import { GitAuthService } from '../git-auth'
import { executeCommand } from '../../utils/process'
import { getRepoById } from '../../db/queries'
import type { Database } from 'bun:sqlite'
import { getReposPath } from '@opencode-manager/shared/config/env'
import path from 'path'
import { logger } from '../../utils/logger'
import type { FileDiffResponse, GitDiffOptions, GitFileStatusType } from '../../types/git'
import type { GitDiffProvider } from './interfaces'
export class GitDiffService implements GitDiffProvider {
constructor(private gitAuthService: GitAuthService) {}
async getFileDiff(repoId: number, filePath: string, database: Database, options?: GitDiffOptions & { includeStaged?: boolean }): Promise<FileDiffResponse> {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found: ${repoId}`)
}
const repoPath = path.resolve(getReposPath(), repo.localPath)
const env = this.gitAuthService.getGitEnvironment()
const includeStaged = options?.includeStaged ?? true
const status = await this.getFileStatus(repoPath, filePath, env)
if (status.status === 'untracked') {
return this.getUntrackedFileDiff(repoPath, filePath, env)
}
return this.getTrackedFileDiff(repoPath, filePath, env, includeStaged, options)
}
private async getFileStatus(repoPath: string, filePath: string, env: Record<string, string>): Promise<{ status: string }> {
try {
const output = await executeCommand([
'git', '-C', repoPath, 'status', '--porcelain', '--', filePath
], { env, silent: true })
if (!output.trim()) {
return { status: 'untracked' }
}
const statusCode = output.trim().split(' ')[0]
return { status: statusCode || 'untracked' }
} catch {
return { status: 'untracked' }
}
}
private async getUntrackedFileDiff(repoPath: string, filePath: string, env: Record<string, string>): Promise<FileDiffResponse> {
const result = await executeCommand([
'git', '-C', repoPath, 'diff', '--no-index', '--', '/dev/null', filePath
], { env, ignoreExitCode: true })
if (typeof result === 'string') {
return this.parseDiffOutput(result, 'untracked', filePath)
}
// Non-zero exit, but still parse stdout
return this.parseDiffOutput((result as { stdout: string }).stdout, 'untracked', filePath)
}
private async getTrackedFileDiff(repoPath: string, filePath: string, env: Record<string, string>, includeStaged: boolean, options?: GitDiffOptions): Promise<FileDiffResponse> {
try {
const hasCommits = await this.hasCommits(repoPath)
const diffArgs = ['git', '-C', repoPath, 'diff']
if (options?.showContext !== undefined) {
diffArgs.push(`-U${options.showContext}`)
}
if (options?.ignoreWhitespace) {
diffArgs.push('--ignore-all-space')
}
if (options?.unified !== undefined) {
diffArgs.push(`--unified=${options.unified}`)
}
if (hasCommits) {
if (includeStaged) {
diffArgs.push('HEAD', '--', filePath)
} else {
diffArgs.push('--', filePath)
}
} else {
return {
path: filePath,
status: 'added',
diff: `New file (no commits yet): ${filePath}`,
additions: 0,
deletions: 0,
isBinary: false
}
}
const diff = await executeCommand(diffArgs, { env })
return this.parseDiffOutput(diff, 'modified', filePath)
} catch (error) {
logger.warn(`Failed to get diff for tracked file ${filePath}:`, error)
throw new Error(`Failed to get file diff: ${error instanceof Error ? error.message : String(error)}`)
}
}
private parseDiffOutput(diff: string, status: string, filePath?: string): FileDiffResponse {
let additions = 0
let deletions = 0
let isBinary = false
if (typeof diff === 'string') {
if (diff.includes('Binary files') || diff.includes('GIT binary patch')) {
isBinary = true
} else {
const lines = diff.split('\n')
for (const line of lines) {
if (line.startsWith('+') && !line.startsWith('+++')) additions++
if (line.startsWith('-') && !line.startsWith('---')) deletions++
}
}
}
return {
path: filePath || '',
status: status as GitFileStatusType,
diff: typeof diff === 'string' ? diff : '',
additions,
deletions,
isBinary
}
}
private async hasCommits(repoPath: string): Promise<boolean> {
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', 'HEAD'], { silent: true })
return true
} catch {
return false
}
}
async getFullDiff(repoId: number, filePath: string, database: Database, options?: GitDiffOptions): Promise<FileDiffResponse> {
return this.getFileDiff(repoId, filePath, database, options)
}
}
@@ -0,0 +1,33 @@
import { GitAuthService } from '../git-auth'
import { executeCommand } from '../../utils/process'
import { getRepoById } from '../../db/queries'
import type { Database } from 'bun:sqlite'
import path from 'path'
export class GitFetchPullService {
constructor(private gitAuthService: GitAuthService) {}
async fetch(repoId: number, database: Database): Promise<string> {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error('Repository not found')
}
const fullPath = path.resolve(repo.fullPath)
const env = this.gitAuthService.getGitEnvironment(true)
return executeCommand(['git', '-C', fullPath, 'fetch', '--all', '--prune'], { env })
}
async pull(repoId: number, database: Database): Promise<string> {
const repo = getRepoById(database, repoId)
if (!repo) {
throw new Error('Repository not found')
}
const fullPath = path.resolve(repo.fullPath)
const env = this.gitAuthService.getGitEnvironment(false)
return executeCommand(['git', '-C', fullPath, 'pull'], { env })
}
}
+143
View File
@@ -0,0 +1,143 @@
import { GitAuthService } from '../git-auth'
import { executeCommand } from '../../utils/process'
import { logger } from '../../utils/logger'
import { getErrorMessage } from '../../utils/error-utils'
import * as db from '../../db/queries'
import { getReposPath } from '@opencode-manager/shared/config/env'
import type { Database } from 'bun:sqlite'
import type { GitCommit, FileDiffResponse } from '../../types/git'
import path from 'path'
import type { GitDiffService } from './GitDiffService'
export class GitLogService {
private gitAuthService: GitAuthService
private gitDiffService: GitDiffService
constructor(gitAuthService: GitAuthService, gitDiffService: GitDiffService) {
this.gitAuthService = gitAuthService
this.gitDiffService = gitDiffService
}
async getLog(repoId: number, database: Database, limit: number = 10): Promise<GitCommit[]> {
try {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found: ${repoId}`)
}
const repoPath = path.resolve(getReposPath(), repo.localPath)
const logArgs = [
'git',
'-C',
repoPath,
'log',
`--all`,
`-n`,
String(limit),
'--format=%H|%an|%ae|%ai|%s'
]
const logEnv = this.gitAuthService.getGitEnvironment(true)
const output = await executeCommand(logArgs, { env: logEnv })
const lines = output.trim().split('\n')
const commits: GitCommit[] = []
for (const line of lines) {
if (!line.trim()) continue
const parts = line.split('|')
const [hash, authorName, authorEmail, date, ...messageParts] = parts
const message = messageParts.join('|')
if (hash) {
commits.push({
hash,
authorName: authorName || '',
authorEmail: authorEmail || '',
date: date || '',
message: message || ''
})
}
}
const unpushedCommits = await this.getUnpushedCommitHashes(repoPath, logEnv)
return commits.map(commit => ({
...commit,
unpushed: unpushedCommits.has(commit.hash)
}))
} catch (error: unknown) {
logger.error(`Failed to get git log for repo ${repoId}:`, error)
throw new Error(`Failed to get git log: ${getErrorMessage(error)}`)
}
}
private async getUnpushedCommitHashes(repoPath: string, env: Record<string, string>): Promise<Set<string>> {
try {
const output = await executeCommand(
['git', '-C', repoPath, 'log', '--not', '--remotes', '--format=%H'],
{ env, silent: true }
)
const hashes = output.trim().split('\n').filter(Boolean)
return new Set(hashes)
} catch {
return new Set()
}
}
async getCommit(repoId: number, hash: string, database: Database): Promise<GitCommit | null> {
try {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found: ${repoId}`)
}
const repoPath = path.resolve(getReposPath(), repo.localPath)
const logArgs = [
'git',
'-C',
repoPath,
'log',
'--format=%H|%an|%ae|%ai|%s',
hash,
'-1'
]
const env = this.gitAuthService.getGitEnvironment(true)
const output = await executeCommand(logArgs, { env })
if (!output.trim()) {
return null
}
const parts = output.trim().split('|')
const [commitHash, authorName, authorEmail, date, ...messageParts] = parts
const message = messageParts.join('|')
if (!commitHash) {
return null
}
return {
hash: commitHash,
authorName: authorName || '',
authorEmail: authorEmail || '',
date: date || '',
message: message || ''
}
} catch (error: unknown) {
logger.error(`Failed to get commit ${hash} for repo ${repoId}:`, error)
throw new Error(`Failed to get commit: ${getErrorMessage(error)}`)
}
}
async getDiff(repoId: number, filePath: string, database: Database): Promise<string> {
const result = await this.gitDiffService.getFileDiff(repoId, filePath, database)
return result.diff
}
async getFullDiff(repoId: number, filePath: string, database: Database, includeStaged?: boolean): Promise<FileDiffResponse> {
return this.gitDiffService.getFileDiff(repoId, filePath, database, { includeStaged })
}
}
@@ -0,0 +1,30 @@
import { executeCommand } from '../../utils/process'
import { GitAuthService } from '../git-auth'
import type { Database } from 'bun:sqlite'
import * as db from '../../db/queries'
import path from 'path'
export class GitPushService {
constructor(private gitAuthService: GitAuthService) {}
async push(
repoId: number,
options: { setUpstream?: boolean },
database: Database
): Promise<string> {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error('Repository not found')
}
const fullPath = path.resolve(repo.fullPath)
const args = ['git', '-C', fullPath, 'push']
if (options.setUpstream) {
args.push('--set-upstream', 'origin', 'HEAD')
}
const env = this.gitAuthService.getGitEnvironment()
return executeCommand(args, { env })
}
}
@@ -0,0 +1,129 @@
import { GitAuthService } from '../git-auth'
import { executeCommand } from '../../utils/process'
import { logger } from '../../utils/logger'
import * as db from '../../db/queries'
import type { Database } from 'bun:sqlite'
import type { GitFileStatus, GitStatusResponse } from '../../types/git'
export class GitStatusService {
constructor(private gitAuthService: GitAuthService) {}
async getStatus(repoId: number, database: Database): Promise<GitStatusResponse> {
try {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repository not found`)
}
const repoPath = repo.fullPath
const env = this.gitAuthService.getGitEnvironment()
const [branch, branchStatus, porcelainOutput] = await Promise.all([
this.getCurrentBranch(repoPath, env),
this.getBranchStatus(repoPath, env),
executeCommand(['git', '-C', repoPath, 'status', '--porcelain'], { env })
])
const files = this.parsePorcelainOutput(porcelainOutput)
const hasChanges = files.length > 0
return {
branch,
ahead: branchStatus.ahead,
behind: branchStatus.behind,
files,
hasChanges
}
} catch (error: unknown) {
logger.error(`Failed to get status for repo ${repoId}:`, error)
throw error
}
}
private async getCurrentBranch(repoPath: string, env: Record<string, string> | undefined): Promise<string> {
try {
const branch = await executeCommand(['git', '-C', repoPath, 'rev-parse', '--abbrev-ref', 'HEAD'], { env, silent: true })
return branch.trim()
} catch {
return ''
}
}
private async getBranchStatus(repoPath: string, env: Record<string, string> | undefined): Promise<{ ahead: number; behind: number }> {
try {
const stdout = await executeCommand(['git', '-C', repoPath, 'rev-list', '--left-right', '--count', 'HEAD...@{upstream}'], { env, silent: true })
const [ahead, behind] = stdout.trim().split(/\s+/).map(Number)
return { ahead: ahead || 0, behind: behind || 0 }
} catch {
return { ahead: 0, behind: 0 }
}
}
private parsePorcelainOutput(output: string): GitFileStatus[] {
const files: GitFileStatus[] = []
const lines = output.trim().split('\n').filter(line => line.trim())
for (const line of lines) {
if (line.length < 3) continue
const stagedStatus = line[0] as string
const unstagedStatus = line[1] as string
let filePath = line.substring(3)
let oldPath: string | undefined
if ((stagedStatus === 'R' || stagedStatus === 'C') && filePath.includes(' -> ')) {
const arrowIndex = filePath.indexOf(' -> ')
oldPath = filePath.substring(0, arrowIndex)
filePath = filePath.substring(arrowIndex + 4)
}
if (stagedStatus !== ' ' && stagedStatus !== '?') {
files.push({
path: filePath,
status: this.parseStatusCode(stagedStatus),
staged: true,
...(oldPath && { oldPath })
})
}
if (unstagedStatus !== ' ' && unstagedStatus !== '?') {
files.push({
path: filePath,
status: this.parseStatusCode(unstagedStatus),
staged: false,
...(oldPath && { oldPath })
})
}
if (stagedStatus === '?' || unstagedStatus === '?') {
files.push({
path: filePath,
status: 'untracked',
staged: false
})
}
}
return files
}
private parseStatusCode(code: string): 'modified' | 'added' | 'deleted' | 'renamed' | 'untracked' | 'copied' {
switch (code) {
case 'M':
return 'modified'
case 'A':
return 'added'
case 'D':
return 'deleted'
case 'R':
return 'renamed'
case 'C':
return 'copied'
case '?':
return 'untracked'
default:
return 'modified'
}
}
}
+11
View File
@@ -0,0 +1,11 @@
import type { Database } from 'bun:sqlite'
import type { FileDiffResponse, GitDiffOptions, GitStatusResponse } from '../../types/git'
export interface GitDiffProvider {
getFileDiff(repoId: number, filePath: string, database: Database, options?: GitDiffOptions): Promise<FileDiffResponse>
getFullDiff(repoId: number, filePath: string, database: Database, options?: GitDiffOptions): Promise<FileDiffResponse>
}
export interface GitStatusProvider {
getStatus(repoId: number, database: Database): Promise<GitStatusResponse>
}
+162 -368
View File
@@ -4,81 +4,45 @@ import * as db from '../db/queries'
import type { Database } from 'bun:sqlite'
import type { Repo, CreateRepoInput } from '../types/repo'
import { logger } from '../utils/logger'
import { SettingsService } from './settings'
import { createGitEnv, createNoPromptGitEnv, createGitHubGitEnv, isGitHubHttpsUrl } from '../utils/git-auth'
import { getReposPath } from '@opencode-manager/shared/config/env'
import type { GitAuthService } from './git-auth'
import path from 'path'
export class GitAuthenticationError extends Error {
constructor(message: string) {
super(message)
this.name = 'GitAuthenticationError'
interface ErrorWithMessage {
message: string
}
function isErrorWithMessage(error: unknown): error is ErrorWithMessage {
return (
typeof error === 'object' &&
error !== null &&
'message' in error &&
typeof (error as ErrorWithMessage).message === 'string'
)
}
function getErrorMessage(error: unknown): string {
if (isErrorWithMessage(error)) {
return error.message
}
}
function isAuthenticationError(error: any): boolean {
const message = error?.message?.toLowerCase() || ''
return message.includes('authentication failed') ||
message.includes('invalid username or token') ||
message.includes('could not read username')
}
interface GitCommandOptions {
cwd?: string
env?: Record<string, string>
silent?: boolean
}
async function executeGitWithFallback(
cmd: string[],
options: GitCommandOptions = {}
): Promise<string> {
const { cwd, env = createNoPromptGitEnv(), silent } = options
try {
return await executeCommand(cmd, { cwd, env, silent })
} catch (error: any) {
if (!isAuthenticationError(error)) {
throw error
}
logger.warn(`Git command failed with auth, trying CLI fallbacks`)
const url = cmd.find(arg => arg.includes('http://') || arg.includes('https://'))
if (!url) {
return await executeCommand(cmd, { cwd, env: createNoPromptGitEnv(), silent })
}
try {
if (isGitHubHttpsUrl(url)) {
logger.warn(`Detected GitHub URL, trying gh auth token`)
const ghToken = (await executeCommand(['gh', 'auth', 'token'])).trim()
const ghEnv = createGitHubGitEnv(ghToken)
return await executeCommand(cmd, { cwd, env: ghEnv, silent })
}
} catch (cliError: any) {
logger.warn(`CLI auth fallback failed:`, cliError.message)
}
logger.warn(`All auth fallbacks failed, trying without auth (public repo)`)
return await executeCommand(cmd, { cwd, env: createNoPromptGitEnv(), silent })
if (error instanceof Error) {
return error.message
}
return String(error)
}
async function hasCommits(repoPath: string): Promise<boolean> {
async function hasCommits(repoPath: string, env: Record<string, string>): Promise<boolean> {
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', 'HEAD'], { silent: true })
await executeCommand(['git', '-C', repoPath, 'rev-parse', 'HEAD'], { env, silent: true })
return true
} catch {
return false
}
}
async function isValidGitRepo(repoPath: string): Promise<boolean> {
async function isValidGitRepo(repoPath: string, env: Record<string, string>): Promise<boolean> {
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--git-dir'], { silent: true })
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--git-dir'], { env, silent: true })
return true
} catch {
return false
@@ -96,36 +60,35 @@ async function checkRepoNameAvailable(name: string): Promise<boolean> {
}
}
async function copyRepoToWorkspace(sourcePath: string, targetName: string): Promise<void> {
async function copyRepoToWorkspace(sourcePath: string, targetName: string, env: Record<string, string>): Promise<void> {
const reposPath = getReposPath()
const targetPath = path.join(reposPath, targetName)
logger.info(`Copying repo from ${sourcePath} to ${targetPath}`)
await executeCommand(['git', 'clone', '--local', sourcePath, targetName], { cwd: reposPath })
await executeCommand(['git', 'clone', '--local', sourcePath, targetName], { cwd: reposPath, env })
logger.info(`Successfully copied repo to ${targetPath}`)
}
async function safeGetCurrentBranch(repoPath: string): Promise<string | null> {
async function safeGetCurrentBranch(repoPath: string, env: Record<string, string>): Promise<string | null> {
try {
const repoHasCommits = await hasCommits(repoPath)
const repoHasCommits = await hasCommits(repoPath, env)
if (!repoHasCommits) {
try {
const symbolicRef = await executeCommand(['git', '-C', repoPath, 'symbolic-ref', '--short', 'HEAD'], { silent: true })
const symbolicRef = await executeCommand(['git', '-C', repoPath, 'symbolic-ref', '--short', 'HEAD'], { env, silent: true })
return symbolicRef.trim()
} catch {
return null
}
}
const currentBranch = await executeCommand(['git', '-C', repoPath, 'rev-parse', '--abbrev-ref', 'HEAD'], { silent: true })
const currentBranch = await executeCommand(['git', '-C', repoPath, 'rev-parse', '--abbrev-ref', 'HEAD'], { env, silent: true })
return currentBranch.trim()
} catch {
return null
}
}
async function checkoutBranchSafely(repoPath: string, branch: string): Promise<void> {
async function checkoutBranchSafely(repoPath: string, branch: string, env: Record<string, string>): Promise<void> {
const sanitizedBranch = branch
.replace(/^refs\/heads\//, '')
.replace(/^refs\/remotes\//, '')
@@ -133,7 +96,7 @@ async function checkoutBranchSafely(repoPath: string, branch: string): Promise<v
let localBranchExists = false
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/heads/${sanitizedBranch}`], { silent: true })
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/heads/${sanitizedBranch}`], { env, silent: true })
localBranchExists = true
} catch {
localBranchExists = false
@@ -141,7 +104,7 @@ async function checkoutBranchSafely(repoPath: string, branch: string): Promise<v
let remoteBranchExists = false
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/remotes/origin/${sanitizedBranch}`], { silent: true })
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/remotes/origin/${sanitizedBranch}`], { env, silent: true })
remoteBranchExists = true
} catch {
remoteBranchExists = false
@@ -149,34 +112,24 @@ async function checkoutBranchSafely(repoPath: string, branch: string): Promise<v
if (localBranchExists) {
logger.info(`Checking out existing local branch: ${sanitizedBranch}`)
await executeCommand(['git', '-C', repoPath, 'checkout', sanitizedBranch])
await executeCommand(['git', '-C', repoPath, 'checkout', sanitizedBranch], { env })
} else if (remoteBranchExists) {
logger.info(`Checking out remote branch: ${sanitizedBranch}`)
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch, `origin/${sanitizedBranch}`])
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch, `origin/${sanitizedBranch}`], { env })
} else {
logger.info(`Creating new branch: ${sanitizedBranch}`)
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch])
}
}
function getGitEnv(database: Database): Record<string, string> {
try {
const settingsService = new SettingsService(database)
const settings = settingsService.getSettings('default')
const gitCredentials = settings.preferences.gitCredentials || []
return createGitEnv(gitCredentials)
} catch {
return createNoPromptGitEnv()
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch], { env })
}
}
export async function initLocalRepo(
database: Database,
gitAuthService: GitAuthService,
localPath: string,
branch?: string
): Promise<Repo> {
const normalizedInputPath = localPath.trim().replace(/\/+$/, '')
const env = gitAuthService.getGitEnvironment()
let targetPath: string
let repoLocalPath: string
@@ -194,7 +147,7 @@ export async function initLocalRepo(
throw new Error(`No such file or directory: '${normalizedInputPath}'`)
}
const isGit = await isValidGitRepo(normalizedInputPath)
const isGit = await isValidGitRepo(normalizedInputPath, env)
if (isGit) {
sourceWasGitRepo = true
@@ -208,16 +161,16 @@ export async function initLocalRepo(
repoLocalPath = baseName
logger.info(`Copying existing git repo from ${normalizedInputPath} to workspace as ${baseName}`)
await copyRepoToWorkspace(normalizedInputPath, baseName)
await copyRepoToWorkspace(normalizedInputPath, baseName, env)
targetPath = path.join(getReposPath(), baseName)
} else {
throw new Error(`Directory exists but is not a valid Git repository. Please provide either a Git repository path or a simple directory name to create a new empty repository.`)
}
} catch (error: any) {
if (error.message.includes('No such file or directory')) {
} catch (error: unknown) {
if (isErrorWithMessage(error) && getErrorMessage(error).includes('No such file or directory')) {
throw error
}
throw new Error(`Failed to process absolute path '${normalizedInputPath}': ${error.message}`)
throw new Error(`Failed to process absolute path '${normalizedInputPath}': ${getErrorMessage(error)}`)
}
} else {
repoLocalPath = normalizedInputPath
@@ -245,9 +198,9 @@ export async function initLocalRepo(
try {
repo = db.createRepo(database, createRepoInput)
logger.info(`Created database record for local repo: ${repoLocalPath} (id: ${repo.id})`)
} catch (error: any) {
} catch (error: unknown) {
logger.error(`Failed to create database record for local repo: ${repoLocalPath}`, error)
throw new Error(`Failed to register local repository '${repoLocalPath}': ${error.message}`)
throw new Error(`Failed to register local repository '${repoLocalPath}': ${getErrorMessage(error)}`)
}
try {
@@ -265,10 +218,10 @@ export async function initLocalRepo(
} else {
if (branch) {
logger.info(`Switching to branch ${branch} for copied repo`)
const currentBranch = await safeGetCurrentBranch(targetPath)
const currentBranch = await safeGetCurrentBranch(targetPath, env)
if (currentBranch !== branch) {
await checkoutBranchSafely(targetPath, branch)
await checkoutBranchSafely(targetPath, branch, env)
}
}
}
@@ -284,38 +237,39 @@ export async function initLocalRepo(
db.updateRepoStatus(database, repo.id, 'ready')
logger.info(`Local git repo ready: ${repoLocalPath}`)
return { ...repo, cloneStatus: 'ready' }
} catch (error: any) {
} catch (error: unknown) {
logger.error(`Failed to initialize local repo, rolling back: ${repoLocalPath}`, error)
try {
db.deleteRepo(database, repo.id)
logger.info(`Rolled back database record for repo id: ${repo.id}`)
} catch (dbError: any) {
logger.error(`Failed to rollback database record for repo id ${repo.id}:`, dbError)
} catch (dbError: unknown) {
logger.error(`Failed to rollback database record for repo id ${repo.id}:`, getErrorMessage(dbError))
}
if (directoryCreated && !sourceWasGitRepo) {
try {
await executeCommand(['rm', '-rf', repoLocalPath], getReposPath())
logger.info(`Rolled back directory: ${repoLocalPath}`)
} catch (fsError: any) {
logger.error(`Failed to rollback directory ${repoLocalPath}:`, fsError)
} catch (fsError: unknown) {
logger.error(`Failed to rollback directory ${repoLocalPath}:`, getErrorMessage(fsError))
}
} else if (sourceWasGitRepo) {
try {
await executeCommand(['rm', '-rf', repoLocalPath], getReposPath())
logger.info(`Cleaned up copied directory: ${repoLocalPath}`)
} catch (fsError: any) {
logger.error(`Failed to clean up copied directory ${repoLocalPath}:`, fsError)
} catch (fsError: unknown) {
logger.error(`Failed to clean up copied directory ${repoLocalPath}:`, getErrorMessage(fsError))
}
}
throw new Error(`Failed to initialize local repository '${repoLocalPath}': ${error.message}`)
throw new Error(`Failed to initialize local repository '${repoLocalPath}': ${getErrorMessage(error)}`)
}
}
export async function cloneRepo(
database: Database,
gitAuthService: GitAuthService,
repoUrl: string,
branch?: string,
useWorktree: boolean = false
@@ -351,9 +305,9 @@ export async function cloneRepo(
}
const repo = db.createRepo(database, createRepoInput)
try {
const env = getGitEnv(database)
const env = gitAuthService.getGitEnvironment()
if (shouldUseWorktree) {
logger.info(`Creating worktree for branch: ${branch}`)
@@ -361,10 +315,10 @@ export async function cloneRepo(
const baseRepoPath = path.resolve(getReposPath(), baseRepoDirName)
const worktreePath = path.resolve(getReposPath(), worktreeDirName)
await executeGitWithFallback(['git', '-C', baseRepoPath, 'fetch', '--all'], { cwd: getReposPath(), env })
await executeCommand(['git', '-C', baseRepoPath, 'fetch', '--all'], { cwd: getReposPath(), env })
await createWorktreeSafely(baseRepoPath, worktreePath, branch)
await createWorktreeSafely(baseRepoPath, worktreePath, branch, env)
const worktreeVerified = await executeCommand(['test', '-d', worktreePath])
.then(() => true)
@@ -388,22 +342,22 @@ export async function cloneRepo(
if (verifyRemoved.trim() === 'exists') {
throw new Error(`Failed to remove existing directory: ${worktreeDirName}`)
}
} catch (cleanupError: any) {
} catch (cleanupError: unknown) {
logger.error(`Failed to clean up existing directory: ${worktreeDirName}`, cleanupError)
throw new Error(`Cannot clone: directory ${worktreeDirName} exists and could not be removed`)
}
}
try {
await executeGitWithFallback(['git', 'clone', '-b', branch, normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env })
} catch (error: any) {
if (error.message.includes('destination path') && error.message.includes('already exists')) {
await executeCommand(['git', 'clone', '-b', branch, normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env })
} catch (error: unknown) {
if (isErrorWithMessage(error) && getErrorMessage(error).includes('destination path') && getErrorMessage(error).includes('already exists')) {
logger.error(`Clone failed: directory still exists after cleanup attempt`)
throw new Error(`Workspace directory ${worktreeDirName} already exists. Please delete it manually or contact support.`)
}
logger.info(`Branch '${branch}' not found during clone, cloning default branch and creating branch locally`)
await executeGitWithFallback(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env })
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env })
let localBranchExists = 'missing'
try {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`])
@@ -427,7 +381,7 @@ export async function cloneRepo(
if (branch) {
logger.info(`Switching to branch: ${branch}`)
await executeGitWithFallback(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'fetch', '--all'], { cwd: getReposPath(), env })
await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'fetch', '--all'], { cwd: getReposPath(), env })
let remoteBranchExists = false
@@ -474,30 +428,30 @@ export async function cloneRepo(
try {
await executeCommand(['rm', '-rf', worktreeDirName], getReposPath())
const verifyRemoved = await executeCommand(['bash', '-c', `test -d ${worktreeDirName} && echo exists || echo removed`], getReposPath())
if (verifyRemoved.trim() === 'exists') {
throw new Error(`Failed to remove existing directory: ${worktreeDirName}`)
}
} catch (cleanupError: any) {
logger.error(`Failed to clean up existing directory: ${worktreeDirName}`, cleanupError)
throw new Error(`Cannot clone: directory ${worktreeDirName} exists and could not be removed`)
if (verifyRemoved.trim() === 'exists') {
throw new Error(`Failed to remove existing directory: ${worktreeDirName}`)
}
} catch (cleanupError: unknown) {
logger.error(`Failed to clean up existing directory: ${worktreeDirName}`, cleanupError)
throw new Error(`Cannot clone: directory ${worktreeDirName} exists and could not be removed`)
}
}
try {
const cloneCmd = branch
? ['git', 'clone', '-b', branch, normalizedRepoUrl, worktreeDirName]
: ['git', 'clone', normalizedRepoUrl, worktreeDirName]
await executeGitWithFallback(cloneCmd, { cwd: getReposPath(), env })
} catch (error: any) {
if (error.message.includes('destination path') && error.message.includes('already exists')) {
await executeCommand(cloneCmd, { cwd: getReposPath(), env })
} catch (error: unknown) {
if (isErrorWithMessage(error) && getErrorMessage(error).includes('destination path') && getErrorMessage(error).includes('already exists')) {
logger.error(`Clone failed: directory still exists after cleanup attempt`)
throw new Error(`Workspace directory ${worktreeDirName} already exists. Please delete it manually or contact support.`)
}
if (branch && (error.message.includes('Remote branch') || error.message.includes('not found'))) {
if (branch && isErrorWithMessage(error) && (getErrorMessage(error).includes('Remote branch') || getErrorMessage(error).includes('not found'))) {
logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`)
await executeGitWithFallback(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env })
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env })
let localBranchExists = 'missing'
try {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`])
@@ -520,64 +474,25 @@ export async function cloneRepo(
db.updateRepoStatus(database, repo.id, 'ready')
logger.info(`Repo ready: ${normalizedRepoUrl}${branch ? `#${branch}` : ''}${shouldUseWorktree ? ' (worktree)' : ''}`)
return { ...repo, cloneStatus: 'ready' }
} catch (error: any) {
} catch (error: unknown) {
logger.error(`Failed to create repo: ${normalizedRepoUrl}${branch ? `#${branch}` : ''}`, error)
db.deleteRepo(database, repo.id)
throw error
}
}
export async function getCurrentBranch(repo: Repo): Promise<string | null> {
export async function getCurrentBranch(repo: Repo, env: Record<string, string>): Promise<string | null> {
const repoPath = path.resolve(getReposPath(), repo.localPath)
const branch = await safeGetCurrentBranch(repoPath)
const branch = await safeGetCurrentBranch(repoPath, env)
return branch || repo.branch || repo.defaultBranch || null
}
export async function listBranches(database: Database, repo: Repo): Promise<{ local: string[], all: string[], current: string | null }> {
try {
const repoPath = path.resolve(getReposPath(), repo.localPath)
const env = getGitEnv(database)
if (!repo.isLocal) {
try {
await executeGitWithFallback(['git', '-C', repoPath, 'fetch', '--all'], { env })
} catch (error) {
logger.warn(`Failed to fetch remote for repo ${repo.id}, using cached branch info:`, error)
}
}
const localBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '--format=%(refname:short)'])
const localBranches = localBranchesOutput.trim().split('\n').filter(b => b.trim())
let remoteBranches: string[] = []
try {
const remoteBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '-r', '--format=%(refname:short)'])
remoteBranches = remoteBranchesOutput.trim().split('\n')
.filter(b => b.trim() && !b.includes('HEAD') && b.includes('/'))
} catch (error) {
logger.warn(`Failed to get remote branches for repo ${repo.id}:`, error)
}
const current = await getCurrentBranch(repo)
const remoteOnlyBranches = remoteBranches
.map(b => b.replace(/^[^/]+\//, ''))
.filter(b => !localBranches.includes(b))
const allBranches = [...localBranches, ...remoteOnlyBranches]
return {
local: localBranches,
all: allBranches,
current
}
} catch (error: any) {
logger.error(`Failed to list branches for repo ${repo.id}:`, error)
throw error
}
}
export async function switchBranch(database: Database, repoId: number, branch: string): Promise<void> {
export async function switchBranch(
database: Database,
gitAuthService: GitAuthService,
repoId: number,
branch: string
): Promise<void> {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repo not found: ${repoId}`)
@@ -585,7 +500,7 @@ export async function switchBranch(database: Database, repoId: number, branch: s
try {
const repoPath = path.resolve(getReposPath(), repo.localPath)
const env = getGitEnv(database)
const env = gitAuthService.getGitEnvironment()
const sanitizedBranch = branch
.replace(/^refs\/heads\//, '')
@@ -594,18 +509,20 @@ export async function switchBranch(database: Database, repoId: number, branch: s
logger.info(`Switching to branch: ${sanitizedBranch} in ${repo.localPath}`)
await executeGitWithFallback(['git', '-C', repoPath, 'fetch', '--all'], { env })
await executeCommand(['git', '-C', repoPath, 'fetch', '--all'], { env })
await checkoutBranchSafely(repoPath, sanitizedBranch)
await checkoutBranchSafely(repoPath, sanitizedBranch, env)
logger.info(`Successfully switched to branch: ${sanitizedBranch}`)
} catch (error: any) {
db.updateRepoBranch(database, repoId, sanitizedBranch)
} catch (error: unknown) {
logger.error(`Failed to switch branch for repo ${repoId}:`, error)
throw error
}
}
export async function createBranch(database: Database, repoId: number, branch: string): Promise<void> {
export async function createBranch(database: Database, gitAuthService: GitAuthService, repoId: number, branch: string): Promise<void> {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repo not found: ${repoId}`)
@@ -613,6 +530,7 @@ export async function createBranch(database: Database, repoId: number, branch: s
try {
const repoPath = path.resolve(getReposPath(), repo.localPath)
const env = gitAuthService.getGitEnvironment()
const sanitizedBranch = branch
.replace(/^refs\/heads\//, '')
@@ -620,15 +538,21 @@ export async function createBranch(database: Database, repoId: number, branch: s
.replace(/^origin\//, '')
logger.info(`Creating new branch: ${sanitizedBranch} in ${repo.localPath}`)
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch])
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch], { env })
logger.info(`Successfully created and switched to branch: ${sanitizedBranch}`)
} catch (error: any) {
db.updateRepoBranch(database, repoId, sanitizedBranch)
} catch (error: unknown) {
logger.error(`Failed to create branch for repo ${repoId}:`, error)
throw error
}
}
export async function pullRepo(database: Database, repoId: number): Promise<void> {
export async function pullRepo(
database: Database,
gitAuthService: GitAuthService,
repoId: number
): Promise<void> {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repo not found: ${repoId}`)
@@ -640,14 +564,14 @@ export async function pullRepo(database: Database, repoId: number): Promise<void
}
try {
const env = getGitEnv(database)
const env = gitAuthService.getGitEnvironment()
logger.info(`Pulling repo: ${repo.repoUrl}`)
await executeCommand(['git', '-C', path.resolve(getReposPath(), repo.localPath), 'pull'], { env })
db.updateLastPulled(database, repoId)
logger.info(`Repo pulled successfully: ${repo.repoUrl}`)
} catch (error: any) {
} catch (error: unknown) {
logger.error(`Failed to pull repo: ${repo.repoUrl}`, error)
throw error
}
@@ -658,85 +582,41 @@ export async function deleteRepoFiles(database: Database, repoId: number): Promi
if (!repo) {
throw new Error(`Repo not found: ${repoId}`)
}
const repoIdentifier = repo.repoUrl || repo.localPath
try {
logger.info(`Deleting repo files: ${repoIdentifier}`)
// Extract just the directory name from the localPath
const dirName = repo.localPath.split('/').pop() || repo.localPath
const fullPath = path.resolve(getReposPath(), dirName)
// If this is a worktree, properly remove it from git first
if (repo.isWorktree && repo.branch && repo.repoUrl) {
const { name: repoName } = normalizeRepoUrl(repo.repoUrl)
const baseRepoPath = path.resolve(getReposPath(), repoName)
logger.info(`Removing worktree: ${dirName} from base repo: ${baseRepoPath}`)
try {
// First try to remove the worktree properly
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', fullPath])
logger.info(`Successfully removed worktree: ${dirName}`)
} catch (worktreeError: any) {
logger.warn(`Failed to remove worktree with normal command, trying force: ${worktreeError.message}`)
try {
// Try force removal
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', '--force', fullPath])
logger.info(`Successfully force-removed worktree: ${dirName}`)
} catch (forceError: any) {
logger.warn(`Force worktree removal failed, trying prune: ${forceError.message}`)
try {
// Prune worktree references and try again
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'prune'])
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', '--force', fullPath])
logger.info(`Successfully removed worktree after prune: ${dirName}`)
} catch (pruneError: any) {
logger.error(`All worktree removal methods failed: ${pruneError.message}`)
// Continue with directory removal anyway
}
}
}
const dirName = repo.localPath.split('/').pop() || repo.localPath
const fullPath = path.resolve(getReposPath(), dirName)
if (repo.isWorktree && repo.repoUrl) {
const { name: repoName } = normalizeRepoUrl(repo.repoUrl)
const baseRepoPath = path.resolve(getReposPath(), repoName)
try {
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', '--force', fullPath])
} catch {
// Worktree removal failed, continue with directory removal
} finally {
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'prune']).catch(() => {})
}
// Remove the directory
logger.info(`Removing directory: ${dirName} from ${getReposPath()}`)
await executeCommand(['rm', '-rf', dirName], getReposPath())
const checkExists = await executeCommand(['bash', '-c', `test -d ${dirName} && echo exists || echo deleted`], getReposPath())
if (checkExists.trim() === 'exists') {
logger.error(`Directory still exists after deletion: ${dirName}`)
throw new Error(`Failed to delete workspace directory: ${dirName}`)
}
// If this was a worktree, also prune the base repo to clean up any remaining references
if (repo.isWorktree && repo.branch && repo.repoUrl) {
const { name: repoName } = normalizeRepoUrl(repo.repoUrl)
const baseRepoPath = path.resolve(getReposPath(), repoName)
try {
logger.info(`Pruning worktree references in base repo: ${baseRepoPath}`)
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'prune'])
} catch (pruneError: any) {
logger.warn(`Failed to prune worktree references: ${pruneError.message}`)
}
}
db.deleteRepo(database, repoId)
logger.info(`Repo deleted successfully: ${repoIdentifier}`)
} catch (error: any) {
logger.error(`Failed to delete repo: ${repoIdentifier}`, error)
throw error
}
await executeCommand(['rm', '-rf', dirName], getReposPath())
db.deleteRepo(database, repoId)
}
function normalizeRepoUrl(url: string): { url: string; name: string } {
const shorthandMatch = url.match(/^([^\/]+)\/([^\/]+)$/)
const sshMatch = url.match(/^git@([^:]+):(.+?)(?:\.git)?$/)
if (sshMatch) {
const [, host, pathPart] = sshMatch
const repoName = pathPart.split('/').pop() || `repo-${Date.now()}`
return {
url: `https://${host}/${pathPart.replace(/\.git$/, '')}`,
name: repoName
}
}
const shorthandMatch = url.match(/^([^/]+)\/([^/]+)$/)
if (shorthandMatch) {
const [, owner, repoName] = shorthandMatch as [string, string, string]
const [, owner, repoName] = shorthandMatch
return {
url: `https://github.com/${owner}/${repoName}`,
name: repoName
@@ -744,11 +624,10 @@ function normalizeRepoUrl(url: string): { url: string; name: string } {
}
if (url.startsWith('http://') || url.startsWith('https://')) {
const httpsUrl = url.replace(/^http:/, 'https:')
const urlWithoutGit = httpsUrl.replace(/\.git$/, '')
const match = urlWithoutGit.match(/\/([^\/]+)$/)
const httpsUrl = url.replace(/^http:/, 'https:').replace(/\.git$/, '')
const match = httpsUrl.match(/([^/]+)$/)
return {
url: urlWithoutGit,
url: httpsUrl,
name: match?.[1] || `repo-${Date.now()}`
}
}
@@ -763,140 +642,55 @@ export async function cleanupOrphanedDirectories(database: Database): Promise<vo
try {
const reposPath = getReposPath()
await ensureDirectoryExists(reposPath)
const dirResult = await executeCommand(['ls', '-1'], reposPath).catch(() => '')
const directories = dirResult.split('\n').filter(d => d.trim())
if (directories.length === 0) {
return
}
const allRepos = db.listRepos(database)
const trackedPaths = new Set(allRepos.map(r => r.localPath.split('/').pop()))
const orphanedDirs = directories.filter(dir => !trackedPaths.has(dir))
if (orphanedDirs.length > 0) {
logger.info(`Found ${orphanedDirs.length} orphaned directories: ${orphanedDirs.join(', ')}`)
for (const dir of orphanedDirs) {
try {
logger.info(`Removing orphaned directory: ${dir}`)
await executeCommand(['rm', '-rf', dir], reposPath)
} catch (error) {
logger.warn(`Failed to remove orphaned directory ${dir}:`, error)
}
}
for (const dir of orphanedDirs) {
await executeCommand(['rm', '-rf', dir], reposPath).catch(() => {})
}
} catch (error) {
logger.warn('Failed to cleanup orphaned directories:', error)
} catch {
// Cleanup is best-effort
}
}
async function pruneWorktreeReferences(baseRepoPath: string): Promise<void> {
try {
logger.info(`Pruning worktree references for: ${baseRepoPath}`)
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'prune'])
logger.info(`Successfully pruned worktree references`)
} catch (error: any) {
logger.warn(`Failed to prune worktree references:`, error.message)
}
}
async function cleanupStaleWorktree(baseRepoPath: string, worktreePath: string): Promise<boolean> {
try {
logger.info(`Cleaning up stale worktree: ${worktreePath}`)
const worktreeList = await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'list', '--porcelain'])
const lines = worktreeList.split('\n').filter(line => line.trim())
for (const line of lines) {
if (line.includes(worktreePath)) {
logger.info(`Found worktree reference: ${line}`)
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', '--force', worktreePath])
logger.info(`Successfully removed worktree: ${worktreePath}`)
return true
}
}
logger.info(`No worktree reference found for ${worktreePath}, attempting prune`)
await pruneWorktreeReferences(baseRepoPath)
return true
} catch (error: any) {
logger.warn(`Failed to cleanup worktree ${worktreePath}:`, error.message)
return false
}
}
async function createWorktreeSafely(baseRepoPath: string, worktreePath: string, branch: string): Promise<void> {
const currentBranch = await safeGetCurrentBranch(baseRepoPath)
async function createWorktreeSafely(baseRepoPath: string, worktreePath: string, branch: string, env: Record<string, string>): Promise<void> {
const currentBranch = await safeGetCurrentBranch(baseRepoPath, env)
if (currentBranch === branch) {
logger.info(`Branch '${branch}' is checked out in main repo, switching away...`)
const defaultBranch = await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--abbrev-ref', 'origin/HEAD'])
const defaultBranch = await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--abbrev-ref', 'origin/HEAD'], { env })
.then(ref => ref.trim().replace('origin/', ''))
.catch(() => 'main')
try {
await executeCommand(['git', '-C', baseRepoPath, 'checkout', defaultBranch])
} catch {
logger.warn(`Could not switch to ${defaultBranch}, trying 'main'`)
await executeCommand(['git', '-C', baseRepoPath, 'checkout', 'main'])
}
await executeCommand(['git', '-C', baseRepoPath, 'checkout', defaultBranch], { env })
.catch(() => executeCommand(['git', '-C', baseRepoPath, 'checkout', 'main'], { env }))
}
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'prune'], { env }).catch(() => {})
let branchExists = false
try {
await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--verify', `refs/heads/${branch}`])
await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--verify', `refs/heads/${branch}`], { env, silent: true })
branchExists = true
} catch {
try {
await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--verify', `refs/remotes/origin/${branch}`])
await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--verify', `refs/remotes/origin/${branch}`], { env, silent: true })
branchExists = true
} catch {
branchExists = false
}
}
const maxRetries = 3
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
logger.info(`Creating worktree (attempt ${attempt}/${maxRetries}): ${branch} -> ${worktreePath}`)
if (branchExists) {
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'add', worktreePath, branch])
} else {
logger.info(`Branch '${branch}' does not exist, creating it in worktree`)
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'add', '-b', branch, worktreePath])
}
logger.info(`Successfully created worktree: ${worktreePath}`)
return
} catch (error: any) {
const isLastAttempt = attempt === maxRetries
const errorMessage = error.message || ''
if (errorMessage.includes('already used by worktree')) {
logger.warn(`Worktree already exists, attempting cleanup (attempt ${attempt}/${maxRetries})`)
const cleaned = await cleanupStaleWorktree(baseRepoPath, worktreePath)
if (!cleaned && isLastAttempt) {
throw new Error(`Failed to create worktree: '${branch}' is already used by a worktree and cleanup failed. Manual intervention may be required.`)
}
if (!cleaned) {
logger.warn(`Cleanup failed, will retry...`)
continue
}
} else if (isLastAttempt) {
throw new Error(`Failed to create worktree after ${maxRetries} attempts: ${errorMessage}`)
} else {
logger.warn(`Worktree creation failed (attempt ${attempt}/${maxRetries}): ${errorMessage}, retrying...`)
}
}
if (branchExists) {
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'add', worktreePath, branch], { env })
} else {
await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'add', '-b', branch, worktreePath], { env })
}
}