mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
Add GitHub token environment variable support and improve git operations
This commit is contained in:
1 parent
025b2990ed
commit
af0dcac7c8
11 files changed
+125
-21
No files matched your search
@@ -135,6 +135,7 @@ try {
|
||||
await ensureDefaultConfigExists()
|
||||
await syncDefaultConfigToDisk()
|
||||
|
||||
opencodeServerManager.setDatabase(db)
|
||||
await opencodeServerManager.start()
|
||||
logger.info(`OpenCode server running on port ${opencodeServerManager.getPort()}`)
|
||||
} catch (error) {
|
||||
|
||||
@@ -79,8 +79,18 @@ export function createSettingsRoutes(db: Database) {
|
||||
const body = await c.req.json()
|
||||
const validated = UpdateSettingsSchema.parse(body)
|
||||
|
||||
const currentSettings = settingsService.getSettings(userId)
|
||||
const settings = settingsService.updateSettings(validated.preferences, userId)
|
||||
return c.json(settings)
|
||||
|
||||
let serverRestarted = false
|
||||
if (validated.preferences.gitToken !== undefined &&
|
||||
validated.preferences.gitToken !== currentSettings.preferences.gitToken) {
|
||||
logger.info('GitHub token changed, restarting OpenCode server')
|
||||
await opencodeServerManager.restart()
|
||||
serverRestarted = true
|
||||
}
|
||||
|
||||
return c.json({ ...settings, serverRestarted })
|
||||
} catch (error) {
|
||||
logger.error('Failed to update settings:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { logger } from '../utils/logger'
|
||||
import { SettingsService } from './settings'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import path from 'path'
|
||||
|
||||
async function hasCommits(repoPath: string): Promise<boolean> {
|
||||
@@ -11,6 +13,33 @@ async function hasCommits(repoPath: string): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
function getGitEnvironment(database: Database): Record<string, string> {
|
||||
try {
|
||||
const settingsService = new SettingsService(database)
|
||||
const settings = settingsService.getSettings('default')
|
||||
const gitToken = settings.preferences.gitToken
|
||||
|
||||
if (gitToken) {
|
||||
return {
|
||||
GITHUB_TOKEN: gitToken,
|
||||
GIT_ASKPASS: 'echo',
|
||||
GIT_TERMINAL_PROMPT: '0'
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
GIT_ASKPASS: 'echo',
|
||||
GIT_TERMINAL_PROMPT: '0'
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to get git token from settings:', error)
|
||||
return {
|
||||
GIT_ASKPASS: 'echo',
|
||||
GIT_TERMINAL_PROMPT: '0'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type GitFileStatusType = 'modified' | 'added' | 'deleted' | 'renamed' | 'untracked' | 'copied'
|
||||
|
||||
export interface GitFileStatus {
|
||||
@@ -123,10 +152,11 @@ function parsePorcelainV2(output: string): { branch: string; ahead: number; behi
|
||||
return { branch, ahead, behind, files }
|
||||
}
|
||||
|
||||
export async function getGitStatus(repoPath: string): Promise<GitStatusResponse> {
|
||||
export async function getGitStatus(repoPath: string, database?: Database): Promise<GitStatusResponse> {
|
||||
try {
|
||||
const fullPath = path.resolve(repoPath)
|
||||
const output = await executeCommand(['git', '-C', fullPath, 'status', '--porcelain=v2', '--branch'])
|
||||
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)
|
||||
|
||||
return {
|
||||
@@ -142,10 +172,10 @@ export async function getGitStatus(repoPath: string): Promise<GitStatusResponse>
|
||||
}
|
||||
}
|
||||
|
||||
export async function getFileDiff(repoPath: string, filePath: string): Promise<FileDiffResponse> {
|
||||
export async function getFileDiff(repoPath: string, filePath: string, database?: Database): Promise<FileDiffResponse> {
|
||||
try {
|
||||
const fullRepoPath = path.resolve(repoPath)
|
||||
const status = await getGitStatus(repoPath)
|
||||
const status = await getGitStatus(repoPath, database)
|
||||
const fileStatus = status.files.find(f => f.path === filePath)
|
||||
|
||||
if (!fileStatus) {
|
||||
@@ -164,9 +194,11 @@ export async function getFileDiff(repoPath: string, filePath: string): Promise<F
|
||||
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])
|
||||
const content = await executeCommand(['git', '-C', fullRepoPath, 'diff', '--no-index', '--', '/dev/null', filePath], { env })
|
||||
diff = content
|
||||
} catch (error: any) {
|
||||
if (error.message?.includes('exit code 1') || error.message?.includes('Command failed with code 1')) {
|
||||
@@ -181,7 +213,7 @@ export async function getFileDiff(repoPath: string, filePath: string): Promise<F
|
||||
try {
|
||||
const repoHasCommits = await hasCommits(fullRepoPath)
|
||||
if (repoHasCommits) {
|
||||
diff = await executeCommand(['git', '-C', fullRepoPath, 'diff', 'HEAD', '--', filePath])
|
||||
diff = await executeCommand(['git', '-C', fullRepoPath, 'diff', 'HEAD', '--', filePath], { env })
|
||||
} else {
|
||||
diff = `New file (no commits yet): ${filePath}`
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { spawn, execSync } from 'child_process'
|
||||
import path from 'path'
|
||||
import { logger } from '../utils/logger'
|
||||
import { SettingsService } from './settings'
|
||||
import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-webui/shared'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
|
||||
const OPENCODE_SERVER_DIRECTORY = getWorkspacePath()
|
||||
@@ -12,9 +14,14 @@ class OpenCodeServerManager {
|
||||
private serverProcess: any = null
|
||||
private serverPid: number | null = null
|
||||
private isHealthy: boolean = false
|
||||
private db: Database | null = null
|
||||
|
||||
private constructor() {}
|
||||
|
||||
setDatabase(db: Database) {
|
||||
this.db = db
|
||||
}
|
||||
|
||||
static getInstance(): OpenCodeServerManager {
|
||||
if (!OpenCodeServerManager.instance) {
|
||||
OpenCodeServerManager.instance = new OpenCodeServerManager()
|
||||
@@ -30,6 +37,17 @@ class OpenCodeServerManager {
|
||||
|
||||
const isDevelopment = ENV.SERVER.NODE_ENV !== 'production'
|
||||
|
||||
let gitToken = ''
|
||||
if (this.db) {
|
||||
try {
|
||||
const settingsService = new SettingsService(this.db)
|
||||
const settings = settingsService.getSettings('default')
|
||||
gitToken = settings.preferences.gitToken || ''
|
||||
} catch (error) {
|
||||
logger.warn('Failed to get git token from settings:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const existingProcesses = await this.findProcessesByPort(OPENCODE_SERVER_PORT)
|
||||
if (existingProcesses.length > 0) {
|
||||
logger.info(`OpenCode server already running on port ${OPENCODE_SERVER_PORT}`)
|
||||
@@ -79,7 +97,10 @@ class OpenCodeServerManager {
|
||||
env: {
|
||||
...process.env,
|
||||
XDG_DATA_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.opencode/state'),
|
||||
OPENCODE_CONFIG: OPENCODE_CONFIG_PATH
|
||||
OPENCODE_CONFIG: OPENCODE_CONFIG_PATH,
|
||||
GITHUB_TOKEN: gitToken,
|
||||
GIT_ASKPASS: 'echo',
|
||||
GIT_TERMINAL_PROMPT: '0'
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
@@ -17,6 +17,13 @@ async function hasCommits(repoPath: string): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
function getAuthenticatedUrl(repoUrl: string, gitToken: string): string {
|
||||
if (gitToken && repoUrl.startsWith('https://github.com')) {
|
||||
return repoUrl.replace('https://', `https://${gitToken}@`)
|
||||
}
|
||||
return repoUrl
|
||||
}
|
||||
|
||||
async function safeGetCurrentBranch(repoPath: string): Promise<string | null> {
|
||||
try {
|
||||
const repoHasCommits = await hasCommits(repoPath)
|
||||
@@ -75,7 +82,18 @@ export async function initLocalRepo(
|
||||
logger.info(`Created directory for local repo: ${fullPath}`)
|
||||
|
||||
logger.info(`Initializing git repository: ${fullPath}`)
|
||||
await executeCommand(['git', 'init'], fullPath)
|
||||
const settingsService = new SettingsService(database)
|
||||
const settings = settingsService.getSettings('default')
|
||||
const gitToken = settings.preferences.gitToken
|
||||
const env: Record<string, string> = gitToken ?
|
||||
{
|
||||
GITHUB_TOKEN: gitToken,
|
||||
GIT_ASKPASS: 'echo',
|
||||
GIT_TERMINAL_PROMPT: '0'
|
||||
} :
|
||||
{ GIT_ASKPASS: 'echo', GIT_TERMINAL_PROMPT: '0' }
|
||||
|
||||
await executeCommand(['git', 'init'], { cwd: fullPath })
|
||||
|
||||
if (branch && branch !== 'main') {
|
||||
await executeCommand(['git', '-C', fullPath, 'checkout', '-b', branch])
|
||||
@@ -158,9 +176,7 @@ export async function cloneRepo(
|
||||
const settings = settingsService.getSettings('default')
|
||||
const gitToken = settings.preferences.gitToken
|
||||
|
||||
let cloneUrl = gitToken && repoUrl.startsWith('https://github.com')
|
||||
? repoUrl.replace('https://', `https://${gitToken}@`)
|
||||
: repoUrl
|
||||
const cloneUrl = getAuthenticatedUrl(repoUrl, gitToken || '')
|
||||
|
||||
if (shouldUseWorktree) {
|
||||
logger.info(`Creating worktree for branch: ${branch}`)
|
||||
@@ -201,7 +217,7 @@ export async function cloneRepo(
|
||||
}
|
||||
|
||||
try {
|
||||
const cloneCmd = ['git', 'clone', '-b', branch, cloneUrl, worktreeDirName]
|
||||
const cloneCmd = ['git', 'clone', '-b', branch, repoUrl, worktreeDirName]
|
||||
await executeCommand(cloneCmd, getReposPath())
|
||||
} catch (error: any) {
|
||||
if (error.message.includes('destination path') && error.message.includes('already exists')) {
|
||||
@@ -210,7 +226,7 @@ export async function cloneRepo(
|
||||
}
|
||||
|
||||
logger.info(`Branch '${branch}' not found during clone, cloning default branch and creating branch locally`)
|
||||
const cloneCmd = ['git', 'clone', cloneUrl, worktreeDirName]
|
||||
const cloneCmd = ['git', 'clone', repoUrl, worktreeDirName]
|
||||
await executeCommand(cloneCmd, getReposPath())
|
||||
let localBranchExists = 'missing'
|
||||
try {
|
||||
@@ -292,8 +308,8 @@ export async function cloneRepo(
|
||||
|
||||
try {
|
||||
const cloneCmd = branch
|
||||
? ['git', 'clone', '-b', branch, cloneUrl, worktreeDirName]
|
||||
: ['git', 'clone', cloneUrl, worktreeDirName]
|
||||
? ['git', 'clone', '-b', branch, repoUrl, worktreeDirName]
|
||||
: ['git', 'clone', repoUrl, worktreeDirName]
|
||||
|
||||
await executeCommand(cloneCmd, getReposPath())
|
||||
} catch (error: any) {
|
||||
@@ -304,7 +320,7 @@ export async function cloneRepo(
|
||||
|
||||
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`)
|
||||
const cloneCmd = ['git', 'clone', cloneUrl, worktreeDirName]
|
||||
const cloneCmd = ['git', 'clone', repoUrl, worktreeDirName]
|
||||
await executeCommand(cloneCmd, getReposPath())
|
||||
let localBranchExists = 'missing'
|
||||
try {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { logger } from './logger'
|
||||
interface ExecuteCommandOptions {
|
||||
cwd?: string
|
||||
silent?: boolean
|
||||
env?: Record<string, string>
|
||||
}
|
||||
|
||||
export async function executeCommand(
|
||||
@@ -19,7 +20,8 @@ export async function executeCommand(
|
||||
|
||||
const proc: ChildProcess = spawn(command || '', cmdArgs, {
|
||||
cwd: options.cwd,
|
||||
shell: false
|
||||
shell: false,
|
||||
env: { ...process.env, ...options.env }
|
||||
})
|
||||
|
||||
let stdout = ''
|
||||
|
||||
Reference in new issue
Block a user