mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +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
Executable
+2
@@ -0,0 +1,2 @@
|
||||
#!/bin/sh
|
||||
echo ''
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env bun
|
||||
import http from 'http'
|
||||
import fs from 'fs'
|
||||
|
||||
interface AskpassRequest {
|
||||
askpassType: 'https' | 'ssh'
|
||||
argv: string[]
|
||||
}
|
||||
|
||||
function fatal(err: unknown): never {
|
||||
if (err instanceof Error) {
|
||||
console.error(err.message)
|
||||
} else if (typeof err === 'string') {
|
||||
console.error(err)
|
||||
}
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
function main(argv: string[]): void {
|
||||
const output = process.env['VSCODE_GIT_ASKPASS_PIPE']
|
||||
if (!output) {
|
||||
return fatal('Missing pipe')
|
||||
}
|
||||
|
||||
const askpassType = process.env['VSCODE_GIT_ASKPASS_TYPE']
|
||||
if (!askpassType) {
|
||||
return fatal('Missing type')
|
||||
}
|
||||
|
||||
if (askpassType !== 'https' && askpassType !== 'ssh') {
|
||||
return fatal(`Invalid type: ${askpassType}`)
|
||||
}
|
||||
|
||||
const ipcHandlePath = process.env['VSCODE_GIT_IPC_HANDLE']
|
||||
|
||||
console.error(`[askpass-main] pid=${process.pid}, output=${output}, askpassType=${askpassType}, ipcHandlePath=${ipcHandlePath}, argv=${argv.join(', ')}`)
|
||||
|
||||
if (process.env['VSCODE_GIT_FETCH_SILENT']) {
|
||||
console.error('[askpass-main] Silent fetch mode, returning empty')
|
||||
fs.writeFileSync(output, '\n')
|
||||
return process.exit(0)
|
||||
}
|
||||
|
||||
if (!ipcHandlePath) {
|
||||
console.error('[askpass-main] No IPC handle, returning empty')
|
||||
fs.writeFileSync(output, '\n')
|
||||
return process.exit(0)
|
||||
}
|
||||
|
||||
const opts: http.RequestOptions = {
|
||||
socketPath: ipcHandlePath,
|
||||
path: '/askpass',
|
||||
method: 'POST'
|
||||
}
|
||||
|
||||
console.error(`[askpass-main] Connecting to IPC server at ${ipcHandlePath}`)
|
||||
|
||||
const req = http.request(opts, res => {
|
||||
console.error(`[askpass-main] IPC response status: ${res.statusCode}`)
|
||||
if (res.statusCode !== 200) {
|
||||
console.error('[askpass-main] IPC error response, returning empty')
|
||||
fs.writeFileSync(output, '\n')
|
||||
return process.exit(1)
|
||||
}
|
||||
|
||||
const chunks: Buffer[] = []
|
||||
res.on('data', d => chunks.push(d))
|
||||
res.on('end', () => {
|
||||
const body = Buffer.concat(chunks).toString('utf8')
|
||||
console.error(`[askpass-main] IPC response body: "${body}"`)
|
||||
if (!body) {
|
||||
fs.writeFileSync(output, '\n')
|
||||
return process.exit(0)
|
||||
}
|
||||
try {
|
||||
const result = JSON.parse(body)
|
||||
console.error(`[askpass-main] Parsed result: "${result}"`)
|
||||
fs.writeFileSync(output, result + '\n')
|
||||
process.exit(0)
|
||||
} catch (e) {
|
||||
console.error('[askpass-main] JSON parse error:', e)
|
||||
fs.writeFileSync(output, '\n')
|
||||
process.exit(1)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
req.on('error', (e) => {
|
||||
console.error('[askpass-main] IPC request error:', e.message)
|
||||
fs.writeFileSync(output, '\n')
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
const requestPayload: AskpassRequest = { askpassType, argv }
|
||||
console.error('[askpass-main] Sending request:', JSON.stringify(requestPayload))
|
||||
req.write(JSON.stringify(requestPayload))
|
||||
req.end()
|
||||
}
|
||||
|
||||
main(process.argv)
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
VSCODE_GIT_ASKPASS_PIPE=`mktemp`
|
||||
ELECTRON_RUN_AS_NODE="1" VSCODE_GIT_ASKPASS_PIPE="$VSCODE_GIT_ASKPASS_PIPE" VSCODE_GIT_ASKPASS_TYPE="https" "$VSCODE_GIT_ASKPASS_NODE" "$VSCODE_GIT_ASKPASS_MAIN" $VSCODE_GIT_ASKPASS_EXTRA_ARGS $*
|
||||
cat $VSCODE_GIT_ASKPASS_PIPE
|
||||
rm $VSCODE_GIT_ASKPASS_PIPE
|
||||
@@ -171,6 +171,11 @@ export function updateLastPulled(db: Database, id: number): void {
|
||||
stmt.run(Date.now(), id)
|
||||
}
|
||||
|
||||
export function updateRepoBranch(db: Database, id: number, branch: string): void {
|
||||
const stmt = db.prepare('UPDATE repos SET branch = ? WHERE id = ?')
|
||||
stmt.run(branch, id)
|
||||
}
|
||||
|
||||
export function deleteRepo(db: Database, id: number): void {
|
||||
const stmt = db.prepare('DELETE FROM repos WHERE id = ?')
|
||||
stmt.run(id)
|
||||
|
||||
+15
-2
@@ -6,6 +6,8 @@ import os from 'os'
|
||||
import path from 'path'
|
||||
import { initializeDatabase } from './db/schema'
|
||||
import { createRepoRoutes } from './routes/repos'
|
||||
import { createIPCServer, type IPCServer } from './ipc/ipcServer'
|
||||
import { GitAuthService } from './services/git-auth'
|
||||
import { createSettingsRoutes } from './routes/settings'
|
||||
import { createHealthRoutes } from './routes/health'
|
||||
import { createTTSRoutes, cleanupExpiredCache } from './routes/tts'
|
||||
@@ -46,6 +48,9 @@ app.use('/*', cors({
|
||||
|
||||
const db = initializeDatabase(DB_PATH)
|
||||
|
||||
let ipcServer: IPCServer | undefined
|
||||
const gitAuthService = new GitAuthService()
|
||||
|
||||
export const DEFAULT_AGENTS_MD = `# OpenCode Manager - Global Agent Instructions
|
||||
|
||||
## Critical System Constraints
|
||||
@@ -219,6 +224,10 @@ try {
|
||||
const settingsService = new SettingsService(db)
|
||||
settingsService.initializeLastKnownGoodConfig()
|
||||
|
||||
ipcServer = await createIPCServer(process.env.STORAGE_PATH || undefined)
|
||||
gitAuthService.initialize(ipcServer, db)
|
||||
logger.info(`Git IPC server running at ${ipcServer.ipcHandlePath}`)
|
||||
|
||||
opencodeServerManager.setDatabase(db)
|
||||
await opencodeServerManager.start()
|
||||
logger.info(`OpenCode server running on port ${opencodeServerManager.getPort()}`)
|
||||
@@ -226,7 +235,7 @@ try {
|
||||
logger.error('Failed to initialize workspace:', error)
|
||||
}
|
||||
|
||||
app.route('/api/repos', createRepoRoutes(db))
|
||||
app.route('/api/repos', createRepoRoutes(db, gitAuthService))
|
||||
app.route('/api/settings', createSettingsRoutes(db))
|
||||
app.route('/api/health', createHealthRoutes(db))
|
||||
app.route('/api/files', createFileRoutes())
|
||||
@@ -304,11 +313,15 @@ let isShuttingDown = false
|
||||
const shutdown = async (signal: string) => {
|
||||
if (isShuttingDown) return
|
||||
isShuttingDown = true
|
||||
|
||||
|
||||
logger.info(`${signal} received, shutting down gracefully...`)
|
||||
try {
|
||||
sseAggregator.shutdown()
|
||||
logger.info('SSE Aggregator stopped')
|
||||
if (ipcServer) {
|
||||
ipcServer.dispose()
|
||||
logger.info('Git IPC server stopped')
|
||||
}
|
||||
await opencodeServerManager.stop()
|
||||
logger.info('OpenCode server stopped')
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import * as path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import type { IPCServer, IPCHandler } from './ipcServer'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import type { GitCredential } from '../utils/git-auth'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
const __dirname = path.dirname(__filename)
|
||||
|
||||
interface Credentials {
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
interface AskpassRequest {
|
||||
askpassType: 'https' | 'ssh'
|
||||
argv: string[]
|
||||
}
|
||||
|
||||
export class AskpassHandler implements IPCHandler {
|
||||
private cache = new Map<string, Credentials>()
|
||||
private env: Record<string, string>
|
||||
|
||||
constructor(
|
||||
private ipcServer: IPCServer | undefined,
|
||||
private database: Database
|
||||
) {
|
||||
const scriptsDir = path.join(__dirname, '../../scripts')
|
||||
|
||||
this.env = {
|
||||
GIT_ASKPASS: path.join(scriptsDir, this.ipcServer ? 'askpass.sh' : 'askpass-empty.sh'),
|
||||
VSCODE_GIT_ASKPASS_NODE: process.execPath,
|
||||
VSCODE_GIT_ASKPASS_EXTRA_ARGS: '',
|
||||
VSCODE_GIT_ASKPASS_MAIN: path.join(scriptsDir, 'askpass-main.ts'),
|
||||
}
|
||||
|
||||
logger.info(`AskpassHandler initialized: execPath=${process.execPath}, GIT_ASKPASS=${this.env.GIT_ASKPASS}, VSCODE_GIT_ASKPASS_NODE=${this.env.VSCODE_GIT_ASKPASS_NODE}, VSCODE_GIT_ASKPASS_MAIN=${this.env.VSCODE_GIT_ASKPASS_MAIN}`)
|
||||
|
||||
if (this.ipcServer) {
|
||||
this.ipcServer.registerHandler('askpass', this)
|
||||
logger.info('AskpassHandler registered with IPC server')
|
||||
} else {
|
||||
logger.warn('AskpassHandler: No IPC server provided, using empty askpass')
|
||||
}
|
||||
}
|
||||
|
||||
async handle(request: AskpassRequest): Promise<string> {
|
||||
logger.info(`Askpass request received: type=${request.askpassType}, argv=${JSON.stringify(request.argv)}`)
|
||||
if (request.askpassType === 'https') {
|
||||
return this.handleHttpsAskpass(request.argv)
|
||||
}
|
||||
return this.handleSshAskpass()
|
||||
}
|
||||
|
||||
private async handleHttpsAskpass(argv: string[]): Promise<string> {
|
||||
const request = argv[2] || ''
|
||||
const host = argv[4]?.replace(/^["']+|["':]+$/g, '') || ''
|
||||
|
||||
let authority = ''
|
||||
try {
|
||||
const uri = new URL(host)
|
||||
authority = uri.hostname
|
||||
} catch {
|
||||
authority = host
|
||||
}
|
||||
|
||||
const isPassword = /password/i.test(request)
|
||||
|
||||
const cached = this.cache.get(authority)
|
||||
if (cached && isPassword) {
|
||||
this.cache.delete(authority)
|
||||
return cached.password
|
||||
}
|
||||
|
||||
const credentials = await this.getCredentialsForHost(authority)
|
||||
if (credentials) {
|
||||
this.cache.set(authority, credentials)
|
||||
setTimeout(() => this.cache.delete(authority), 60_000)
|
||||
return isPassword ? credentials.password : credentials.username
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
|
||||
private async handleSshAskpass(): Promise<string> {
|
||||
return ''
|
||||
}
|
||||
|
||||
private async getCredentialsForHost(hostname: string): Promise<Credentials | null> {
|
||||
logger.info(`Looking up credentials for host: ${hostname}`)
|
||||
const settingsService = new SettingsService(this.database)
|
||||
const settings = settingsService.getSettings('default')
|
||||
const gitCredentials: GitCredential[] = settings.preferences.gitCredentials || []
|
||||
logger.info(`Found ${gitCredentials.length} configured git credentials`)
|
||||
|
||||
for (const cred of gitCredentials) {
|
||||
try {
|
||||
const parsed = new URL(cred.host)
|
||||
if (parsed.hostname.toLowerCase() === hostname.toLowerCase()) {
|
||||
logger.info(`Found matching credential for ${hostname}`)
|
||||
return {
|
||||
username: cred.username || this.getDefaultUsername(cred.host),
|
||||
password: cred.token,
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
if (cred.host.toLowerCase().includes(hostname.toLowerCase())) {
|
||||
logger.info(`Found matching credential (fuzzy match) for ${hostname}`)
|
||||
return {
|
||||
username: cred.username || 'oauth2',
|
||||
password: cred.token,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.warn(`No credentials found for host: ${hostname}`)
|
||||
return null
|
||||
}
|
||||
|
||||
private getDefaultUsername(host: string): string {
|
||||
try {
|
||||
const parsed = new URL(host)
|
||||
const hostname = parsed.hostname.toLowerCase()
|
||||
|
||||
if (hostname === 'github.com') {
|
||||
return 'x-access-token'
|
||||
}
|
||||
if (hostname === 'gitlab.com' || hostname.includes('gitlab')) {
|
||||
return 'oauth2'
|
||||
}
|
||||
return 'oauth2'
|
||||
} catch {
|
||||
return 'oauth2'
|
||||
}
|
||||
}
|
||||
|
||||
getEnv(): Record<string, string> {
|
||||
return {
|
||||
...this.env,
|
||||
...(this.ipcServer?.getEnv() || {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import * as http from 'http'
|
||||
import * as crypto from 'crypto'
|
||||
import * as path from 'path'
|
||||
import * as os from 'os'
|
||||
import * as fs from 'fs/promises'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
function getIPCHandlePath(id: string): string {
|
||||
if (process.platform === 'win32') {
|
||||
return `\\\\.\\pipe\\opencode-git-${id}-sock`
|
||||
}
|
||||
if (process.platform !== 'darwin' && process.env['XDG_RUNTIME_DIR']) {
|
||||
return path.join(process.env['XDG_RUNTIME_DIR'], `opencode-git-${id}.sock`)
|
||||
}
|
||||
return path.join(os.tmpdir(), `opencode-git-${id}.sock`)
|
||||
}
|
||||
|
||||
export interface IPCHandler {
|
||||
handle(request: unknown): Promise<unknown>
|
||||
}
|
||||
|
||||
export class IPCServer {
|
||||
private handlers = new Map<string, IPCHandler>()
|
||||
|
||||
constructor(
|
||||
private server: http.Server,
|
||||
public readonly ipcHandlePath: string
|
||||
) {
|
||||
server.on('request', (req, res) => this.onRequest(req, res))
|
||||
}
|
||||
|
||||
registerHandler(name: string, handler: IPCHandler): void {
|
||||
this.handlers.set(`/${name}`, handler)
|
||||
}
|
||||
|
||||
getEnv(): Record<string, string> {
|
||||
return { VSCODE_GIT_IPC_HANDLE: this.ipcHandlePath }
|
||||
}
|
||||
|
||||
private onRequest(req: http.IncomingMessage, res: http.ServerResponse): void {
|
||||
logger.info(`IPC request received: url=${req.url}, method=${req.method}`)
|
||||
const handler = this.handlers.get(req.url || '')
|
||||
if (!handler) {
|
||||
logger.warn(`IPC handler not found for path: ${req.url}, registered paths: ${Array.from(this.handlers.keys()).join(', ')}`)
|
||||
res.writeHead(404)
|
||||
res.end(JSON.stringify({ error: 'Handler not found' }))
|
||||
return
|
||||
}
|
||||
|
||||
const chunks: Buffer[] = []
|
||||
req.on('data', (d: Buffer) => chunks.push(d))
|
||||
req.on('end', async () => {
|
||||
try {
|
||||
const body = Buffer.concat(chunks).toString('utf8')
|
||||
logger.info(`IPC request body: "${body}"`)
|
||||
if (!body) {
|
||||
logger.warn(`Empty request body for path: ${req.url}`)
|
||||
res.writeHead(400)
|
||||
res.end(JSON.stringify({ error: 'Empty request body' }))
|
||||
return
|
||||
}
|
||||
const request = JSON.parse(body)
|
||||
logger.info(`IPC calling handler for ${req.url} with:`, request)
|
||||
const result = await handler.handle(request)
|
||||
logger.info(`IPC handler result for ${req.url}:`, result)
|
||||
res.writeHead(200)
|
||||
res.end(JSON.stringify(result))
|
||||
} catch (error) {
|
||||
logger.error(`IPC request error for path ${req.url}:`, error)
|
||||
res.writeHead(500)
|
||||
res.end(JSON.stringify({ error: 'Internal server error' }))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.server.close()
|
||||
}
|
||||
}
|
||||
|
||||
export async function createIPCServer(context?: string): Promise<IPCServer> {
|
||||
const server = http.createServer()
|
||||
const hash = crypto.createHash('sha256')
|
||||
|
||||
if (!context) {
|
||||
const buffer = crypto.randomBytes(20)
|
||||
hash.update(buffer)
|
||||
} else {
|
||||
hash.update(context)
|
||||
}
|
||||
|
||||
const ipcHandlePath = getIPCHandlePath(hash.digest('hex').substring(0, 10))
|
||||
|
||||
if (process.platform !== 'win32') {
|
||||
try {
|
||||
await fs.unlink(ipcHandlePath)
|
||||
} catch {
|
||||
/* socket file may not exist */
|
||||
}
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
server.on('error', reject)
|
||||
server.listen(ipcHandlePath, () => {
|
||||
resolve(new IPCServer(server, ipcHandlePath))
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import * as db from '../db/queries'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { GitCommitService } from '../services/git/GitCommitService'
|
||||
import { GitPushService } from '../services/git/GitPushService'
|
||||
import { GitLogService } from '../services/git/GitLogService'
|
||||
import { GitStatusService } from '../services/git/GitStatusService'
|
||||
import { GitFetchPullService } from '../services/git/GitFetchPullService'
|
||||
import { GitBranchService } from '../services/git/GitBranchService'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import { GitDiffService } from '../services/git/GitDiffService'
|
||||
import type { GitStatusResponse } from '../types/git'
|
||||
|
||||
export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthService) {
|
||||
const app = new Hono()
|
||||
const gitDiffService = new GitDiffService(gitAuthService)
|
||||
const gitFetchPullService = new GitFetchPullService(gitAuthService)
|
||||
const gitBranchService = new GitBranchService(gitAuthService)
|
||||
const gitCommitService = new GitCommitService(gitAuthService)
|
||||
const gitPushService = new GitPushService(gitAuthService)
|
||||
const gitLogService = new GitLogService(gitAuthService, gitDiffService)
|
||||
const gitStatusService = new GitStatusService(gitAuthService)
|
||||
|
||||
app.get('/:id/git/status', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const status = await gitStatusService.getStatus(id, database)
|
||||
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get git status:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/git-status-batch', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
const { repoIds } = body
|
||||
|
||||
if (!Array.isArray(repoIds) || repoIds.some((id: unknown) => typeof id !== 'number')) {
|
||||
return c.json({ error: 'repoIds must be an array of numbers' }, 400)
|
||||
}
|
||||
|
||||
const statuses = await Promise.all(
|
||||
repoIds.map(async (id) => {
|
||||
try {
|
||||
const status = await gitStatusService.getStatus(id, database)
|
||||
return [id, status]
|
||||
} catch (error: unknown) {
|
||||
logger.error(`Failed to get git status for repo ${id}:`, error)
|
||||
return null
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
const resultMap: Record<number, GitStatusResponse> = {}
|
||||
for (const entry of statuses) {
|
||||
if (entry) {
|
||||
const [id, status] = entry
|
||||
resultMap[id] = status
|
||||
}
|
||||
}
|
||||
|
||||
return c.json(resultMap)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get batch git status:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/git/diff', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const filePath = c.req.query('path')
|
||||
|
||||
if (!filePath) {
|
||||
return c.json({ error: 'path query parameter is required' }, 400)
|
||||
}
|
||||
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const diff = await gitLogService.getDiff(id, filePath, database)
|
||||
|
||||
return c.json(diff)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get file diff:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
// Add new endpoint for full diff details
|
||||
app.get('/:id/git/diff-full', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const filePath = c.req.query('path')
|
||||
const includeStaged = c.req.query('includeStaged') === 'true'
|
||||
|
||||
if (!filePath) {
|
||||
return c.json({ error: 'path query parameter is required' }, 400)
|
||||
}
|
||||
|
||||
const repo = db.getRepoById(database, id)
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const diffResponse = await gitLogService.getFullDiff(id, filePath, database, includeStaged)
|
||||
return c.json(diffResponse)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get full file diff:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/git/fetch', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
await gitFetchPullService.fetch(id, database)
|
||||
|
||||
const status = await gitStatusService.getStatus(id, database)
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to fetch git:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/git/pull', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
await gitFetchPullService.pull(id, database)
|
||||
|
||||
const status = await gitStatusService.getStatus(id, database)
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to pull git:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/git/commit', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const body = await c.req.json()
|
||||
const { message, stagedPaths } = body
|
||||
|
||||
if (!message) {
|
||||
return c.json({ error: 'message is required' }, 400)
|
||||
}
|
||||
|
||||
await gitCommitService.commit(id, message, database, stagedPaths)
|
||||
|
||||
const status = await gitStatusService.getStatus(id, database)
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to commit git:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/git/push', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const body = await c.req.json()
|
||||
const { setUpstream } = body
|
||||
|
||||
await gitPushService.push(id, { setUpstream: setUpstream || false }, database)
|
||||
|
||||
const status = await gitStatusService.getStatus(id, database)
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to push git:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/git/stage', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const body = await c.req.json()
|
||||
const { paths } = body
|
||||
|
||||
if (!paths || !Array.isArray(paths)) {
|
||||
return c.json({ error: 'paths is required and must be an array' }, 400)
|
||||
}
|
||||
|
||||
await gitCommitService.stageFiles(id, paths, database)
|
||||
|
||||
const status = await gitStatusService.getStatus(id, database)
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to stage files:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/git/unstage', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const body = await c.req.json()
|
||||
const { paths } = body
|
||||
|
||||
if (!paths || !Array.isArray(paths)) {
|
||||
return c.json({ error: 'paths is required and must be an array' }, 400)
|
||||
}
|
||||
|
||||
await gitCommitService.unstageFiles(id, paths, database)
|
||||
|
||||
const status = await gitStatusService.getStatus(id, database)
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to unstage files:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/git/log', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const limit = parseInt(c.req.query('limit') || '10', 10)
|
||||
const commits = await gitLogService.getLog(id, database, limit)
|
||||
|
||||
return c.json({ commits })
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get git log:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/git/reset', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const body = await c.req.json()
|
||||
const { commitHash } = body
|
||||
|
||||
if (!commitHash) {
|
||||
return c.json({ error: 'commitHash is required' }, 400)
|
||||
}
|
||||
|
||||
await gitCommitService.resetToCommit(id, commitHash, database)
|
||||
|
||||
const status = await gitStatusService.getStatus(id, database)
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to reset to commit:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/git/branches', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const branches = await gitBranchService.getBranches(id, database)
|
||||
const status = await gitBranchService.getBranchStatus(id, database)
|
||||
|
||||
return c.json({ branches, status })
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get branches:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
+15
-81
@@ -3,8 +3,6 @@ import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import * as db from '../db/queries'
|
||||
import * as repoService from '../services/repo'
|
||||
import { GitAuthenticationError } from '../services/repo'
|
||||
import * as gitOperations from '../services/git-operations'
|
||||
import * as archiveService from '../services/archive'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { writeFileContent } from '../services/file-operations'
|
||||
@@ -13,11 +11,15 @@ import { proxyToOpenCodeWithDirectory } from '../services/proxy'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
|
||||
import { getOpenCodeConfigFilePath, getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import { createRepoGitRoutes } from './repo-git'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import path from 'path'
|
||||
|
||||
export function createRepoRoutes(database: Database) {
|
||||
export function createRepoRoutes(database: Database, gitAuthService: GitAuthService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.route('/', createRepoGitRoutes(database, gitAuthService))
|
||||
|
||||
app.post('/', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
@@ -33,12 +35,14 @@ export function createRepoRoutes(database: Database) {
|
||||
if (localPath) {
|
||||
repo = await repoService.initLocalRepo(
|
||||
database,
|
||||
gitAuthService,
|
||||
localPath,
|
||||
branch
|
||||
)
|
||||
} else {
|
||||
repo = await repoService.cloneRepo(
|
||||
database,
|
||||
gitAuthService,
|
||||
repoUrl!,
|
||||
branch,
|
||||
useWorktree
|
||||
@@ -72,7 +76,8 @@ app.get('/', async (c) => {
|
||||
|
||||
const reposWithCurrentBranch = await Promise.all(
|
||||
repos.map(async (repo) => {
|
||||
const currentBranch = await repoService.getCurrentBranch(repo)
|
||||
const env = gitAuthService.getGitEnvironment()
|
||||
const currentBranch = await repoService.getCurrentBranch(repo, env)
|
||||
return { ...repo, currentBranch }
|
||||
})
|
||||
)
|
||||
@@ -112,7 +117,7 @@ app.get('/', async (c) => {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const currentBranch = await repoService.getCurrentBranch(repo)
|
||||
const currentBranch = await repoService.getCurrentBranch(repo, gitAuthService.getGitEnvironment())
|
||||
|
||||
return c.json({ ...repo, currentBranch })
|
||||
} catch (error: unknown) {
|
||||
@@ -142,7 +147,7 @@ app.get('/', async (c) => {
|
||||
app.post('/:id/pull', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
await repoService.pullRepo(database, id)
|
||||
await repoService.pullRepo(database, gitAuthService, id)
|
||||
|
||||
const repo = db.getRepoById(database, id)
|
||||
return c.json(repo)
|
||||
@@ -212,17 +217,14 @@ app.get('/', async (c) => {
|
||||
return c.json({ error: 'branch is required' }, 400)
|
||||
}
|
||||
|
||||
await repoService.switchBranch(database, id, branch)
|
||||
await repoService.switchBranch(database, gitAuthService, id, branch)
|
||||
|
||||
const updatedRepo = db.getRepoById(database, id)
|
||||
const currentBranch = await repoService.getCurrentBranch(updatedRepo!)
|
||||
const currentBranch = await repoService.getCurrentBranch(updatedRepo!, gitAuthService.getGitEnvironment())
|
||||
|
||||
return c.json({ ...updatedRepo, currentBranch })
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to switch branch:', error)
|
||||
if (error instanceof GitAuthenticationError) {
|
||||
return c.json({ error: error.message, code: 'AUTH_FAILED' }, 401)
|
||||
}
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
@@ -243,82 +245,14 @@ app.get('/', async (c) => {
|
||||
return c.json({ error: 'branch is required' }, 400)
|
||||
}
|
||||
|
||||
await repoService.createBranch(database, id, branch)
|
||||
await repoService.createBranch(database, gitAuthService, id, branch)
|
||||
|
||||
const updatedRepo = db.getRepoById(database, id)
|
||||
const currentBranch = await repoService.getCurrentBranch(updatedRepo!)
|
||||
const currentBranch = await repoService.getCurrentBranch(updatedRepo!, gitAuthService.getGitEnvironment())
|
||||
|
||||
return c.json({ ...updatedRepo, currentBranch })
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to create branch:', error)
|
||||
if (error instanceof GitAuthenticationError) {
|
||||
return c.json({ error: error.message, code: 'AUTH_FAILED' }, 401)
|
||||
}
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/branches', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const branches = await repoService.listBranches(database, repo)
|
||||
|
||||
|
||||
return c.json(branches)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to list branches:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/git/status', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const repoPath = path.resolve(getReposPath(), repo.localPath)
|
||||
const status = await gitOperations.getGitStatus(repoPath, database)
|
||||
|
||||
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get git status:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/git/diff', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const filePath = c.req.query('path')
|
||||
|
||||
if (!filePath) {
|
||||
return c.json({ error: 'path query parameter is required' }, 400)
|
||||
}
|
||||
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const repoPath = path.resolve(getReposPath(), repo.localPath)
|
||||
const diff = await gitOperations.getFileDiff(repoPath, filePath, database)
|
||||
|
||||
|
||||
return c.json(diff)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get file diff:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -61,6 +61,7 @@ const ConnectMcpDirectorySchema = z.object({
|
||||
directory: z.string().min(1),
|
||||
})
|
||||
|
||||
|
||||
async function extractOpenCodeError(response: Response, defaultError: string): Promise<string> {
|
||||
const errorObj = await response.json().catch(() => null)
|
||||
return (errorObj && typeof errorObj === 'object' && 'error' in errorObj)
|
||||
|
||||
@@ -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}`)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 })
|
||||
}
|
||||
}
|
||||
@@ -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'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
export type GitFileStatusType = 'modified' | 'added' | 'deleted' | 'renamed' | 'untracked' | 'copied'
|
||||
|
||||
export interface GitFileStatus {
|
||||
path: string
|
||||
status: GitFileStatusType
|
||||
staged: boolean
|
||||
oldPath?: string
|
||||
}
|
||||
|
||||
export interface GitCommit {
|
||||
hash: string
|
||||
authorName: string
|
||||
authorEmail: string
|
||||
date: string
|
||||
message: string
|
||||
unpushed?: boolean
|
||||
}
|
||||
|
||||
export interface GitStatusResponse {
|
||||
branch: string
|
||||
ahead: number
|
||||
behind: number
|
||||
files: GitFileStatus[]
|
||||
hasChanges: boolean
|
||||
}
|
||||
|
||||
export interface FileDiffResponse {
|
||||
path: string
|
||||
status: GitFileStatusType
|
||||
diff: string
|
||||
additions: number
|
||||
deletions: number
|
||||
isBinary: boolean
|
||||
}
|
||||
|
||||
export interface GitDiffOptions {
|
||||
showContext?: number
|
||||
ignoreWhitespace?: boolean
|
||||
unified?: boolean
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
export function isError(error: unknown): error is Error {
|
||||
function isError(error: unknown): error is Error {
|
||||
return error instanceof Error
|
||||
}
|
||||
|
||||
@@ -9,12 +9,6 @@ export function getErrorMessage(error: unknown): string {
|
||||
return String(error)
|
||||
}
|
||||
|
||||
export function getErrorStack(error: unknown): string | undefined {
|
||||
if (isError(error)) {
|
||||
return error.stack
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
interface ErrorWithStatusCode {
|
||||
statusCode?: number
|
||||
|
||||
@@ -14,17 +14,11 @@ export function isGitHubHttpsUrl(repoUrl: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
export function createNoPromptGitEnv(): Record<string, string> {
|
||||
return {
|
||||
GIT_TERMINAL_PROMPT: '0'
|
||||
}
|
||||
}
|
||||
|
||||
function getDefaultUsername(host: string): string {
|
||||
export function getDefaultUsername(host: string): string {
|
||||
try {
|
||||
const parsed = new URL(host)
|
||||
const hostname = parsed.hostname.toLowerCase()
|
||||
|
||||
|
||||
if (hostname === 'github.com') {
|
||||
return 'x-access-token'
|
||||
}
|
||||
@@ -37,7 +31,7 @@ function getDefaultUsername(host: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHost(host: string): string {
|
||||
export function normalizeHost(host: string): string {
|
||||
if (!host.endsWith('/')) {
|
||||
return `${host}/`
|
||||
}
|
||||
@@ -45,8 +39,11 @@ function normalizeHost(host: string): string {
|
||||
}
|
||||
|
||||
export function createGitEnv(credentials: GitCredential[]): Record<string, string> {
|
||||
const env: Record<string, string> = { GIT_TERMINAL_PROMPT: '0' }
|
||||
|
||||
const env: Record<string, string> = {
|
||||
GIT_TERMINAL_PROMPT: '0',
|
||||
GIT_CONFIG_COUNT: '0'
|
||||
}
|
||||
|
||||
if (!credentials || credentials.length === 0) {
|
||||
return env
|
||||
}
|
||||
@@ -67,9 +64,7 @@ export function createGitEnv(credentials: GitCredential[]): Record<string, strin
|
||||
configIndex++
|
||||
}
|
||||
|
||||
if (configIndex > 0) {
|
||||
env.GIT_CONFIG_COUNT = String(configIndex)
|
||||
}
|
||||
env.GIT_CONFIG_COUNT = String(configIndex)
|
||||
|
||||
return env
|
||||
}
|
||||
@@ -78,15 +73,9 @@ export function createGitHubGitEnv(gitToken: string): Record<string, string> {
|
||||
return createGitEnv([{ name: 'GitHub', host: 'https://github.com/', token: gitToken }])
|
||||
}
|
||||
|
||||
export interface GitHubUserInfo {
|
||||
name: string | null
|
||||
email: string
|
||||
login: string
|
||||
}
|
||||
|
||||
export function findGitHubCredential(credentials: GitCredential[]): GitCredential | null {
|
||||
if (!credentials || credentials.length === 0) return null
|
||||
|
||||
|
||||
return credentials.find(cred => {
|
||||
try {
|
||||
const parsed = new URL(cred.host)
|
||||
@@ -97,6 +86,23 @@ export function findGitHubCredential(credentials: GitCredential[]): GitCredentia
|
||||
}) || null
|
||||
}
|
||||
|
||||
export function getCredentialForHost(credentials: GitCredential[], host: string): GitCredential | undefined {
|
||||
return credentials.find(cred => {
|
||||
try {
|
||||
const parsed = new URL(cred.host)
|
||||
return parsed.hostname.toLowerCase() === host.toLowerCase()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export interface GitHubUserInfo {
|
||||
name: string | null
|
||||
email: string
|
||||
login: string
|
||||
}
|
||||
|
||||
export interface GitIdentity {
|
||||
name: string
|
||||
email: string
|
||||
|
||||
@@ -5,12 +5,21 @@ interface ExecuteCommandOptions {
|
||||
cwd?: string
|
||||
silent?: boolean
|
||||
env?: Record<string, string>
|
||||
ignoreExitCode?: boolean
|
||||
}
|
||||
|
||||
export async function executeCommand(
|
||||
args: string[],
|
||||
cwdOrOptions?: string | ExecuteCommandOptions
|
||||
): Promise<string> {
|
||||
): Promise<string>
|
||||
export async function executeCommand(
|
||||
args: string[],
|
||||
cwdOrOptions: string | (ExecuteCommandOptions & { ignoreExitCode: true })
|
||||
): Promise<string | { exitCode: number; stdout: string; stderr: string }>
|
||||
export async function executeCommand(
|
||||
args: string[],
|
||||
cwdOrOptions?: string | ExecuteCommandOptions
|
||||
): Promise<string | { exitCode: number; stdout: string; stderr: string }> {
|
||||
const options: ExecuteCommandOptions = typeof cwdOrOptions === 'string'
|
||||
? { cwd: cwdOrOptions }
|
||||
: cwdOrOptions || {}
|
||||
@@ -18,10 +27,20 @@ export async function executeCommand(
|
||||
return new Promise((resolve, reject) => {
|
||||
const [command, ...cmdArgs] = args
|
||||
|
||||
const effectiveEnv = { ...process.env, ...options.env }
|
||||
|
||||
// Log key git-related environment variables
|
||||
if (command === 'git') {
|
||||
logger.info(`executeCommand: ${args.join(' ')}`)
|
||||
logger.info(` GIT_ASKPASS: ${effectiveEnv.GIT_ASKPASS || '(not set)'}`)
|
||||
logger.info(` VSCODE_GIT_IPC_HANDLE: ${effectiveEnv.VSCODE_GIT_IPC_HANDLE || '(not set)'}`)
|
||||
logger.info(` GIT_TERMINAL_PROMPT: ${effectiveEnv.GIT_TERMINAL_PROMPT || '(not set)'}`)
|
||||
}
|
||||
|
||||
const proc: ChildProcess = spawn(command || '', cmdArgs, {
|
||||
cwd: options.cwd,
|
||||
shell: false,
|
||||
env: { ...process.env, ...options.env }
|
||||
env: effectiveEnv
|
||||
})
|
||||
|
||||
let stdout = ''
|
||||
@@ -43,7 +62,9 @@ export async function executeCommand(
|
||||
})
|
||||
|
||||
proc.on('close', (code: number | null) => {
|
||||
if (code === 0) {
|
||||
if (options.ignoreExitCode) {
|
||||
resolve({ exitCode: code || 0, stdout, stderr })
|
||||
} else if (code === 0) {
|
||||
resolve(stdout)
|
||||
} else {
|
||||
const error = new Error(`Command failed with code ${code}: ${stderr || stdout}`)
|
||||
|
||||
Vendored
-46
@@ -1,46 +0,0 @@
|
||||
import { mkdir, writeFile, rm } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { executeCommand } from '../../src/utils/process'
|
||||
|
||||
export function gitReuseDir(name: string): string {
|
||||
const base = process.env.TMPDIR || '/tmp'
|
||||
return join(base, `opencode-test-${name}`)
|
||||
}
|
||||
|
||||
export async function setupGitTestRepo(repoPath: string): Promise<void> {
|
||||
try {
|
||||
await rm(repoPath, { recursive: true, force: true })
|
||||
} catch {
|
||||
// Ignore if dir doesn't exist
|
||||
}
|
||||
|
||||
await mkdir(repoPath, { recursive: true })
|
||||
await executeCommand(['git', 'init'], { cwd: repoPath })
|
||||
await executeCommand(['git', 'config', 'user.name', 'Test User'], { cwd: repoPath })
|
||||
await executeCommand(['git', 'config', 'user.email', 'test@example.com'], { cwd: repoPath })
|
||||
await executeCommand(['git', 'config', 'commit.gpgSign', 'false'], { cwd: repoPath })
|
||||
}
|
||||
|
||||
export async function cleanupTestRepo(repoPath: string): Promise<void> {
|
||||
try {
|
||||
await rm(repoPath, { recursive: true, force: true })
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
export async function createTestFile(repoPath: string, fileName: string, content: string): Promise<void> {
|
||||
const filePath = join(repoPath, fileName)
|
||||
const dir = join(repoPath, fileName.split('/').slice(0, -1).join('/'))
|
||||
|
||||
if (dir !== repoPath) {
|
||||
await mkdir(dir, { recursive: true })
|
||||
}
|
||||
|
||||
await writeFile(filePath, content, 'utf-8')
|
||||
}
|
||||
|
||||
export async function stageAndCommitTestFile(repoPath: string, fileName: string): Promise<void> {
|
||||
await executeCommand(['git', 'add', fileName], { cwd: repoPath })
|
||||
await executeCommand(['git', 'commit', '-m', `Add ${fileName}`], { cwd: repoPath })
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
import { describe, it, expect, vi, beforeEach, type MockedFunction } from 'vitest'
|
||||
import { createRepoRoutes } from '../../src/routes/repos'
|
||||
import type { Hono } from 'hono'
|
||||
import { getRepoById } from '../../src/db/queries'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo } from '../../../shared/src/types'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/db/queries', () => ({
|
||||
getRepoById: vi.fn(),
|
||||
}))
|
||||
|
||||
const getRepoByIdMock = getRepoById as MockedFunction<typeof getRepoById>
|
||||
|
||||
const createMockRepo = (overrides: Partial<Repo> = {}): Repo => ({
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
fullPath: '/nonexistent/path',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
...overrides,
|
||||
} as Repo)
|
||||
|
||||
describe('Git Routes', () => {
|
||||
let app: Hono
|
||||
let mockDatabase: Database
|
||||
let mockGitAuthService: GitAuthService
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockDatabase = {
|
||||
run: vi.fn(),
|
||||
prepare: vi.fn(() => ({
|
||||
run: vi.fn(),
|
||||
get: vi.fn(),
|
||||
all: vi.fn(),
|
||||
iterate: vi.fn(),
|
||||
values: vi.fn(),
|
||||
})),
|
||||
exec: vi.fn(),
|
||||
query: vi.fn(),
|
||||
inTransaction: vi.fn(),
|
||||
close: vi.fn(),
|
||||
} as unknown as Database
|
||||
mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue({}),
|
||||
} as unknown as GitAuthService
|
||||
app = createRepoRoutes(mockDatabase, mockGitAuthService)
|
||||
})
|
||||
|
||||
describe('GET /:id/git/status', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/999/git/status')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails for non-existent path', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/status')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:id/git/fetch', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/999/git/fetch', { method: 'POST' })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/fetch', { method: 'POST' })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:id/git/pull', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/999/git/pull', { method: 'POST' })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/pull', { method: 'POST' })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:id/git/push', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/999/git/push', { method: 'POST' })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should accept setUpstream parameter', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/push', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ setUpstream: true }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('should work without setUpstream parameter', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/push', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/push', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:id/git/commit', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/999/git/commit', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: 'Test' }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should return 400 when message is missing', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/commit', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'message is required')
|
||||
})
|
||||
|
||||
it('should accept message and stagedPaths', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/commit', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: 'Test commit', stagedPaths: ['file1.ts'] }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/commit', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: 'Test' }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:id/git/stage', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/999/git/stage', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths: ['file1.ts'] }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should return 400 when paths is not an array', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/stage', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths: 'not-an-array' }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'paths is required and must be an array')
|
||||
})
|
||||
|
||||
it('should return 400 when paths is missing', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/stage', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'paths is required and must be an array')
|
||||
})
|
||||
|
||||
it('should accept array of paths', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/stage', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths: ['file1.ts', 'file2.ts'] }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/stage', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths: ['file1.ts'] }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:id/git/unstage', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/999/git/unstage', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths: ['file1.ts'] }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should return 400 when paths is not an array', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/unstage', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths: 'not-an-array' }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'paths is required and must be an array')
|
||||
})
|
||||
|
||||
it('should return 400 when paths is missing', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/unstage', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'paths is required and must be an array')
|
||||
})
|
||||
|
||||
it('should accept array of paths', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/unstage', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths: ['file1.ts', 'file2.ts'] }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/unstage', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths: ['file1.ts'] }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /:id/git/log', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/999/git/log')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should use default limit when not provided', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/log')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('should use custom limit when provided', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/log?limit=5')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/log')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /:id/git/diff', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/999/git/diff?path=file.ts')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should return 400 when path parameter is missing', async () => {
|
||||
const response = await app.request('/1/git/diff')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'path query parameter is required')
|
||||
})
|
||||
|
||||
it('should accept path parameter', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/diff?path=file.ts')
|
||||
await response.text()
|
||||
|
||||
expect([200, 500]).toContain(response.status)
|
||||
})
|
||||
|
||||
it('should handle special characters in path', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/diff?path=src%2Fcomponents%2FButton.tsx')
|
||||
expect([200, 500]).toContain(response.status)
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/diff?path=file.ts')
|
||||
expect([200, 500]).toContain(response.status)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:id/git/reset', () => {
|
||||
it('should return 404 when repo does not exist', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
const response = await app.request('/999/git/reset', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ commitHash: 'abc123' }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error', 'Repo not found')
|
||||
})
|
||||
|
||||
it('should return 400 when commitHash is missing', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/reset', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error', 'commitHash is required')
|
||||
})
|
||||
|
||||
it('should accept commitHash parameter', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/reset', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ commitHash: 'abc123' }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('should return 500 when git operation fails', async () => {
|
||||
getRepoByIdMock.mockReturnValue(createMockRepo())
|
||||
const response = await app.request('/1/git/reset', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ commitHash: 'abc123' }),
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,369 @@
|
||||
import { describe, it, expect, vi, beforeEach, type MockedFunction } from 'vitest'
|
||||
import { createSettingsRoutes } from '../../src/routes/settings'
|
||||
import type { Hono } from 'hono'
|
||||
import { spawn } from 'child_process'
|
||||
import { mkdir, rm } from 'fs/promises'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
|
||||
const mockSettingsService = {
|
||||
getSettings: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
resetSettings: vi.fn(),
|
||||
getOpenCodeConfigs: vi.fn(),
|
||||
createOpenCodeConfig: vi.fn(),
|
||||
updateOpenCodeConfig: vi.fn(),
|
||||
deleteOpenCodeConfig: vi.fn(),
|
||||
setDefaultOpenCodeConfig: vi.fn(),
|
||||
getDefaultOpenCodeConfig: vi.fn(),
|
||||
saveLastKnownGoodConfig: vi.fn(),
|
||||
rollbackToLastKnownGoodHealth: vi.fn(),
|
||||
deleteFilesystemConfig: vi.fn(),
|
||||
}
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn(() => ({
|
||||
run: vi.fn(),
|
||||
prepare: vi.fn(() => ({
|
||||
run: vi.fn()
|
||||
}))
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn().mockImplementation(() => mockSettingsService),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: {
|
||||
getVersion: vi.fn(),
|
||||
fetchVersion: vi.fn(),
|
||||
clearStartupError: vi.fn(),
|
||||
restart: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('child_process', () => ({
|
||||
spawn: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('fs/promises', () => ({
|
||||
mkdir: vi.fn(),
|
||||
rm: vi.fn(),
|
||||
}))
|
||||
|
||||
const spawnMock = spawn as MockedFunction<typeof spawn>
|
||||
const mkdirMock = mkdir as MockedFunction<typeof mkdir>
|
||||
const rmMock = rm as MockedFunction<typeof rm>
|
||||
|
||||
describe('Settings Routes', () => {
|
||||
let app: Hono
|
||||
let mockDatabase: Database
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockDatabase = {
|
||||
run: vi.fn(),
|
||||
prepare: vi.fn(() => ({
|
||||
run: vi.fn()
|
||||
}))
|
||||
} as Database
|
||||
Object.keys(mockSettingsService).forEach(key => {
|
||||
mockSettingsService[key as keyof typeof mockSettingsService].mockClear()
|
||||
})
|
||||
app = createSettingsRoutes(mockDatabase)
|
||||
})
|
||||
|
||||
describe('POST /test-credential', () => {
|
||||
const validCredential = {
|
||||
name: 'test-cred',
|
||||
host: 'github.com',
|
||||
token: 'ghp_test_token_123',
|
||||
}
|
||||
|
||||
it('should return 400 for invalid request body', async () => {
|
||||
const response = await app.request('/test-credential', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ invalid: 'data' }),
|
||||
})
|
||||
const body = await response.json() as any
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error')
|
||||
expect(body).toHaveProperty('details')
|
||||
})
|
||||
|
||||
it('should return 400 for missing required fields', async () => {
|
||||
const response = await app.request('/test-credential', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'test' }),
|
||||
})
|
||||
const body = await response.json() as any
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error')
|
||||
expect(body).toHaveProperty('details')
|
||||
})
|
||||
|
||||
it('should return 400 for empty strings', async () => {
|
||||
const response = await app.request('/test-credential', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: '', host: '', token: '' }),
|
||||
})
|
||||
const body = await response.json() as any
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('error')
|
||||
expect(body).toHaveProperty('details')
|
||||
})
|
||||
|
||||
it('should handle GitHub.com authentication successfully', async () => {
|
||||
spawnMock.mockReturnValue({
|
||||
on: vi.fn().mockImplementation((event, callback) => {
|
||||
if (event === 'close') callback(0)
|
||||
}),
|
||||
stderr: {
|
||||
on: vi.fn(),
|
||||
},
|
||||
} as any)
|
||||
|
||||
mkdirMock.mockResolvedValueOnce(undefined)
|
||||
rmMock.mockResolvedValueOnce(undefined)
|
||||
|
||||
const response = await app.request('/test-credential', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(validCredential),
|
||||
})
|
||||
const body = await response.json() as any
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('success', true)
|
||||
expect(body).toHaveProperty('maskedToken')
|
||||
expect(body.maskedToken).toBe('ghp_test...')
|
||||
})
|
||||
|
||||
it('should handle GitLab.com authentication with default username', async () => {
|
||||
spawnMock.mockReturnValue({
|
||||
on: vi.fn().mockImplementation((event, callback) => {
|
||||
if (event === 'close') callback(0)
|
||||
}),
|
||||
stderr: {
|
||||
on: vi.fn(),
|
||||
},
|
||||
} as any)
|
||||
|
||||
mkdirMock.mockResolvedValueOnce(undefined)
|
||||
rmMock.mockResolvedValueOnce(undefined)
|
||||
|
||||
const response = await app.request('/test-credential', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...validCredential,
|
||||
host: 'gitlab.com',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as any
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('success', true)
|
||||
expect(body).toHaveProperty('maskedToken')
|
||||
})
|
||||
|
||||
it('should handle custom username', async () => {
|
||||
spawnMock.mockReturnValue({
|
||||
on: vi.fn().mockImplementation((event, callback) => {
|
||||
if (event === 'close') callback(0)
|
||||
}),
|
||||
stderr: {
|
||||
on: vi.fn(),
|
||||
},
|
||||
} as any)
|
||||
|
||||
mkdirMock.mockResolvedValueOnce(undefined)
|
||||
rmMock.mockResolvedValueOnce(undefined)
|
||||
|
||||
const response = await app.request('/test-credential', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...validCredential,
|
||||
username: 'custom-user',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as any
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('success', true)
|
||||
})
|
||||
|
||||
it('should return 400 when git authentication fails', async () => {
|
||||
spawnMock.mockReturnValue({
|
||||
on: vi.fn().mockImplementation((event, callback) => {
|
||||
if (event === 'close') callback(128) // Git auth failure exit code
|
||||
}),
|
||||
stderr: {
|
||||
on: vi.fn().mockImplementation((event, callback) => {
|
||||
callback('Authentication failed for repository')
|
||||
}),
|
||||
},
|
||||
} as any)
|
||||
|
||||
mkdirMock.mockResolvedValueOnce(undefined)
|
||||
rmMock.mockResolvedValueOnce(undefined)
|
||||
|
||||
const response = await app.request('/test-credential', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(validCredential),
|
||||
})
|
||||
const body = await response.json() as any
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('success', false)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('should return 500 when git process throws error', async () => {
|
||||
spawnMock.mockImplementation(() => {
|
||||
throw new Error('Spawn failed')
|
||||
})
|
||||
|
||||
mkdirMock.mockResolvedValueOnce(undefined)
|
||||
|
||||
const response = await app.request('/test-credential', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(validCredential),
|
||||
})
|
||||
const body = await response.json() as any
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('success', false)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('should handle hosts with trailing slashes', async () => {
|
||||
spawnMock.mockReturnValue({
|
||||
on: vi.fn().mockImplementation((event, callback) => {
|
||||
if (event === 'close') callback(0)
|
||||
}),
|
||||
stderr: {
|
||||
on: vi.fn(),
|
||||
},
|
||||
} as any)
|
||||
|
||||
mkdirMock.mockResolvedValueOnce(undefined)
|
||||
rmMock.mockResolvedValueOnce(undefined)
|
||||
|
||||
const response = await app.request('/test-credential', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...validCredential,
|
||||
host: 'github.com/',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as any
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('success', true)
|
||||
})
|
||||
|
||||
it('should handle invalid URLs gracefully', async () => {
|
||||
spawnMock.mockReturnValue({
|
||||
on: vi.fn().mockImplementation((event, callback) => {
|
||||
if (event === 'close') callback(0)
|
||||
}),
|
||||
stderr: {
|
||||
on: vi.fn(),
|
||||
},
|
||||
} as any)
|
||||
|
||||
mkdirMock.mockResolvedValueOnce(undefined)
|
||||
rmMock.mockResolvedValueOnce(undefined)
|
||||
|
||||
const response = await app.request('/test-credential', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...validCredential,
|
||||
host: 'not-a-valid-url',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as any
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('success', true)
|
||||
})
|
||||
|
||||
it('should mask tokens correctly', async () => {
|
||||
spawnMock.mockReturnValue({
|
||||
on: vi.fn().mockImplementation((event, callback) => {
|
||||
if (event === 'close') callback(0)
|
||||
}),
|
||||
stderr: {
|
||||
on: vi.fn(),
|
||||
},
|
||||
} as any)
|
||||
|
||||
mkdirMock.mockResolvedValueOnce(undefined)
|
||||
rmMock.mockResolvedValueOnce(undefined)
|
||||
|
||||
const response = await app.request('/test-credential', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...validCredential,
|
||||
token: 'ghp_very_long_token_that_should_be_masked_properly',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as any
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('success', true)
|
||||
expect(body.maskedToken).toBe('ghp_very...')
|
||||
})
|
||||
|
||||
it('should handle very short tokens', async () => {
|
||||
spawnMock.mockReturnValue({
|
||||
on: vi.fn().mockImplementation((event, callback) => {
|
||||
if (event === 'close') callback(0)
|
||||
}),
|
||||
stderr: {
|
||||
on: vi.fn(),
|
||||
},
|
||||
} as any)
|
||||
|
||||
mkdirMock.mockResolvedValueOnce(undefined)
|
||||
rmMock.mockResolvedValueOnce(undefined)
|
||||
|
||||
const response = await app.request('/test-credential', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...validCredential,
|
||||
token: 'short',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as any
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('success', true)
|
||||
expect(body.maskedToken).toBe('*******')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,77 +0,0 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { gitReuseDir, setupGitTestRepo, cleanupTestRepo, createTestFile, stageAndCommitTestFile } from '../fixtures/git-helpers'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn()
|
||||
}))
|
||||
|
||||
import { getFileDiff } from '../../src/services/git-operations'
|
||||
|
||||
const testRepoPath = gitReuseDir('git-operations-test')
|
||||
|
||||
describe('getFileDiff', () => {
|
||||
beforeAll(async () => {
|
||||
await setupGitTestRepo(testRepoPath)
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanupTestRepo(testRepoPath)
|
||||
})
|
||||
|
||||
describe('untracked file diff', () => {
|
||||
it('should extract diff from git --no-index output when exit code 1', async () => {
|
||||
const fileName = 'new-file.txt'
|
||||
const content = 'First line\nSecond line\nThird line\n'
|
||||
await createTestFile(testRepoPath, fileName, content)
|
||||
|
||||
const result = await getFileDiff(testRepoPath, fileName)
|
||||
|
||||
expect(result.status).toBe('untracked')
|
||||
expect(result.diff).toBeTruthy()
|
||||
expect(result.diff).toContain('diff --git')
|
||||
expect(result.diff).toContain(`a/${fileName}`)
|
||||
expect(result.diff).toContain(`b/${fileName}`)
|
||||
expect(result.additions).toBe(3)
|
||||
expect(result.deletions).toBe(0)
|
||||
expect(result.isBinary).toBe(false)
|
||||
})
|
||||
|
||||
it('should handle new file with multiple additions', async () => {
|
||||
const fileName = 'new-code-file.js'
|
||||
const content = 'function hello() {\n console.log("Hello world");\n return true;\n}\n'
|
||||
await createTestFile(testRepoPath, fileName, content)
|
||||
|
||||
const result = await getFileDiff(testRepoPath, fileName)
|
||||
|
||||
expect(result.status).toBe('untracked')
|
||||
expect(result.additions).toBeGreaterThan(0)
|
||||
expect(result.diff).toContain('diff --git')
|
||||
})
|
||||
})
|
||||
|
||||
describe('tracked file diff', () => {
|
||||
it('should get diff for modified tracked file', async () => {
|
||||
const fileName = 'modified-file.txt'
|
||||
const originalContent = 'Original line 1\nOriginal line 2\n'
|
||||
await createTestFile(testRepoPath, fileName, originalContent)
|
||||
await stageAndCommitTestFile(testRepoPath, fileName)
|
||||
|
||||
const modifiedContent = 'Original line 1\nModified line 2\nNew line 3\n'
|
||||
await createTestFile(testRepoPath, fileName, modifiedContent)
|
||||
|
||||
const result = await getFileDiff(testRepoPath, fileName)
|
||||
|
||||
expect(result.status).toBe('modified')
|
||||
expect(result.diff).toBeTruthy()
|
||||
expect(result.diff).toContain('-Original line 2')
|
||||
expect(result.diff).toContain('+Modified line 2')
|
||||
expect(result.diff).toContain('+New line 3')
|
||||
expect(result.additions).toBe(2)
|
||||
expect(result.deletions).toBe(1)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,233 @@
|
||||
import { describe, it, expect, vi, beforeEach, type MockedFunction } from 'vitest'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { GitAuthService } from '../../../src/services/git-auth'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn().mockImplementation(() => ({
|
||||
getSettings: vi.fn().mockReturnValue({
|
||||
preferences: {
|
||||
gitIdentity: null,
|
||||
gitCredentials: [],
|
||||
},
|
||||
}),
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/utils/process', () => ({
|
||||
executeCommand: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/db/queries', () => ({
|
||||
getRepoById: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/utils/git-auth', () => ({
|
||||
resolveGitIdentity: vi.fn().mockResolvedValue(null),
|
||||
createGitIdentityEnv: vi.fn().mockReturnValue({}),
|
||||
createSilentGitEnv: vi.fn(),
|
||||
}))
|
||||
|
||||
import { GitCommitService } from '../../../src/services/git/GitCommitService'
|
||||
import { executeCommand } from '../../../src/utils/process'
|
||||
import { getRepoById } from '../../../src/db/queries'
|
||||
|
||||
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
|
||||
const getRepoByIdMock = getRepoById as MockedFunction<typeof getRepoById>
|
||||
|
||||
describe('GitCommitService', () => {
|
||||
let service: GitCommitService
|
||||
let database: Database
|
||||
let mockGitAuthService: GitAuthService
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
database = {} as Database
|
||||
mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue({}),
|
||||
} as unknown as GitAuthService
|
||||
service = new GitCommitService(mockGitAuthService)
|
||||
})
|
||||
|
||||
describe('commit', () => {
|
||||
it('commits staged changes with message', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('[main abc1234] Test commit\n 1 file changed')
|
||||
|
||||
const result = await service.commit(1, 'Test commit', database)
|
||||
|
||||
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', mockRepo.fullPath, 'commit', '-m', 'Test commit'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toBe('[main abc1234] Test commit\n 1 file changed')
|
||||
})
|
||||
|
||||
it('commits specific staged files', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('[main abc1234] Commit specific files\n 2 files changed')
|
||||
|
||||
const result = await service.commit(1, 'Commit specific files', database, ['file1.ts', 'file2.ts'])
|
||||
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', mockRepo.fullPath, 'commit', '-m', 'Commit specific files', '--', 'file1.ts', 'file2.ts'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toBe('[main abc1234] Commit specific files\n 2 files changed')
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.commit(999, 'Test', database)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('throws error when commit command fails', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockRejectedValue(new Error('Nothing to commit'))
|
||||
|
||||
await expect(service.commit(1, 'Test', database)).rejects.toThrow('Nothing to commit')
|
||||
})
|
||||
})
|
||||
|
||||
describe('stageFiles', () => {
|
||||
it('stages files', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('')
|
||||
|
||||
const result = await service.stageFiles(1, ['file1.ts', 'file2.ts'], database)
|
||||
|
||||
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', mockRepo.fullPath, 'add', '--', 'file1.ts', 'file2.ts'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toBe('')
|
||||
})
|
||||
|
||||
it('returns early when no files to stage', async () => {
|
||||
const result = await service.stageFiles(1, [], database)
|
||||
|
||||
expect(executeCommandMock).not.toHaveBeenCalled()
|
||||
expect(result).toBe('')
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.stageFiles(999, ['file.ts'], database)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('throws error when stage command fails', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockRejectedValue(new Error('Pathspec error'))
|
||||
|
||||
await expect(service.stageFiles(1, ['invalid.txt'], database)).rejects.toThrow('Pathspec error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('unstageFiles', () => {
|
||||
it('unstages files', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('')
|
||||
|
||||
const result = await service.unstageFiles(1, ['file1.ts', 'file2.ts'], database)
|
||||
|
||||
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', mockRepo.fullPath, 'restore', '--staged', '--', 'file1.ts', 'file2.ts'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toBe('')
|
||||
})
|
||||
|
||||
it('returns early when no files to unstage', async () => {
|
||||
const result = await service.unstageFiles(1, [], database)
|
||||
|
||||
expect(executeCommandMock).not.toHaveBeenCalled()
|
||||
expect(result).toBe('')
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.unstageFiles(999, ['file.ts'], database)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('throws error when unstage command fails', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockRejectedValue(new Error('Error unstaging'))
|
||||
|
||||
await expect(service.unstageFiles(1, ['file.ts'], database)).rejects.toThrow('Error unstaging')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resetToCommit', () => {
|
||||
it('resets to specific commit', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('HEAD is now at abc123')
|
||||
|
||||
const result = await service.resetToCommit(1, 'abc123', database)
|
||||
|
||||
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', mockRepo.fullPath, 'reset', '--hard', 'abc123'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toBe('HEAD is now at abc123')
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.resetToCommit(999, 'abc123', database)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('throws error when reset command fails', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockRejectedValue(new Error('Invalid commit hash'))
|
||||
|
||||
await expect(service.resetToCommit(1, 'invalid', database)).rejects.toThrow('Invalid commit hash')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,330 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { describe, it, expect, vi, beforeEach, type MockedFunction } from 'vitest'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn()
|
||||
}))
|
||||
|
||||
import { GitLogService } from '../../../src/services/git/GitLogService'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { executeCommand } from '../../../src/utils/process'
|
||||
import { getRepoById } from '../../../src/db/queries'
|
||||
|
||||
const mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn(),
|
||||
}
|
||||
|
||||
const mockGitDiffService = {
|
||||
getFileDiff: vi.fn(),
|
||||
}
|
||||
|
||||
vi.mock('../../../src/utils/process', () => ({
|
||||
executeCommand: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/db/queries', () => ({
|
||||
getRepoById: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/services/git-auth', () => ({
|
||||
GitAuthService: vi.fn().mockImplementation(() => mockGitAuthService),
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
getReposPath: vi.fn(() => '/repos'),
|
||||
}))
|
||||
|
||||
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
|
||||
const getRepoByIdMock = getRepoById as MockedFunction<typeof getRepoById>
|
||||
|
||||
describe('GitLogService', () => {
|
||||
let service: GitLogService
|
||||
let database: Database
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
database = {} as Database
|
||||
service = new GitLogService(mockGitAuthService as any, mockGitDiffService as any)
|
||||
mockGitAuthService.getGitEnvironment.mockResolvedValue({})
|
||||
})
|
||||
|
||||
describe('getLog', () => {
|
||||
it('returns list of commits', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock
|
||||
.mockResolvedValueOnce(
|
||||
'abc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|First commit\n' +
|
||||
'def456|Jane Smith|jane@example.com|2024-01-02 13:00:00 +0000|Second commit'
|
||||
)
|
||||
.mockResolvedValueOnce('')
|
||||
|
||||
const result = await service.getLog(1, database, 10)
|
||||
|
||||
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', '/repos/test-repo', 'log', '--all', '-n', '10', '--format=%H|%an|%ae|%ai|%s'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toHaveLength(2)
|
||||
expect(result[0]).toEqual({
|
||||
hash: 'abc123',
|
||||
authorName: 'John Doe',
|
||||
authorEmail: 'john@example.com',
|
||||
date: '2024-01-01 12:00:00 +0000',
|
||||
message: 'First commit',
|
||||
unpushed: false,
|
||||
})
|
||||
expect(result[1]).toEqual({
|
||||
hash: 'def456',
|
||||
authorName: 'Jane Smith',
|
||||
authorEmail: 'jane@example.com',
|
||||
date: '2024-01-02 13:00:00 +0000',
|
||||
message: 'Second commit',
|
||||
unpushed: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('respects limit parameter', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock
|
||||
.mockResolvedValueOnce('abc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|First commit')
|
||||
.mockResolvedValueOnce('')
|
||||
|
||||
await service.getLog(1, database, 5)
|
||||
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', '/repos/test-repo', 'log', '--all', '-n', '5', '--format=%H|%an|%ae|%ai|%s'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
})
|
||||
|
||||
it('handles commits with empty messages', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock
|
||||
.mockResolvedValueOnce('abc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|')
|
||||
.mockResolvedValueOnce('')
|
||||
|
||||
const result = await service.getLog(1, database, 10)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]?.message).toBe('')
|
||||
})
|
||||
|
||||
it('handles commits with multi-line messages', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock
|
||||
.mockResolvedValueOnce('abc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|Multi|line commit')
|
||||
.mockResolvedValueOnce('')
|
||||
|
||||
const result = await service.getLog(1, database, 10)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]?.message).toBe('Multi|line commit')
|
||||
})
|
||||
|
||||
it('handles empty log output', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock
|
||||
.mockResolvedValueOnce('')
|
||||
.mockResolvedValueOnce('')
|
||||
|
||||
const result = await service.getLog(1, database, 10)
|
||||
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('handles whitespace lines in output', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock
|
||||
.mockResolvedValueOnce('\n\nabc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|Test\n\n')
|
||||
.mockResolvedValueOnce('')
|
||||
|
||||
const result = await service.getLog(1, database, 10)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]?.hash).toBe('abc123')
|
||||
})
|
||||
|
||||
it('skips lines without hash', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock
|
||||
.mockResolvedValueOnce('|John Doe|john@example.com|2024-01-01 12:00:00 +0000|No hash')
|
||||
.mockResolvedValueOnce('')
|
||||
|
||||
const result = await service.getLog(1, database, 10)
|
||||
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.getLog(999, database, 10)).rejects.toThrow('Repository not found: 999')
|
||||
})
|
||||
|
||||
it('throws error when log command fails', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockRejectedValue(new Error('Not a git repository'))
|
||||
|
||||
await expect(service.getLog(1, database, 10)).rejects.toThrow('Failed to get git log')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getCommit', () => {
|
||||
it('returns commit details for valid hash', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('abc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|Test commit')
|
||||
|
||||
const result = await service.getCommit(1, 'abc123', database)
|
||||
|
||||
expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1)
|
||||
expect(executeCommandMock).toHaveBeenCalledWith(
|
||||
['git', '-C', '/repos/test-repo', 'log', '--format=%H|%an|%ae|%ai|%s', 'abc123', '-1'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toEqual({
|
||||
hash: 'abc123',
|
||||
authorName: 'John Doe',
|
||||
authorEmail: 'john@example.com',
|
||||
date: '2024-01-01 12:00:00 +0000',
|
||||
message: 'Test commit',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null when commit hash not found', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('')
|
||||
|
||||
const result = await service.getCommit(1, 'nonexistent', database)
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when output is empty', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue(' ')
|
||||
|
||||
const result = await service.getCommit(1, 'abc123', database)
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when hash field is empty', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('|John Doe|john@example.com|2024-01-01 12:00:00 +0000|Test')
|
||||
|
||||
const result = await service.getCommit(1, 'abc123', database)
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('handles commits with empty messages', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('abc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|')
|
||||
|
||||
const result = await service.getCommit(1, 'abc123', database)
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.message).toBe('')
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.getCommit(999, 'abc123', database)).rejects.toThrow('Repository not found: 999')
|
||||
})
|
||||
|
||||
it('throws error when command fails', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
localPath: 'test-repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockRejectedValue(new Error('Invalid commit hash'))
|
||||
|
||||
await expect(service.getCommit(1, 'invalid', database)).rejects.toThrow('Failed to get commit')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getDiff', () => {
|
||||
it('returns diff for file', async () => {
|
||||
const expectedDiff = 'diff --git a/file.ts b/file.ts\nindex 123..456 100644\n--- a/file.ts\n+++ b/file.ts\n@@ -1,1 +1,1 @@\n-old line\n+new line'
|
||||
mockGitDiffService.getFileDiff.mockResolvedValue({ diff: expectedDiff })
|
||||
|
||||
const result = await service.getDiff(1, 'file.ts', database)
|
||||
|
||||
expect(mockGitDiffService.getFileDiff).toHaveBeenCalledWith(1, 'file.ts', database)
|
||||
expect(result).toBe(expectedDiff)
|
||||
})
|
||||
|
||||
it('returns empty diff when file has no changes', async () => {
|
||||
mockGitDiffService.getFileDiff.mockResolvedValue({ diff: '' })
|
||||
|
||||
const result = await service.getDiff(1, 'file.ts', database)
|
||||
|
||||
expect(result).toBe('')
|
||||
})
|
||||
|
||||
it('throws error when diff command fails', async () => {
|
||||
mockGitDiffService.getFileDiff.mockRejectedValue(new Error('Repository not found: 999'))
|
||||
|
||||
await expect(service.getDiff(999, 'file.ts', database)).rejects.toThrow('Repository not found: 999')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { GitAuthService } from '../../../src/services/git-auth'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/utils/process', () => ({
|
||||
executeCommand: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/db/queries', () => ({
|
||||
getRepoById: vi.fn(),
|
||||
}))
|
||||
|
||||
describe('GitPushService', () => {
|
||||
let executeCommand: ReturnType<typeof vi.fn>
|
||||
let getRepoById: ReturnType<typeof vi.fn>
|
||||
let mockGitAuthService: GitAuthService
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
const process = await import('../../../src/utils/process')
|
||||
const queries = await import('../../../src/db/queries')
|
||||
executeCommand = process.executeCommand as ReturnType<typeof vi.fn>
|
||||
getRepoById = queries.getRepoById as ReturnType<typeof vi.fn>
|
||||
mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue({}),
|
||||
} as unknown as GitAuthService
|
||||
})
|
||||
|
||||
describe('push', () => {
|
||||
it('pushes changes to remote', async () => {
|
||||
const { GitPushService } = await import('../../../src/services/git/GitPushService')
|
||||
const service = new GitPushService(mockGitAuthService)
|
||||
const database = {} as Database
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoById.mockReturnValue(mockRepo)
|
||||
executeCommand.mockResolvedValue('Everything up-to-date')
|
||||
|
||||
const result = await service.push(1, {}, database)
|
||||
|
||||
expect(getRepoById).toHaveBeenCalledWith(database, 1)
|
||||
expect(executeCommand).toHaveBeenCalledWith(
|
||||
['git', '-C', '/path/to/repo', 'push'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toBe('Everything up-to-date')
|
||||
})
|
||||
|
||||
it('pushes changes with upstream flag', async () => {
|
||||
const { GitPushService } = await import('../../../src/services/git/GitPushService')
|
||||
const service = new GitPushService(mockGitAuthService)
|
||||
const database = {} as Database
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoById.mockReturnValue(mockRepo)
|
||||
executeCommand.mockResolvedValue('Branch set up to track remote branch')
|
||||
|
||||
const result = await service.push(1, { setUpstream: true }, database)
|
||||
|
||||
expect(executeCommand).toHaveBeenCalledWith(
|
||||
['git', '-C', '/path/to/repo', 'push', '--set-upstream', 'origin', 'HEAD'],
|
||||
{ env: expect.any(Object) }
|
||||
)
|
||||
expect(result).toBe('Branch set up to track remote branch')
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
const { GitPushService } = await import('../../../src/services/git/GitPushService')
|
||||
const service = new GitPushService(mockGitAuthService)
|
||||
const database = {} as Database
|
||||
getRepoById.mockReturnValue(null)
|
||||
|
||||
await expect(service.push(999, {}, database)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('throws error when push command fails', async () => {
|
||||
const { GitPushService } = await import('../../../src/services/git/GitPushService')
|
||||
const service = new GitPushService(mockGitAuthService)
|
||||
const database = {} as Database
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoById.mockReturnValue(mockRepo)
|
||||
executeCommand.mockRejectedValue(new Error('Authentication failed'))
|
||||
|
||||
await expect(service.push(1, {}, database)).rejects.toThrow('Authentication failed')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,343 @@
|
||||
import { describe, it, expect, vi, beforeEach, type MockedFunction } from 'vitest'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { GitAuthService } from '../../../src/services/git-auth'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/utils/process', () => ({
|
||||
executeCommand: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/db/queries', () => ({
|
||||
getRepoById: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/utils/git-auth', () => ({
|
||||
createSilentGitEnv: vi.fn(),
|
||||
}))
|
||||
|
||||
import { GitStatusService } from '../../../src/services/git/GitStatusService'
|
||||
import { executeCommand } from '../../../src/utils/process'
|
||||
import { getRepoById } from '../../../src/db/queries'
|
||||
|
||||
const executeCommandMock = executeCommand as MockedFunction<typeof executeCommand>
|
||||
const getRepoByIdMock = getRepoById as MockedFunction<typeof getRepoById>
|
||||
|
||||
describe('GitStatusService', () => {
|
||||
let service: GitStatusService
|
||||
let database: Database
|
||||
let mockGitAuthService: GitAuthService
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
database = {} as Database
|
||||
mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue({}),
|
||||
} as unknown as GitAuthService
|
||||
service = new GitStatusService(mockGitAuthService)
|
||||
})
|
||||
|
||||
describe('getStatus', () => {
|
||||
it('returns empty status for clean repository', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
if (args.includes('status')) return Promise.resolve('')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.branch).toBe('main')
|
||||
expect(result.ahead).toBe(0)
|
||||
expect(result.behind).toBe(0)
|
||||
expect(result.files).toEqual([])
|
||||
expect(result.hasChanges).toBe(false)
|
||||
})
|
||||
|
||||
it('parses modified files correctly', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
if (args.includes('status')) return Promise.resolve('MM file.ts')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.files).toHaveLength(2)
|
||||
expect(result.files[0]).toEqual({ path: 'file.ts', status: 'modified', staged: true })
|
||||
expect(result.files[1]).toEqual({ path: 'file.ts', status: 'modified', staged: false })
|
||||
expect(result.hasChanges).toBe(true)
|
||||
})
|
||||
|
||||
it('parses staged files correctly', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
if (args.includes('status')) return Promise.resolve('M file1.ts\nA file2.ts')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.files).toHaveLength(2)
|
||||
expect(result.files[0]).toEqual({ path: 'file1.ts', status: 'modified', staged: true })
|
||||
expect(result.files[1]).toEqual({ path: 'file2.ts', status: 'added', staged: true })
|
||||
})
|
||||
|
||||
it('parses deleted files correctly', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
if (args.includes('status')) return Promise.resolve('D file1.ts\n D file2.ts')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.files).toHaveLength(2)
|
||||
expect(result.files[0]).toEqual({ path: 'file1.ts', status: 'deleted', staged: true })
|
||||
expect(result.files[1]).toEqual({ path: 'file2.ts', status: 'deleted', staged: false })
|
||||
})
|
||||
|
||||
it('parses renamed files correctly with arrow notation', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
if (args.includes('status')) return Promise.resolve('R old.ts -> new.ts')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.files).toHaveLength(1)
|
||||
expect(result.files[0]).toEqual({ path: 'new.ts', oldPath: 'old.ts', status: 'renamed', staged: true })
|
||||
})
|
||||
|
||||
it('parses untracked files correctly', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
if (args.includes('status')) return Promise.resolve('?? newfile.ts')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.files).toHaveLength(1)
|
||||
expect(result.files[0]).toEqual({ path: 'newfile.ts', status: 'untracked', staged: false })
|
||||
})
|
||||
|
||||
it('parses copied files correctly', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
if (args.includes('status')) return Promise.resolve('C original.ts')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.files).toHaveLength(1)
|
||||
expect(result.files[0]).toEqual({ path: 'original.ts', status: 'copied', staged: true })
|
||||
})
|
||||
|
||||
it('parses mixed status output', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
if (args.includes('status')) return Promise.resolve('MM file1.ts\nA file2.ts\n?? file3.ts\nD file4.ts')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.files).toHaveLength(5)
|
||||
expect(result.files).toContainEqual({ path: 'file1.ts', status: 'modified', staged: true })
|
||||
expect(result.files).toContainEqual({ path: 'file1.ts', status: 'modified', staged: false })
|
||||
expect(result.files).toContainEqual({ path: 'file2.ts', status: 'added', staged: true })
|
||||
expect(result.files).toContainEqual({ path: 'file3.ts', status: 'untracked', staged: false })
|
||||
expect(result.files).toContainEqual({ path: 'file4.ts', status: 'deleted', staged: true })
|
||||
})
|
||||
|
||||
it('returns branch status with ahead/behind', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('feature-branch')
|
||||
if (args.includes('rev-list')) return Promise.resolve('2 3')
|
||||
if (args.includes('status')) return Promise.resolve('')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.branch).toBe('feature-branch')
|
||||
expect(result.ahead).toBe(2)
|
||||
expect(result.behind).toBe(3)
|
||||
})
|
||||
|
||||
it('handles branch status command failure gracefully', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.reject(new Error('No upstream'))
|
||||
if (args.includes('rev-list')) return Promise.reject(new Error('No upstream'))
|
||||
if (args.includes('status')) return Promise.resolve('')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.branch).toBe('')
|
||||
expect(result.ahead).toBe(0)
|
||||
expect(result.behind).toBe(0)
|
||||
})
|
||||
|
||||
it('throws error when repository not found', async () => {
|
||||
getRepoByIdMock.mockReturnValue(null)
|
||||
|
||||
await expect(service.getStatus(999, database)).rejects.toThrow('Repository not found')
|
||||
})
|
||||
|
||||
it('throws error when status command fails', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockRejectedValue(new Error('Not a git repository'))
|
||||
|
||||
await expect(service.getStatus(1, database)).rejects.toThrow('Not a git repository')
|
||||
})
|
||||
|
||||
it('parses copied files correctly with arrow notation', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
if (args.includes('status')) return Promise.resolve('C source.ts -> copy.ts')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.files).toHaveLength(1)
|
||||
expect(result.files[0]).toEqual({ path: 'copy.ts', oldPath: 'source.ts', status: 'copied', staged: true })
|
||||
})
|
||||
|
||||
it('preserves spaces in filenames without trimming', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 0')
|
||||
if (args.includes('status')) return Promise.resolve('M path with spaces/file name.ts')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.files).toHaveLength(1)
|
||||
expect(result.files[0]).toEqual({ path: 'path with spaces/file name.ts', status: 'modified', staged: true })
|
||||
})
|
||||
|
||||
it('handles tab-separated ahead/behind output', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('5\t0')
|
||||
if (args.includes('status')) return Promise.resolve('')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.ahead).toBe(5)
|
||||
expect(result.behind).toBe(0)
|
||||
})
|
||||
|
||||
it('handles only behind count correctly', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('rev-parse')) return Promise.resolve('main')
|
||||
if (args.includes('rev-list')) return Promise.resolve('0 7')
|
||||
if (args.includes('status')) return Promise.resolve('')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.ahead).toBe(0)
|
||||
expect(result.behind).toBe(7)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import { createGitHubGitEnv } from '../../src/utils/git-auth'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
|
||||
const executeCommand = vi.fn()
|
||||
const ensureDirectoryExists = vi.fn()
|
||||
@@ -25,18 +25,15 @@ vi.mock('../../src/db/queries', () => ({
|
||||
deleteRepo,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn().mockImplementation(() => ({
|
||||
getSettings: () => ({
|
||||
preferences: {
|
||||
gitCredentials: [
|
||||
{ name: 'GitHub', host: 'https://github.com/', token: 'ghp_test_token' }
|
||||
],
|
||||
},
|
||||
updatedAt: Date.now(),
|
||||
}),
|
||||
})),
|
||||
}))
|
||||
const mockEnv = {
|
||||
GIT_TERMINAL_PROMPT: '0',
|
||||
LANG: 'en_US.UTF-8',
|
||||
LC_ALL: 'en_US.UTF-8',
|
||||
}
|
||||
|
||||
const mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue(mockEnv),
|
||||
} as unknown as GitAuthService
|
||||
|
||||
describe('repoService.cloneRepo auth env', () => {
|
||||
beforeEach(() => {
|
||||
@@ -64,14 +61,12 @@ describe('repoService.cloneRepo auth env', () => {
|
||||
.mockResolvedValueOnce('missing')
|
||||
.mockResolvedValueOnce('')
|
||||
|
||||
await cloneRepo(database, repoUrl)
|
||||
|
||||
const expectedEnv = createGitHubGitEnv('ghp_test_token')
|
||||
await cloneRepo(database, mockGitAuthService, repoUrl)
|
||||
|
||||
expect(executeCommand).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
['git', 'clone', 'https://github.com/acme/forge', 'forge'],
|
||||
{ cwd: getReposPath(), env: expectedEnv, silent: undefined }
|
||||
expect.objectContaining({ cwd: getReposPath(), env: mockEnv })
|
||||
)
|
||||
|
||||
expect(ensureDirectoryExists).toHaveBeenCalledWith(getReposPath())
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
|
||||
const executeCommand = vi.fn()
|
||||
const ensureDirectoryExists = vi.fn()
|
||||
@@ -35,10 +36,13 @@ vi.mock('../../src/services/settings', () => ({
|
||||
})),
|
||||
}))
|
||||
|
||||
const mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue({}),
|
||||
} as unknown as GitAuthService
|
||||
|
||||
describe('initLocalRepo', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.resetModules()
|
||||
executeCommand.mockResolvedValue('')
|
||||
ensureDirectoryExists.mockResolvedValue(undefined)
|
||||
})
|
||||
@@ -59,8 +63,8 @@ describe('initLocalRepo', () => {
|
||||
isLocal: true,
|
||||
})
|
||||
|
||||
const result = await initLocalRepo(database, localPath)
|
||||
|
||||
const result = await initLocalRepo(database, mockGitAuthService, localPath)
|
||||
|
||||
expect(executeCommand).toHaveBeenCalledWith(['git', 'init'], expect.any(Object))
|
||||
expect(ensureDirectoryExists).toHaveBeenCalledWith(expect.stringContaining('my-new-repo'))
|
||||
expect(updateRepoStatus).toHaveBeenCalledWith(database, 1, 'ready')
|
||||
@@ -71,7 +75,7 @@ describe('initLocalRepo', () => {
|
||||
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,
|
||||
@@ -82,7 +86,7 @@ describe('initLocalRepo', () => {
|
||||
clonedAt: Date.now(),
|
||||
isLocal: true,
|
||||
}))
|
||||
|
||||
|
||||
let callCount = 0
|
||||
executeCommand.mockImplementation(async () => {
|
||||
callCount++
|
||||
@@ -92,10 +96,10 @@ describe('initLocalRepo', () => {
|
||||
return ''
|
||||
})
|
||||
|
||||
const result = await initLocalRepo(database, absolutePath)
|
||||
|
||||
const result = await initLocalRepo(database, mockGitAuthService, 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', '-C', '/Users/test/existing-repo', 'rev-parse', '--git-dir'], expect.objectContaining({ 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')
|
||||
@@ -111,11 +115,11 @@ describe('initLocalRepo', () => {
|
||||
localPath: 'existing-repo',
|
||||
cloneStatus: 'ready' as const,
|
||||
}
|
||||
|
||||
|
||||
getRepoByLocalPath.mockReturnValue(existingRepo)
|
||||
|
||||
const result = await initLocalRepo(database, localPath)
|
||||
|
||||
|
||||
const result = await initLocalRepo(database, mockGitAuthService, localPath)
|
||||
|
||||
expect(result).toBe(existingRepo)
|
||||
expect(createRepo).not.toHaveBeenCalled()
|
||||
expect(executeCommand).not.toHaveBeenCalled()
|
||||
@@ -125,17 +129,17 @@ describe('initLocalRepo', () => {
|
||||
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")
|
||||
await expect(initLocalRepo(database, mockGitAuthService, 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++
|
||||
@@ -144,14 +148,14 @@ describe('initLocalRepo', () => {
|
||||
return ''
|
||||
})
|
||||
|
||||
await expect(initLocalRepo(database, absolutePath)).rejects.toThrow("A repository named 'existing-repo' already exists in the workspace")
|
||||
await expect(initLocalRepo(database, mockGitAuthService, 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++
|
||||
@@ -159,7 +163,7 @@ describe('initLocalRepo', () => {
|
||||
return ''
|
||||
})
|
||||
|
||||
await expect(initLocalRepo(database, nonGitPath)).rejects.toThrow("Directory exists but is not a valid Git repository")
|
||||
await expect(initLocalRepo(database, mockGitAuthService, nonGitPath)).rejects.toThrow("Directory exists but is not a valid Git repository")
|
||||
})
|
||||
|
||||
it('creates new empty repo with custom branch', async () => {
|
||||
@@ -167,7 +171,7 @@ describe('initLocalRepo', () => {
|
||||
const database = {} as any
|
||||
const localPath = 'custom-branch-repo'
|
||||
const branch = 'develop'
|
||||
|
||||
|
||||
getRepoByLocalPath.mockReturnValue(null)
|
||||
createRepo.mockReturnValue({
|
||||
id: 3,
|
||||
@@ -179,9 +183,9 @@ describe('initLocalRepo', () => {
|
||||
clonedAt: Date.now(),
|
||||
isLocal: true,
|
||||
})
|
||||
|
||||
const result = await initLocalRepo(database, localPath, branch)
|
||||
|
||||
|
||||
const result = await initLocalRepo(database, mockGitAuthService, 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')
|
||||
@@ -191,7 +195,7 @@ describe('initLocalRepo', () => {
|
||||
const { initLocalRepo } = await import('../../src/services/repo')
|
||||
const database = {} as any
|
||||
const localPath = 'my-repo/'
|
||||
|
||||
|
||||
getRepoByLocalPath.mockReturnValue(null)
|
||||
createRepo.mockReturnValue({
|
||||
id: 4,
|
||||
@@ -202,9 +206,9 @@ describe('initLocalRepo', () => {
|
||||
clonedAt: Date.now(),
|
||||
isLocal: true,
|
||||
})
|
||||
|
||||
const result = await initLocalRepo(database, localPath)
|
||||
|
||||
|
||||
const result = await initLocalRepo(database, mockGitAuthService, localPath)
|
||||
|
||||
expect(result.localPath).toBe('my-repo')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user