mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Add local repository support and permission request handling
This commit is contained in:
1 parent
9a2ebc9652
commit
83834e7ed7
22 files changed
+685
-120
No files matched your search
@@ -4,6 +4,41 @@ import { logger } from '../utils/logger'
|
||||
export function runMigrations(db: Database): void {
|
||||
try {
|
||||
const tableInfo = db.prepare("PRAGMA table_info(repos)").all() as any[]
|
||||
|
||||
const repoUrlColumn = tableInfo.find((col: any) => col.name === 'repo_url')
|
||||
if (repoUrlColumn && repoUrlColumn.notnull === 1) {
|
||||
logger.info('Migrating repos table to allow nullable repo_url for local repos')
|
||||
db.run('BEGIN TRANSACTION')
|
||||
try {
|
||||
db.run(`
|
||||
CREATE TABLE repos_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_url TEXT,
|
||||
local_path TEXT NOT NULL,
|
||||
branch TEXT,
|
||||
default_branch TEXT,
|
||||
clone_status TEXT NOT NULL,
|
||||
cloned_at INTEGER NOT NULL,
|
||||
last_pulled INTEGER,
|
||||
opencode_config_name TEXT,
|
||||
is_worktree BOOLEAN DEFAULT FALSE,
|
||||
is_local BOOLEAN DEFAULT FALSE
|
||||
)
|
||||
`)
|
||||
db.run(`
|
||||
INSERT INTO repos_new (id, repo_url, local_path, branch, default_branch, clone_status, cloned_at, last_pulled, opencode_config_name, is_worktree, is_local)
|
||||
SELECT id, repo_url, local_path, branch, default_branch, clone_status, cloned_at, last_pulled, opencode_config_name, is_worktree, is_local FROM repos
|
||||
`)
|
||||
db.run('DROP TABLE repos')
|
||||
db.run('ALTER TABLE repos_new RENAME TO repos')
|
||||
db.run('COMMIT')
|
||||
logger.info('Successfully migrated repos table to allow nullable repo_url')
|
||||
} catch (migrationError) {
|
||||
db.run('ROLLBACK')
|
||||
throw migrationError
|
||||
}
|
||||
}
|
||||
|
||||
const hasBranchColumn = tableInfo.some(col => col.name === 'branch')
|
||||
|
||||
if (!hasBranchColumn) {
|
||||
@@ -21,13 +56,23 @@ export function runMigrations(db: Database): void {
|
||||
logger.debug('Index already exists or could not be created', error)
|
||||
}
|
||||
|
||||
try {
|
||||
db.run(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_local_path
|
||||
ON repos(local_path)
|
||||
`)
|
||||
} catch (error) {
|
||||
logger.debug('Local path index already exists or could not be created', error)
|
||||
}
|
||||
|
||||
const requiredColumns = [
|
||||
{ name: 'default_branch', sql: 'ALTER TABLE repos ADD COLUMN default_branch TEXT' },
|
||||
{ name: 'clone_status', sql: 'ALTER TABLE repos ADD COLUMN clone_status TEXT NOT NULL DEFAULT "cloning"' },
|
||||
{ name: 'cloned_at', sql: 'ALTER TABLE repos ADD COLUMN cloned_at INTEGER NOT NULL DEFAULT 0' },
|
||||
{ name: 'last_pulled', sql: 'ALTER TABLE repos ADD COLUMN last_pulled INTEGER' },
|
||||
{ name: 'opencode_config_name', sql: 'ALTER TABLE repos ADD COLUMN opencode_config_name TEXT' },
|
||||
{ name: 'is_worktree', sql: 'ALTER TABLE repos ADD COLUMN is_worktree BOOLEAN DEFAULT FALSE' }
|
||||
{ name: 'is_worktree', sql: 'ALTER TABLE repos ADD COLUMN is_worktree BOOLEAN DEFAULT FALSE' },
|
||||
{ name: 'is_local', sql: 'ALTER TABLE repos ADD COLUMN is_local BOOLEAN DEFAULT FALSE' }
|
||||
]
|
||||
|
||||
for (const column of requiredColumns) {
|
||||
|
||||
+54
-22
@@ -5,7 +5,7 @@ import path from 'path'
|
||||
|
||||
export interface RepoRow {
|
||||
id: number
|
||||
repo_url: string
|
||||
repo_url?: string
|
||||
local_path: string
|
||||
branch?: string
|
||||
default_branch: string
|
||||
@@ -14,6 +14,7 @@ export interface RepoRow {
|
||||
last_pulled?: number
|
||||
opencode_config_name?: string
|
||||
is_worktree?: number
|
||||
is_local?: number
|
||||
}
|
||||
|
||||
function rowToRepo(row: RepoRow): Repo {
|
||||
@@ -29,35 +30,59 @@ function rowToRepo(row: RepoRow): Repo {
|
||||
lastPulled: row.last_pulled,
|
||||
openCodeConfigName: row.opencode_config_name,
|
||||
isWorktree: row.is_worktree ? Boolean(row.is_worktree) : undefined,
|
||||
isLocal: row.is_local ? Boolean(row.is_local) : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export function createRepo(db: Database, repo: CreateRepoInput): Repo {
|
||||
const stmt = db.prepare(`
|
||||
INSERT OR IGNORE INTO repos (repo_url, local_path, branch, default_branch, clone_status, cloned_at, is_worktree)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
const normalizedPath = repo.localPath.replace(/\/+$/, '')
|
||||
|
||||
const result = stmt.run(
|
||||
repo.repoUrl,
|
||||
repo.localPath,
|
||||
repo.branch || null,
|
||||
repo.defaultBranch,
|
||||
repo.cloneStatus,
|
||||
repo.clonedAt,
|
||||
repo.isWorktree ? 1 : 0
|
||||
)
|
||||
const existing = repo.isLocal
|
||||
? getRepoByLocalPath(db, normalizedPath)
|
||||
: getRepoByUrlAndBranch(db, repo.repoUrl!, repo.branch)
|
||||
|
||||
if (result.changes === 0) {
|
||||
const existing = getRepoByUrlAndBranch(db, repo.repoUrl, repo.branch)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
throw new Error('Failed to create repo and no existing repo found')
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
|
||||
const newRepo = getRepoById(db, Number(result.lastInsertRowid))!
|
||||
return newRepo
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO repos (repo_url, local_path, branch, default_branch, clone_status, cloned_at, is_worktree, is_local)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
try {
|
||||
const result = stmt.run(
|
||||
repo.repoUrl || null,
|
||||
normalizedPath,
|
||||
repo.branch || null,
|
||||
repo.defaultBranch,
|
||||
repo.cloneStatus,
|
||||
repo.clonedAt,
|
||||
repo.isWorktree ? 1 : 0,
|
||||
repo.isLocal ? 1 : 0
|
||||
)
|
||||
|
||||
const newRepo = getRepoById(db, Number(result.lastInsertRowid))
|
||||
if (!newRepo) {
|
||||
throw new Error(`Failed to retrieve newly created repo with id ${result.lastInsertRowid}`)
|
||||
}
|
||||
return newRepo
|
||||
} catch (error: any) {
|
||||
if (error.message?.includes('UNIQUE constraint failed') || error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
|
||||
const conflictRepo = repo.isLocal
|
||||
? getRepoByLocalPath(db, normalizedPath)
|
||||
: getRepoByUrlAndBranch(db, repo.repoUrl!, repo.branch)
|
||||
|
||||
if (conflictRepo) {
|
||||
return conflictRepo
|
||||
}
|
||||
|
||||
const identifier = repo.isLocal ? `path '${normalizedPath}'` : `url '${repo.repoUrl}' branch '${repo.branch || 'default'}'`
|
||||
throw new Error(`Repository with ${identifier} already exists but could not be retrieved. This may indicate database corruption.`)
|
||||
}
|
||||
|
||||
throw new Error(`Failed to create repository: ${error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
export function getRepoById(db: Database, id: number): Repo | null {
|
||||
@@ -87,6 +112,13 @@ export function getRepoByUrlAndBranch(db: Database, repoUrl: string, branch?: st
|
||||
return row ? rowToRepo(row) : null
|
||||
}
|
||||
|
||||
export function getRepoByLocalPath(db: Database, localPath: string): Repo | null {
|
||||
const stmt = db.prepare('SELECT * FROM repos WHERE local_path = ?')
|
||||
const row = stmt.get(localPath) as RepoRow | undefined
|
||||
|
||||
return row ? rowToRepo(row) : null
|
||||
}
|
||||
|
||||
export function listRepos(db: Database): Repo[] {
|
||||
const stmt = db.prepare('SELECT * FROM repos ORDER BY cloned_at DESC')
|
||||
const rows = stmt.all() as RepoRow[]
|
||||
|
||||
@@ -11,7 +11,7 @@ export function initializeDatabase(dbPath: string = './data/opencode.db'): Datab
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS repos (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_url TEXT NOT NULL,
|
||||
repo_url TEXT,
|
||||
local_path TEXT NOT NULL,
|
||||
branch TEXT,
|
||||
default_branch TEXT,
|
||||
@@ -20,8 +20,7 @@ export function initializeDatabase(dbPath: string = './data/opencode.db'): Datab
|
||||
last_pulled INTEGER,
|
||||
opencode_config_name TEXT,
|
||||
is_worktree BOOLEAN DEFAULT FALSE,
|
||||
|
||||
UNIQUE(repo_url, branch)
|
||||
is_local BOOLEAN DEFAULT FALSE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status);
|
||||
|
||||
@@ -17,18 +17,27 @@ export function createRepoRoutes(database: Database) {
|
||||
app.post('/', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
const { repoUrl, branch, openCodeConfigName, useWorktree } = body
|
||||
const { repoUrl, localPath, branch, openCodeConfigName, useWorktree } = body
|
||||
|
||||
if (!repoUrl) {
|
||||
return c.json({ error: 'repoUrl is required' }, 400)
|
||||
if (!repoUrl && !localPath) {
|
||||
return c.json({ error: 'Either repoUrl or localPath is required' }, 400)
|
||||
}
|
||||
|
||||
const repo = await repoService.cloneRepo(
|
||||
database,
|
||||
repoUrl,
|
||||
branch,
|
||||
useWorktree
|
||||
)
|
||||
let repo
|
||||
if (localPath) {
|
||||
repo = await repoService.initLocalRepo(
|
||||
database,
|
||||
localPath,
|
||||
branch
|
||||
)
|
||||
} else {
|
||||
repo = await repoService.cloneRepo(
|
||||
database,
|
||||
repoUrl!,
|
||||
branch,
|
||||
useWorktree
|
||||
)
|
||||
}
|
||||
|
||||
if (openCodeConfigName) {
|
||||
const settingsService = new SettingsService(database)
|
||||
|
||||
+116
-14
@@ -8,6 +8,86 @@ import { SettingsService } from './settings'
|
||||
import { getReposPath } from '@opencode-webui/shared'
|
||||
import path from 'path'
|
||||
|
||||
export async function initLocalRepo(
|
||||
database: Database,
|
||||
localPath: string,
|
||||
branch?: string
|
||||
): Promise<Repo> {
|
||||
const normalizedPath = localPath.replace(/\/+$/, '')
|
||||
const fullPath = path.resolve(getReposPath(), normalizedPath)
|
||||
|
||||
const existing = db.getRepoByLocalPath(database, normalizedPath)
|
||||
if (existing) {
|
||||
logger.info(`Local repo already exists in database: ${normalizedPath}`)
|
||||
return existing
|
||||
}
|
||||
|
||||
const createRepoInput: CreateRepoInput = {
|
||||
localPath: normalizedPath,
|
||||
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: ${normalizedPath} (id: ${repo.id})`)
|
||||
} catch (error: any) {
|
||||
logger.error(`Failed to create database record for local repo: ${normalizedPath}`, error)
|
||||
throw new Error(`Failed to register local repository '${normalizedPath}': ${error.message}`)
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureDirectoryExists(fullPath)
|
||||
directoryCreated = true
|
||||
logger.info(`Created directory for local repo: ${fullPath}`)
|
||||
|
||||
logger.info(`Initializing git repository: ${fullPath}`)
|
||||
await executeCommand(['git', 'init'], fullPath)
|
||||
|
||||
if (branch && branch !== 'main') {
|
||||
await executeCommand(['git', '-C', fullPath, 'checkout', '-b', branch])
|
||||
}
|
||||
|
||||
const isGitRepo = await executeCommand(['git', '-C', fullPath, '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: ${normalizedPath}`)
|
||||
return { ...repo, cloneStatus: 'ready' }
|
||||
} catch (error: any) {
|
||||
logger.error(`Failed to initialize local repo, rolling back: ${normalizedPath}`, 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) {
|
||||
try {
|
||||
await executeCommand(['rm', '-rf', normalizedPath], getReposPath())
|
||||
logger.info(`Rolled back directory: ${normalizedPath}`)
|
||||
} catch (fsError: any) {
|
||||
logger.error(`Failed to rollback directory ${normalizedPath}:`, fsError)
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Failed to initialize local repository '${normalizedPath}': ${error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function cloneRepo(
|
||||
database: Database,
|
||||
repoUrl: string,
|
||||
@@ -229,13 +309,18 @@ export async function cloneRepo(
|
||||
}
|
||||
|
||||
export async function getCurrentBranch(repo: Repo): Promise<string | null> {
|
||||
const repoPath = path.resolve(getReposPath(), repo.localPath)
|
||||
|
||||
try {
|
||||
const repoPath = path.resolve(getReposPath(), repo.localPath)
|
||||
const currentBranch = await executeCommand(['git', '-C', repoPath, 'rev-parse', '--abbrev-ref', 'HEAD'])
|
||||
return currentBranch.trim()
|
||||
} catch (error: any) {
|
||||
logger.warn(`Failed to get current branch for repo ${repo.id}:`, error.message)
|
||||
return null
|
||||
} catch {
|
||||
try {
|
||||
const symbolicRef = await executeCommand(['git', '-C', repoPath, 'symbolic-ref', '--short', 'HEAD'])
|
||||
return symbolicRef.trim()
|
||||
} catch {
|
||||
return repo.branch || repo.defaultBranch || null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,15 +328,25 @@ export async function listBranches(repo: Repo): Promise<{ local: string[], remot
|
||||
try {
|
||||
const repoPath = path.resolve(getReposPath(), repo.localPath)
|
||||
|
||||
await executeCommand(['git', '-C', repoPath, 'fetch', '--all'])
|
||||
if (!repo.isLocal) {
|
||||
await executeCommand(['git', '-C', repoPath, 'fetch', '--all'])
|
||||
}
|
||||
|
||||
const localBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '--format=%(refname:short)'])
|
||||
const localBranches = localBranchesOutput.trim().split('\n').filter(b => b.trim())
|
||||
|
||||
const remoteBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '-r', '--format=%(refname:short)'])
|
||||
const remoteBranches = remoteBranchesOutput.trim().split('\n')
|
||||
.filter(b => b.trim() && !b.includes('HEAD'))
|
||||
.map(b => b.replace('origin/', ''))
|
||||
let remoteBranches: string[] = []
|
||||
if (!repo.isLocal) {
|
||||
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'))
|
||||
.map(b => b.replace('origin/', ''))
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to get remote branches for repo ${repo.id}:`, error)
|
||||
remoteBranches = []
|
||||
}
|
||||
}
|
||||
|
||||
const current = await getCurrentBranch(repo)
|
||||
|
||||
@@ -321,6 +416,11 @@ export async function pullRepo(database: Database, repoId: number): Promise<void
|
||||
throw new Error(`Repo not found: ${repoId}`)
|
||||
}
|
||||
|
||||
if (repo.isLocal) {
|
||||
logger.info(`Skipping pull for local repo: ${repo.localPath}`)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
logger.info(`Pulling repo: ${repo.repoUrl}`)
|
||||
await executeCommand(['git', '-C', path.resolve(getReposPath(), repo.localPath), 'pull'])
|
||||
@@ -339,15 +439,17 @@ export async function deleteRepoFiles(database: Database, repoId: number): Promi
|
||||
throw new Error(`Repo not found: ${repoId}`)
|
||||
}
|
||||
|
||||
const repoIdentifier = repo.repoUrl || repo.localPath
|
||||
|
||||
try {
|
||||
logger.info(`Deleting repo files: ${repo.repoUrl}`)
|
||||
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) {
|
||||
if (repo.isWorktree && repo.branch && repo.repoUrl) {
|
||||
const repoName = extractRepoName(repo.repoUrl)
|
||||
const baseRepoPath = path.resolve(getReposPath(), repoName)
|
||||
|
||||
@@ -391,7 +493,7 @@ export async function deleteRepoFiles(database: Database, repoId: number): Promi
|
||||
}
|
||||
|
||||
// If this was a worktree, also prune the base repo to clean up any remaining references
|
||||
if (repo.isWorktree && repo.branch) {
|
||||
if (repo.isWorktree && repo.branch && repo.repoUrl) {
|
||||
const repoName = extractRepoName(repo.repoUrl)
|
||||
const baseRepoPath = path.resolve(getReposPath(), repoName)
|
||||
|
||||
@@ -404,9 +506,9 @@ export async function deleteRepoFiles(database: Database, repoId: number): Promi
|
||||
}
|
||||
|
||||
db.deleteRepo(database, repoId)
|
||||
logger.info(`Repo deleted successfully: ${repo.repoUrl}`)
|
||||
logger.info(`Repo deleted successfully: ${repoIdentifier}`)
|
||||
} catch (error: any) {
|
||||
logger.error(`Failed to delete repo: ${repo.repoUrl}`, error)
|
||||
logger.error(`Failed to delete repo: ${repoIdentifier}`, error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,11 +7,12 @@ export interface Repo extends BaseRepo {
|
||||
}
|
||||
|
||||
export interface CreateRepoInput {
|
||||
repoUrl: string
|
||||
repoUrl?: string
|
||||
localPath: string
|
||||
branch?: string
|
||||
defaultBranch: string
|
||||
cloneStatus: 'cloning' | 'ready' | 'error'
|
||||
clonedAt: number
|
||||
isWorktree?: boolean
|
||||
isLocal?: boolean
|
||||
}
|
||||
Reference in new issue
Block a user