-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathrepo.ts
More file actions
897 lines (744 loc) · 33.4 KB
/
repo.ts
File metadata and controls
897 lines (744 loc) · 33.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
import { executeCommand } from '../utils/process'
import { ensureDirectoryExists, directoryExists, removeDirectory, listDirectoryNames } from './file-operations'
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 path from 'path'
export class GitAuthenticationError extends Error {
constructor(message: string) {
super(message)
this.name = 'GitAuthenticationError'
}
}
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 })
}
}
async function hasCommits(repoPath: string): Promise<boolean> {
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', 'HEAD'], { silent: true })
return true
} catch {
return false
}
}
async function isValidGitRepo(repoPath: string): Promise<boolean> {
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--git-dir'], { silent: true })
return true
} catch {
return false
}
}
async function checkRepoNameAvailable(name: string): Promise<boolean> {
const reposPath = getReposPath()
const targetPath = path.join(reposPath, name)
return !(await directoryExists(targetPath))
}
async function copyRepoToWorkspace(sourcePath: string, targetName: 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 })
logger.info(`Successfully copied repo to ${targetPath}`)
}
async function safeGetCurrentBranch(repoPath: string): Promise<string | null> {
try {
const repoHasCommits = await hasCommits(repoPath)
if (!repoHasCommits) {
try {
const symbolicRef = await executeCommand(['git', '-C', repoPath, 'symbolic-ref', '--short', 'HEAD'], { silent: true })
return symbolicRef.trim()
} catch {
return null
}
}
const currentBranch = await executeCommand(['git', '-C', repoPath, 'rev-parse', '--abbrev-ref', 'HEAD'], { silent: true })
return currentBranch.trim()
} catch {
return null
}
}
async function checkoutBranchSafely(repoPath: string, branch: string): Promise<void> {
const sanitizedBranch = branch
.replace(/^refs\/heads\//, '')
.replace(/^refs\/remotes\//, '')
.replace(/^origin\//, '')
let localBranchExists = false
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/heads/${sanitizedBranch}`], { silent: true })
localBranchExists = true
} catch {
localBranchExists = false
}
let remoteBranchExists = false
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/remotes/origin/${sanitizedBranch}`], { silent: true })
remoteBranchExists = true
} catch {
remoteBranchExists = false
}
if (localBranchExists) {
logger.info(`Checking out existing local branch: ${sanitizedBranch}`)
await executeCommand(['git', '-C', repoPath, 'checkout', sanitizedBranch])
} else if (remoteBranchExists) {
logger.info(`Checking out remote branch: ${sanitizedBranch}`)
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch, `origin/${sanitizedBranch}`])
} else {
logger.info(`Creating new branch: ${sanitizedBranch}`)
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch])
}
}
function getGitEnv(database: Database): Record<string, string> {
try {
const settingsService = new SettingsService(database)
const settings = settingsService.getSettings('default')
const gitCredentials = settings.preferences.gitCredentials || []
return createGitEnv(gitCredentials)
} catch {
return createNoPromptGitEnv()
}
}
export async function initLocalRepo(
database: Database,
localPath: string,
branch?: string
): Promise<Repo> {
const normalizedInputPath = localPath.trim().replace(/\/+$/, '')
let targetPath: string
let repoLocalPath: string
let sourceWasGitRepo = false
if (path.isAbsolute(normalizedInputPath)) {
logger.info(`Absolute path detected: ${normalizedInputPath}`)
try {
const exists = await directoryExists(normalizedInputPath)
if (!exists) {
throw new Error(`No such file or directory: '${normalizedInputPath}'`)
}
const isGit = await isValidGitRepo(normalizedInputPath)
if (isGit) {
sourceWasGitRepo = true
const baseName = path.basename(normalizedInputPath)
const isAvailable = await checkRepoNameAvailable(baseName)
if (!isAvailable) {
throw new Error(`A repository named '${baseName}' already exists in the workspace. Please remove it first or use a different source directory.`)
}
repoLocalPath = baseName
logger.info(`Copying existing git repo from ${normalizedInputPath} to workspace as ${baseName}`)
await copyRepoToWorkspace(normalizedInputPath, baseName)
targetPath = path.join(getReposPath(), baseName)
} else {
throw new Error(`Directory exists but is not a valid Git repository. Please provide either a Git repository path or a simple directory name to create a new empty repository.`)
}
} catch (error: any) {
if (error.message.includes('No such file or directory')) {
throw error
}
throw new Error(`Failed to process absolute path '${normalizedInputPath}': ${error.message}`)
}
} else {
repoLocalPath = normalizedInputPath
targetPath = path.join(getReposPath(), repoLocalPath)
}
const existing = db.getRepoByLocalPath(database, repoLocalPath)
if (existing) {
logger.info(`Local repo already exists in database: ${repoLocalPath}`)
return existing
}
const createRepoInput: CreateRepoInput = {
localPath: repoLocalPath,
branch: branch || undefined,
defaultBranch: branch || 'main',
cloneStatus: 'cloning',
clonedAt: Date.now(),
isLocal: true,
}
let repo: Repo
let directoryCreated = false
try {
repo = db.createRepo(database, createRepoInput)
logger.info(`Created database record for local repo: ${repoLocalPath} (id: ${repo.id})`)
} catch (error: any) {
logger.error(`Failed to create database record for local repo: ${repoLocalPath}`, error)
throw new Error(`Failed to register local repository '${repoLocalPath}': ${error.message}`)
}
try {
if (!sourceWasGitRepo) {
await ensureDirectoryExists(targetPath)
directoryCreated = true
logger.info(`Created directory for local repo: ${targetPath}`)
logger.info(`Initializing git repository: ${targetPath}`)
await executeCommand(['git', 'init'], { cwd: targetPath })
if (branch && branch !== 'main') {
await executeCommand(['git', '-C', targetPath, 'checkout', '-b', branch])
}
} else {
if (branch) {
logger.info(`Switching to branch ${branch} for copied repo`)
const currentBranch = await safeGetCurrentBranch(targetPath)
if (currentBranch !== branch) {
await checkoutBranchSafely(targetPath, branch)
}
}
}
const isGitRepo = await executeCommand(['git', '-C', targetPath, 'rev-parse', '--git-dir'])
.then(() => true)
.catch(() => false)
if (!isGitRepo) {
throw new Error(`Git initialization failed - directory exists but is not a valid git repository`)
}
db.updateRepoStatus(database, repo.id, 'ready')
logger.info(`Local git repo ready: ${repoLocalPath}`)
return { ...repo, cloneStatus: 'ready' }
} catch (error: any) {
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)
}
if (directoryCreated && !sourceWasGitRepo) {
try {
await removeDirectory(path.join(getReposPath(), repoLocalPath))
logger.info(`Rolled back directory: ${repoLocalPath}`)
} catch (fsError: any) {
logger.error(`Failed to rollback directory ${repoLocalPath}:`, fsError)
}
} else if (sourceWasGitRepo) {
try {
await removeDirectory(path.join(getReposPath(), repoLocalPath))
logger.info(`Cleaned up copied directory: ${repoLocalPath}`)
} catch (fsError: any) {
logger.error(`Failed to clean up copied directory ${repoLocalPath}:`, fsError)
}
}
throw new Error(`Failed to initialize local repository '${repoLocalPath}': ${error.message}`)
}
}
export async function cloneRepo(
database: Database,
repoUrl: string,
branch?: string,
useWorktree: boolean = false
): Promise<Repo> {
const { url: normalizedRepoUrl, name: repoName } = normalizeRepoUrl(repoUrl)
const baseRepoDirName = repoName
const worktreeDirName = branch && useWorktree ? `${repoName}-${branch.replace(/[\\/]/g, '-')}` : repoName
const localPath = worktreeDirName
const existing = db.getRepoByUrlAndBranch(database, normalizedRepoUrl, branch)
if (existing) {
logger.info(`Repo branch already exists: ${normalizedRepoUrl}${branch ? `#${branch}` : ''}`)
return existing
}
await ensureDirectoryExists(getReposPath())
const baseRepoExists = await directoryExists(path.join(getReposPath(), baseRepoDirName))
const shouldUseWorktree = useWorktree && branch && baseRepoExists
const createRepoInput: CreateRepoInput = {
repoUrl: normalizedRepoUrl,
localPath,
branch: branch || undefined,
defaultBranch: branch || 'main',
cloneStatus: 'cloning',
clonedAt: Date.now(),
}
if (shouldUseWorktree) {
createRepoInput.isWorktree = true
}
const repo = db.createRepo(database, createRepoInput)
try {
const env = getGitEnv(database)
if (shouldUseWorktree) {
logger.info(`Creating worktree for branch: ${branch}`)
const baseRepoPath = path.resolve(getReposPath(), baseRepoDirName)
const worktreePath = path.resolve(getReposPath(), worktreeDirName)
await executeGitWithFallback(['git', '-C', baseRepoPath, 'fetch', '--all'], { cwd: getReposPath(), env })
await createWorktreeSafely(baseRepoPath, worktreePath, branch)
const worktreeVerified = await directoryExists(worktreePath)
if (!worktreeVerified) {
throw new Error(`Worktree directory was not created at: ${worktreePath}`)
}
logger.info(`Worktree verified at: ${worktreePath}`)
} else if (branch && baseRepoExists && useWorktree) {
logger.info(`Base repo exists but worktree creation failed, cloning branch separately`)
const worktreeExists = await directoryExists(path.join(getReposPath(), worktreeDirName))
if (worktreeExists) {
logger.info(`Workspace directory exists, removing it: ${worktreeDirName}`)
try {
await removeDirectory(path.join(getReposPath(), worktreeDirName))
const verifyRemoved = !(await directoryExists(path.join(getReposPath(), worktreeDirName)))
if (!verifyRemoved) {
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`)
}
}
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')) {
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 (error.message.includes('Remote branch') || error.message.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 })
let localBranchExists: 'exists' | 'missing'
try {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`])
localBranchExists = 'exists'
} catch {
localBranchExists = 'missing'
}
if (localBranchExists === 'missing') {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', '-b', branch])
} else {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', branch])
}
} else {
throw error
}
}
} else {
if (baseRepoExists) {
logger.info(`Repository directory already exists, verifying it's a valid git repo: ${baseRepoDirName}`)
const isValidRepo = await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'rev-parse', '--git-dir'], path.resolve(getReposPath())).then(() => 'valid').catch(() => 'invalid')
if (isValidRepo === 'valid') {
logger.info(`Valid repository found: ${normalizedRepoUrl}`)
if (branch) {
logger.info(`Switching to branch: ${branch}`)
await executeGitWithFallback(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'fetch', '--all'], { cwd: getReposPath(), env })
let remoteBranchExists = false
try {
await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'rev-parse', '--verify', `refs/remotes/origin/${branch}`])
remoteBranchExists = true
} catch {
remoteBranchExists = false
}
let localBranchExists = false
try {
await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'rev-parse', '--verify', `refs/heads/${branch}`])
localBranchExists = true
} catch {
localBranchExists = false
}
if (localBranchExists) {
logger.info(`Checking out existing local branch: ${branch}`)
await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'checkout', branch])
} else if (remoteBranchExists) {
logger.info(`Checking out remote branch: ${branch}`)
await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'checkout', '-b', branch, `origin/${branch}`])
} else {
logger.info(`Creating new branch: ${branch}`)
await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'checkout', '-b', branch])
}
}
db.updateRepoStatus(database, repo.id, 'ready')
return { ...repo, cloneStatus: 'ready' }
} else {
logger.warn(`Invalid repository directory found, removing and recloning: ${baseRepoDirName}`)
await removeDirectory(path.join(getReposPath(), baseRepoDirName))
}
}
logger.info(`Cloning repo: ${normalizedRepoUrl}${branch ? ` to branch ${branch}` : ''}`)
const worktreeExists = await directoryExists(path.join(getReposPath(), worktreeDirName))
if (worktreeExists) {
logger.info(`Workspace directory exists, removing it: ${worktreeDirName}`)
try {
await removeDirectory(path.join(getReposPath(), worktreeDirName))
const verifyRemoved = !(await directoryExists(path.join(getReposPath(), worktreeDirName)))
if (!verifyRemoved) {
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`)
}
}
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')) {
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'))) {
logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`)
await executeGitWithFallback(['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}`])
localBranchExists = 'exists'
} catch {
localBranchExists = 'missing'
}
if (localBranchExists === 'missing') {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', '-b', branch])
} else {
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', branch])
}
} else {
throw error
}
}
}
db.updateRepoStatus(database, repo.id, 'ready')
logger.info(`Repo ready: ${normalizedRepoUrl}${branch ? `#${branch}` : ''}${shouldUseWorktree ? ' (worktree)' : ''}`)
return { ...repo, cloneStatus: 'ready' }
} catch (error: any) {
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> {
const repoPath = path.resolve(getReposPath(), repo.localPath)
const branch = await safeGetCurrentBranch(repoPath)
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> {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repo not found: ${repoId}`)
}
try {
const repoPath = path.resolve(getReposPath(), repo.localPath)
const env = getGitEnv(database)
const sanitizedBranch = branch
.replace(/^refs\/heads\//, '')
.replace(/^refs\/remotes\//, '')
.replace(/^origin\//, '')
logger.info(`Switching to branch: ${sanitizedBranch} in ${repo.localPath}`)
await executeGitWithFallback(['git', '-C', repoPath, 'fetch', '--all'], { env })
await checkoutBranchSafely(repoPath, sanitizedBranch)
logger.info(`Successfully switched to branch: ${sanitizedBranch}`)
} catch (error: any) {
logger.error(`Failed to switch branch for repo ${repoId}:`, error)
throw error
}
}
export async function createBranch(database: Database, repoId: number, branch: string): Promise<void> {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repo not found: ${repoId}`)
}
try {
const repoPath = path.resolve(getReposPath(), repo.localPath)
const sanitizedBranch = branch
.replace(/^refs\/heads\//, '')
.replace(/^refs\/remotes\//, '')
.replace(/^origin\//, '')
logger.info(`Creating new branch: ${sanitizedBranch} in ${repo.localPath}`)
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch])
logger.info(`Successfully created and switched to branch: ${sanitizedBranch}`)
} catch (error: any) {
logger.error(`Failed to create branch for repo ${repoId}:`, error)
throw error
}
}
export async function pullRepo(database: Database, repoId: number): Promise<void> {
const repo = db.getRepoById(database, repoId)
if (!repo) {
throw new Error(`Repo not found: ${repoId}`)
}
if (repo.isLocal) {
logger.info(`Skipping pull for local repo: ${repo.localPath}`)
return
}
try {
const env = getGitEnv(database)
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) {
logger.error(`Failed to pull repo: ${repo.repoUrl}`, error)
throw error
}
}
export async function deleteRepoFiles(database: Database, repoId: number): Promise<void> {
const repo = db.getRepoById(database, repoId)
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
}
}
}
}
// Remove the directory
logger.info(`Removing directory: ${dirName} from ${getReposPath()}`)
await removeDirectory(path.join(getReposPath(), dirName))
const checkExists = await directoryExists(path.join(getReposPath(), dirName))
if (checkExists) {
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
}
}
function normalizeRepoUrl(url: string): { url: string; name: string } {
const shorthandMatch = url.match(/^([^\/]+)\/([^\/]+)$/)
if (shorthandMatch) {
const [, owner, repoName] = shorthandMatch as [string, string, string]
return {
url: `https://github.com/${owner}/${repoName}`,
name: repoName
}
}
if (url.startsWith('http://') || url.startsWith('https://')) {
const httpsUrl = url.replace(/^http:/, 'https:')
const urlWithoutGit = httpsUrl.replace(/\.git$/, '')
const match = urlWithoutGit.match(/\/([^\/]+)$/)
return {
url: urlWithoutGit,
name: match?.[1] || `repo-${Date.now()}`
}
}
return {
url,
name: `repo-${Date.now()}`
}
}
export async function cleanupOrphanedDirectories(database: Database): Promise<void> {
try {
const reposPath = getReposPath()
await ensureDirectoryExists(reposPath)
const directories = await listDirectoryNames(reposPath)
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 removeDirectory(path.join(reposPath, dir))
} catch (error) {
logger.warn(`Failed to remove orphaned directory ${dir}:`, error)
}
}
}
} catch (error) {
logger.warn('Failed to cleanup orphaned directories:', error)
}
}
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)
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'])
.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'])
}
}
let branchExists = false
try {
await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--verify', `refs/heads/${branch}`])
branchExists = true
} catch {
try {
await executeCommand(['git', '-C', baseRepoPath, 'rev-parse', '--verify', `refs/remotes/origin/${branch}`])
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...`)
}
}
}
}