From f0d97f8d6edb43f56ba098250bcb5082df99fe6c Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 13 Jan 2026 10:15:07 -0500 Subject: [PATCH] Fix issue #42: Support absolute paths when adding local repos (#52) Add ability to import existing git repositories from absolute paths by copying them to the workspace. Backend changes: - Add helper functions: isValidGitRepo(), checkRepoNameAvailable(), copyRepoToWorkspace() - Add checkoutBranchSafely() helper for consistent branch handling across codebase - Modify initLocalRepo() to detect absolute vs relative paths - For absolute paths: validate, check if git repo, copy to workspace using git clone --local - For relative paths: maintain existing behavior (create new empty git repo) - Refactor switchBranch() to use shared checkoutBranchSafely() helper - Fail with clear error message if repo name already exists in workspace Frontend changes: - Update UI placeholder and help text to explain absolute path support - Branch help text adapts based on input type (absolute vs relative) --- backend/src/services/repo.ts | 204 ++++++++++++----- backend/test/services/repo.test.ts | 210 ++++++++++++++++++ .../src/components/repo/AddRepoDialog.tsx | 38 ++-- 3 files changed, 383 insertions(+), 69 deletions(-) create mode 100644 backend/test/services/repo.test.ts diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index 530e7303..056f39ff 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -76,6 +76,35 @@ async function hasCommits(repoPath: string): Promise { } } +async function isValidGitRepo(repoPath: string): Promise { + try { + await executeCommand(['git', '-C', repoPath, 'rev-parse', '--git-dir'], { silent: true }) + return true + } catch { + return false + } +} + +async function checkRepoNameAvailable(name: string): Promise { + const reposPath = getReposPath() + const targetPath = path.join(reposPath, name) + try { + await executeCommand(['test', '-e', targetPath], { silent: true }) + return false + } catch { + return true + } +} + +async function copyRepoToWorkspace(sourcePath: string, targetName: string): Promise { + 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 }) + logger.info(`Successfully copied repo to ${targetPath}`) +} + async function safeGetCurrentBranch(repoPath: string): Promise { @@ -96,6 +125,40 @@ async function safeGetCurrentBranch(repoPath: string): Promise { } } +async function checkoutBranchSafely(repoPath: string, branch: string): Promise { + const sanitizedBranch = branch + .replace(/^refs\/heads\//, '') + .replace(/^refs\/remotes\//, '') + .replace(/^origin\//, '') + + let localBranchExists = false + try { + await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/heads/${sanitizedBranch}`], { silent: true }) + localBranchExists = true + } catch { + localBranchExists = false + } + + let remoteBranchExists = false + try { + await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/remotes/origin/${sanitizedBranch}`], { silent: true }) + remoteBranchExists = true + } catch { + remoteBranchExists = false + } + + if (localBranchExists) { + logger.info(`Checking out existing local branch: ${sanitizedBranch}`) + await executeCommand(['git', '-C', repoPath, 'checkout', sanitizedBranch]) + } else if (remoteBranchExists) { + logger.info(`Checking out remote branch: ${sanitizedBranch}`) + await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch, `origin/${sanitizedBranch}`]) + } else { + logger.info(`Creating new branch: ${sanitizedBranch}`) + await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch]) + } +} + function getGitEnv(database: Database): Record { try { const settingsService = new SettingsService(database) @@ -113,17 +176,62 @@ export async function initLocalRepo( localPath: string, branch?: string ): Promise { - const normalizedPath = localPath.trim().replace(/\/+$/, '') - const fullPath = path.resolve(getReposPath(), normalizedPath) + const normalizedInputPath = localPath.trim().replace(/\/+$/, '') - const existing = db.getRepoByLocalPath(database, normalizedPath) + let targetPath: string + let repoLocalPath: string + let sourceWasGitRepo = false + + if (path.isAbsolute(normalizedInputPath)) { + logger.info(`Absolute path detected: ${normalizedInputPath}`) + + try { + const exists = await executeCommand(['test', '-d', normalizedInputPath], { silent: true }) + .then(() => true) + .catch(() => false) + + if (!exists) { + throw new Error(`No such file or directory: '${normalizedInputPath}'`) + } + + const isGit = await isValidGitRepo(normalizedInputPath) + + if (isGit) { + sourceWasGitRepo = true + const baseName = path.basename(normalizedInputPath) + + const isAvailable = await checkRepoNameAvailable(baseName) + if (!isAvailable) { + throw new Error(`A repository named '${baseName}' already exists in the workspace. Please remove it first or use a different source directory.`) + } + + repoLocalPath = baseName + + logger.info(`Copying existing git repo from ${normalizedInputPath} to workspace as ${baseName}`) + await copyRepoToWorkspace(normalizedInputPath, baseName) + 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')) { + throw error + } + throw new Error(`Failed to process absolute path '${normalizedInputPath}': ${error.message}`) + } + } else { + repoLocalPath = normalizedInputPath + targetPath = path.join(getReposPath(), repoLocalPath) + } + + const existing = db.getRepoByLocalPath(database, repoLocalPath) if (existing) { - logger.info(`Local repo already exists in database: ${normalizedPath}`) + logger.info(`Local repo already exists in database: ${repoLocalPath}`) return existing } const createRepoInput: CreateRepoInput = { - localPath: normalizedPath, + localPath: repoLocalPath, branch: branch || undefined, defaultBranch: branch || 'main', cloneStatus: 'cloning', @@ -136,26 +244,36 @@ export async function initLocalRepo( try { repo = db.createRepo(database, createRepoInput) - logger.info(`Created database record for local repo: ${normalizedPath} (id: ${repo.id})`) + logger.info(`Created database record for local repo: ${repoLocalPath} (id: ${repo.id})`) } catch (error: any) { - logger.error(`Failed to create database record for local repo: ${normalizedPath}`, error) - throw new Error(`Failed to register local repository '${normalizedPath}': ${error.message}`) + logger.error(`Failed to create database record for local repo: ${repoLocalPath}`, error) + throw new Error(`Failed to register local repository '${repoLocalPath}': ${error.message}`) } try { - await ensureDirectoryExists(fullPath) - directoryCreated = true - logger.info(`Created directory for local repo: ${fullPath}`) - - logger.info(`Initializing git repository: ${fullPath}`) - - await executeCommand(['git', 'init'], { cwd: fullPath }) - - if (branch && branch !== 'main') { - await executeCommand(['git', '-C', fullPath, 'checkout', '-b', branch]) + if (!sourceWasGitRepo) { + await ensureDirectoryExists(targetPath) + directoryCreated = true + logger.info(`Created directory for local repo: ${targetPath}`) + + logger.info(`Initializing git repository: ${targetPath}`) + await executeCommand(['git', 'init'], { cwd: targetPath }) + + if (branch && branch !== 'main') { + await executeCommand(['git', '-C', targetPath, 'checkout', '-b', branch]) + } + } else { + if (branch) { + logger.info(`Switching to branch ${branch} for copied repo`) + const currentBranch = await safeGetCurrentBranch(targetPath) + + if (currentBranch !== branch) { + await checkoutBranchSafely(targetPath, branch) + } + } } - const isGitRepo = await executeCommand(['git', '-C', fullPath, 'rev-parse', '--git-dir']) + const isGitRepo = await executeCommand(['git', '-C', targetPath, 'rev-parse', '--git-dir']) .then(() => true) .catch(() => false) @@ -164,10 +282,10 @@ export async function initLocalRepo( } db.updateRepoStatus(database, repo.id, 'ready') - logger.info(`Local git repo ready: ${normalizedPath}`) + logger.info(`Local git repo ready: ${repoLocalPath}`) return { ...repo, cloneStatus: 'ready' } } catch (error: any) { - logger.error(`Failed to initialize local repo, rolling back: ${normalizedPath}`, error) + logger.error(`Failed to initialize local repo, rolling back: ${repoLocalPath}`, error) try { db.deleteRepo(database, repo.id) @@ -176,16 +294,23 @@ export async function initLocalRepo( logger.error(`Failed to rollback database record for repo id ${repo.id}:`, dbError) } - if (directoryCreated) { + if (directoryCreated && !sourceWasGitRepo) { try { - await executeCommand(['rm', '-rf', normalizedPath], getReposPath()) - logger.info(`Rolled back directory: ${normalizedPath}`) + await executeCommand(['rm', '-rf', repoLocalPath], getReposPath()) + logger.info(`Rolled back directory: ${repoLocalPath}`) } catch (fsError: any) { - logger.error(`Failed to rollback directory ${normalizedPath}:`, fsError) + logger.error(`Failed to rollback directory ${repoLocalPath}:`, 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) } } - throw new Error(`Failed to initialize local repository '${normalizedPath}': ${error.message}`) + throw new Error(`Failed to initialize local repository '${repoLocalPath}': ${error.message}`) } } @@ -471,32 +596,7 @@ export async function switchBranch(database: Database, repoId: number, branch: s await executeGitWithFallback(['git', '-C', repoPath, 'fetch', '--all'], { env }) - let localBranchExists = false - try { - await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/heads/${sanitizedBranch}`]) - localBranchExists = true - } catch { - localBranchExists = false - } - - let remoteBranchExists = false - try { - await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/remotes/origin/${sanitizedBranch}`]) - remoteBranchExists = true - } catch { - remoteBranchExists = false - } - - if (localBranchExists) { - logger.info(`Checking out existing local branch: ${sanitizedBranch}`) - await executeCommand(['git', '-C', repoPath, 'checkout', sanitizedBranch]) - } else if (remoteBranchExists) { - logger.info(`Checking out remote branch: ${sanitizedBranch}`) - await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch, `origin/${sanitizedBranch}`]) - } else { - logger.info(`Creating new branch: ${sanitizedBranch}`) - await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch]) - } + await checkoutBranchSafely(repoPath, sanitizedBranch) logger.info(`Successfully switched to branch: ${sanitizedBranch}`) } catch (error: any) { diff --git a/backend/test/services/repo.test.ts b/backend/test/services/repo.test.ts new file mode 100644 index 00000000..33f2e6ea --- /dev/null +++ b/backend/test/services/repo.test.ts @@ -0,0 +1,210 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { getReposPath } from '@opencode-manager/shared/config/env' + +const executeCommand = vi.fn() +const ensureDirectoryExists = vi.fn() + +const getRepoByLocalPath = vi.fn() +const createRepo = vi.fn() +const updateRepoStatus = vi.fn() +const deleteRepo = vi.fn() + +vi.mock('../../src/utils/process', () => ({ + executeCommand, +})) + +vi.mock('../../src/services/file-operations', () => ({ + ensureDirectoryExists, +})) + +vi.mock('../../src/db/queries', () => ({ + getRepoByLocalPath, + createRepo, + updateRepoStatus, + deleteRepo, +})) + +vi.mock('../../src/services/settings', () => ({ + SettingsService: vi.fn().mockImplementation(() => ({ + getSettings: () => ({ + preferences: { + gitCredentials: [], + }, + updatedAt: Date.now(), + }), + })), +})) + +describe('initLocalRepo', () => { + beforeEach(() => { + vi.clearAllMocks() + vi.resetModules() + executeCommand.mockResolvedValue('') + ensureDirectoryExists.mockResolvedValue(undefined) + }) + + it('creates new empty git repo for relative path', async () => { + const { initLocalRepo } = await import('../../src/services/repo') + const database = {} as any + const localPath = 'my-new-repo' + + getRepoByLocalPath.mockReturnValue(null) + createRepo.mockReturnValue({ + id: 1, + repoUrl: undefined, + localPath: 'my-new-repo', + defaultBranch: 'main', + cloneStatus: 'cloning', + clonedAt: Date.now(), + isLocal: true, + }) + + const result = await initLocalRepo(database, localPath) + + expect(executeCommand).toHaveBeenCalledWith(['git', 'init'], expect.any(Object)) + expect(ensureDirectoryExists).toHaveBeenCalledWith(expect.stringContaining('my-new-repo')) + expect(updateRepoStatus).toHaveBeenCalledWith(database, 1, 'ready') + expect(result.cloneStatus).toBe('ready') + }) + + it('copies existing git repo from absolute path', async () => { + const { initLocalRepo } = await import('../../src/services/repo') + const database = {} as any + const absolutePath = '/Users/test/existing-repo' + + getRepoByLocalPath.mockReturnValue(null) + createRepo.mockImplementation((_, input) => ({ + id: 2, + repoUrl: undefined, + localPath: input.localPath, + defaultBranch: 'main', + cloneStatus: 'cloning', + clonedAt: Date.now(), + isLocal: true, + })) + + let callCount = 0 + executeCommand.mockImplementation(async () => { + callCount++ + if (callCount === 2) return '.git' + if (callCount === 3) throw new Error('not found') + if (callCount === 5) return '.git' + return '' + }) + + const result = await initLocalRepo(database, absolutePath) + + expect(executeCommand).toHaveBeenCalledWith(['test', '-d', '/Users/test/existing-repo'], { silent: true }) + expect(executeCommand).toHaveBeenCalledWith(['git', '-C', '/Users/test/existing-repo', 'rev-parse', '--git-dir'], { silent: true }) + expect(executeCommand).toHaveBeenCalledWith(['git', 'clone', '--local', '/Users/test/existing-repo', 'existing-repo'], expect.objectContaining({ cwd: getReposPath() })) + expect(updateRepoStatus).toHaveBeenCalledWith(database, 2, 'ready') + expect(result.cloneStatus).toBe('ready') + expect(result.localPath).toBe('existing-repo') + }) + + it('returns existing repo if local path already in database (relative)', async () => { + const { initLocalRepo } = await import('../../src/services/repo') + const database = {} as any + const localPath = 'existing-repo' + const existingRepo = { + id: 100, + localPath: 'existing-repo', + cloneStatus: 'ready' as const, + } + + getRepoByLocalPath.mockReturnValue(existingRepo) + + const result = await initLocalRepo(database, localPath) + + expect(result).toBe(existingRepo) + expect(createRepo).not.toHaveBeenCalled() + expect(executeCommand).not.toHaveBeenCalled() + }) + + it('throws error when absolute path does not exist', async () => { + const { initLocalRepo } = await import('../../src/services/repo') + const database = {} as any + const nonExistentPath = '/Users/test/non-existent' + + executeCommand.mockRejectedValueOnce(new Error('Command failed')) + + await expect(initLocalRepo(database, nonExistentPath)).rejects.toThrow("No such file or directory") + }) + + it('throws error when repo name already exists in workspace', async () => { + const { initLocalRepo } = await import('../../src/services/repo') + const database = {} as any + const absolutePath = '/Users/test/existing-repo' + + let callCount = 0 + executeCommand.mockImplementation(async () => { + callCount++ + if (callCount === 2) return '.git' + if (callCount === 3) return '' + return '' + }) + + await expect(initLocalRepo(database, absolutePath)).rejects.toThrow("A repository named 'existing-repo' already exists in the workspace") + }) + + it('throws error when absolute path is not a git repo', async () => { + const { initLocalRepo } = await import('../../src/services/repo') + const database = {} as any + const nonGitPath = '/Users/test/not-a-repo' + + let callCount = 0 + executeCommand.mockImplementation(async () => { + callCount++ + if (callCount === 2) throw new Error('Not a git repo') + return '' + }) + + await expect(initLocalRepo(database, nonGitPath)).rejects.toThrow("Directory exists but is not a valid Git repository") + }) + + it('creates new empty repo with custom branch', async () => { + const { initLocalRepo } = await import('../../src/services/repo') + const database = {} as any + const localPath = 'custom-branch-repo' + const branch = 'develop' + + getRepoByLocalPath.mockReturnValue(null) + createRepo.mockReturnValue({ + id: 3, + repoUrl: undefined, + localPath: 'custom-branch-repo', + branch: 'develop', + defaultBranch: 'develop', + cloneStatus: 'cloning', + clonedAt: Date.now(), + isLocal: true, + }) + + const result = await initLocalRepo(database, localPath, branch) + + expect(executeCommand).toHaveBeenCalledWith(['git', 'init'], expect.any(Object)) + expect(executeCommand).toHaveBeenCalledWith(['git', '-C', expect.any(String), 'checkout', '-b', 'develop']) + expect(result.defaultBranch).toBe('develop') + }) + + it('normalizes trailing slashes in path', async () => { + const { initLocalRepo } = await import('../../src/services/repo') + const database = {} as any + const localPath = 'my-repo/' + + getRepoByLocalPath.mockReturnValue(null) + createRepo.mockReturnValue({ + id: 4, + repoUrl: undefined, + localPath: 'my-repo', + defaultBranch: 'main', + cloneStatus: 'cloning', + clonedAt: Date.now(), + isLocal: true, + }) + + const result = await initLocalRepo(database, localPath) + + expect(result.localPath).toBe('my-repo') + }) +}) diff --git a/frontend/src/components/repo/AddRepoDialog.tsx b/frontend/src/components/repo/AddRepoDialog.tsx index 02ce2a4f..b7c7cb42 100644 --- a/frontend/src/components/repo/AddRepoDialog.tsx +++ b/frontend/src/components/repo/AddRepoDialog.tsx @@ -83,31 +83,31 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) { {repoType === 'remote' ? ( -
- - setRepoUrl(e.target.value)} - disabled={mutation.isPending} - className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500" - /> -

- Full URL or shorthand format (owner/repo for GitHub) -

-
+
+ + setRepoUrl(e.target.value)} + disabled={mutation.isPending} + className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500" + /> +

+ Full URL or shorthand format (owner/repo for GitHub) +

+
) : (
setLocalPath(e.target.value)} disabled={mutation.isPending} className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500" />

- Directory name will be created in the repos folder + Directory name for new repo, OR absolute path to existing Git repo (will be copied to workspace)

)} @@ -125,10 +125,14 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) { {branch ? repoType === 'remote' ? `Clones repository directly to '${branch}' branch` - : `Initializes repository with '${branch}' branch` + : localPath?.startsWith('/') + ? `Copies repo and checks out '${branch}' branch (creates if needed)` + : `Initializes repository with '${branch}' branch` : repoType === 'remote' ? "Clones repository to default branch" - : "Initializes repository with 'main' branch" + : localPath?.startsWith('/') + ? "Copies repo and checks out current branch" + : "Initializes repository with 'main' branch" }