Add GitHub token environment variable support and improve git operations

This commit is contained in:
Chris Scott committed 2025-11-30 21:05:30 -05:00
1 parent 025b2990ed
commit af0dcac7c8
11 files changed
+125 -21

No files matched your search

+1
View File
@@ -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) {
+11 -1
View File
@@ -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) {
+38 -6
View File
@@ -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}`
}
+22 -1
View File
@@ -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'
}
}
)
+25 -9
View File
@@ -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 {
+3 -1
View File
@@ -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 = ''
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -50,7 +50,7 @@
"@types/react-dom": "^19.2.2",
"@vitejs/plugin-react": "^5.0.4",
"autoprefixer": "^10.4.21",
"eslint": "^9.36.0",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.22",
"globals": "^16.4.0",
+1
View File
@@ -46,6 +46,7 @@ export interface UserPreferences {
export interface SettingsResponse {
preferences: UserPreferences
updatedAt: number
serverRestarted?: boolean
}
export interface UpdateSettingsRequest {
@@ -6,9 +6,10 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
import { Switch } from '@/components/ui/switch'
import { Input } from '@/components/ui/input'
import { TTSSettings } from './TTSSettings'
import { showToast } from '@/lib/toast'
export function GeneralSettings() {
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
const { preferences, isLoading, updateSettings, updateSettingsAsync, isUpdating } = useSettings()
const [gitToken, setGitToken] = useState('')
@@ -120,7 +121,17 @@ export function GeneralSettings() {
placeholder="ghp_..."
value={gitToken}
onChange={(e) => setGitToken(e.target.value)}
onBlur={() => updateSettings({ gitToken })}
onBlur={async () => {
if (gitToken !== preferences?.gitToken) {
showToast.loading('Restarting OpenCode server...', { id: 'restart-server' })
try {
await updateSettingsAsync({ gitToken })
showToast.success('GitHub token updated', { id: 'restart-server' })
} catch {
showToast.error('Failed to update GitHub token', { id: 'restart-server' })
}
}
}}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
<p className="text-sm text-muted-foreground">
+10
View File
@@ -10,6 +10,12 @@ interface ToastOptions {
id?: string | number
}
interface PromiseToastMessages {
loading: string
success: string
error: string
}
export const showToast = {
success: (message: string, options?: ToastOptions) => {
return toast.success(message, options)
@@ -31,6 +37,10 @@ export const showToast = {
return toast.loading(message, options)
},
promise: <T>(promise: Promise<T>, messages: PromiseToastMessages) => {
return toast.promise(promise, messages)
},
dismiss: (id?: string | number) => {
toast.dismiss(id)
}