mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
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:
1 parent
524ce018dc
commit
e91c54ba20
64 files changed
+6214
-1915
No files matched your search
+162
-368
@@ -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 })
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user