mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Replace global git config with environment-based identity management
This commit is contained in:
1 parent
30e5a14e43
commit
b7e5390ab7
11 files changed
+617
-225
No files matched your search
@@ -9,7 +9,6 @@
|
||||
"build": "bun build src/index.ts --outdir=dist --target=bun",
|
||||
"test": "vitest",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:coverage": "vitest --coverage",
|
||||
"test:watch": "vitest --watch"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -12,10 +12,6 @@ import {
|
||||
import { logger } from '../utils/logger'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { DEFAULT_AGENTS_MD } from '../index'
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const UpdateSettingsSchema = z.object({
|
||||
preferences: UserPreferencesSchema.partial(),
|
||||
@@ -83,32 +79,18 @@ export function createSettingsRoutes(db: Database) {
|
||||
const settings = settingsService.updateSettings(validated.preferences, userId)
|
||||
|
||||
let serverRestarted = false
|
||||
if (validated.preferences.gitCredentials !== undefined) {
|
||||
const currentCreds = JSON.stringify(currentSettings.preferences.gitCredentials || [])
|
||||
const newCreds = JSON.stringify(validated.preferences.gitCredentials)
|
||||
if (currentCreds !== newCreds) {
|
||||
logger.info('Git credentials changed, restarting OpenCode server')
|
||||
await opencodeServerManager.restart()
|
||||
serverRestarted = true
|
||||
}
|
||||
}
|
||||
|
||||
if (validated.preferences.gitIdentity !== undefined) {
|
||||
const identity = validated.preferences.gitIdentity
|
||||
if (identity.name) {
|
||||
await execFileAsync('git', ['config', '--global', 'user.name', identity.name])
|
||||
logger.info(`Set global git user.name: ${identity.name}`)
|
||||
} else {
|
||||
await execFileAsync('git', ['config', '--global', '--unset', 'user.name']).catch(() => {})
|
||||
logger.info('Unset global git user.name')
|
||||
}
|
||||
if (identity.email) {
|
||||
await execFileAsync('git', ['config', '--global', 'user.email', identity.email])
|
||||
logger.info(`Set global git user.email: ${identity.email}`)
|
||||
} else {
|
||||
await execFileAsync('git', ['config', '--global', '--unset', 'user.email']).catch(() => {})
|
||||
logger.info('Unset global git user.email')
|
||||
}
|
||||
|
||||
const credentialsChanged = validated.preferences.gitCredentials !== undefined &&
|
||||
JSON.stringify(currentSettings.preferences.gitCredentials || []) !== JSON.stringify(validated.preferences.gitCredentials)
|
||||
|
||||
const identityChanged = validated.preferences.gitIdentity !== undefined &&
|
||||
JSON.stringify(currentSettings.preferences.gitIdentity || {}) !== JSON.stringify(validated.preferences.gitIdentity)
|
||||
|
||||
if (credentialsChanged || identityChanged) {
|
||||
const changeType = [credentialsChanged && 'credentials', identityChanged && 'identity'].filter(Boolean).join(' and ')
|
||||
logger.info(`Git ${changeType} changed, restarting OpenCode server`)
|
||||
await opencodeServerManager.restart()
|
||||
serverRestarted = true
|
||||
}
|
||||
|
||||
return c.json({ ...settings, serverRestarted })
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { spawn, execSync } from 'child_process'
|
||||
import path from 'path'
|
||||
import { logger } from '../utils/logger'
|
||||
import { createGitEnv, createNoPromptGitEnv } from '../utils/git-auth'
|
||||
import { createGitEnv, createGitIdentityEnv, resolveGitIdentity } from '../utils/git-auth'
|
||||
import { SettingsService } from './settings'
|
||||
import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
@@ -57,13 +57,20 @@ class OpenCodeServerManager {
|
||||
const isDevelopment = ENV.SERVER.NODE_ENV !== 'production'
|
||||
|
||||
let gitCredentials: GitCredential[] = []
|
||||
let gitIdentityEnv: Record<string, string> = {}
|
||||
if (this.db) {
|
||||
try {
|
||||
const settingsService = new SettingsService(this.db)
|
||||
const settings = settingsService.getSettings('default')
|
||||
gitCredentials = settings.preferences.gitCredentials || []
|
||||
|
||||
const identity = await resolveGitIdentity(settings.preferences.gitIdentity, gitCredentials)
|
||||
if (identity) {
|
||||
gitIdentityEnv = createGitIdentityEnv(identity)
|
||||
logger.info(`Git identity resolved: ${identity.name} <${identity.email}>`)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to get git credentials from settings:', error)
|
||||
logger.warn('Failed to get git settings:', error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,6 +127,7 @@ class OpenCodeServerManager {
|
||||
env: {
|
||||
...process.env,
|
||||
...gitEnv,
|
||||
...gitIdentityEnv,
|
||||
XDG_DATA_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.opencode/state'),
|
||||
XDG_CONFIG_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.config'),
|
||||
OPENCODE_CONFIG: OPENCODE_CONFIG_PATH,
|
||||
|
||||
@@ -108,35 +108,6 @@ function getGitEnv(database: Database): Record<string, string> {
|
||||
}
|
||||
}
|
||||
|
||||
interface GitIdentity {
|
||||
name: string
|
||||
email: string
|
||||
}
|
||||
|
||||
function getGitIdentity(database: Database): GitIdentity {
|
||||
const defaultIdentity: GitIdentity = {
|
||||
name: 'OpenCode User',
|
||||
email: 'opencode@localhost'
|
||||
}
|
||||
|
||||
try {
|
||||
const settingsService = new SettingsService(database)
|
||||
const settings = settingsService.getSettings('default')
|
||||
const identity = settings.preferences.gitIdentity
|
||||
|
||||
if (identity?.name && identity?.email) {
|
||||
return identity
|
||||
}
|
||||
|
||||
return {
|
||||
name: identity?.name || defaultIdentity.name,
|
||||
email: identity?.email || defaultIdentity.email
|
||||
}
|
||||
} catch {
|
||||
return defaultIdentity
|
||||
}
|
||||
}
|
||||
|
||||
export async function initLocalRepo(
|
||||
database: Database,
|
||||
localPath: string,
|
||||
@@ -180,27 +151,6 @@ export async function initLocalRepo(
|
||||
|
||||
await executeCommand(['git', 'init'], { cwd: fullPath })
|
||||
|
||||
const hasGlobalEmail = await executeCommand(['git', 'config', '--global', 'user.email'], { silent: true })
|
||||
.then(email => email.trim().length > 0)
|
||||
.catch(() => false)
|
||||
const hasGlobalName = await executeCommand(['git', 'config', '--global', 'user.name'], { silent: true })
|
||||
.then(name => name.trim().length > 0)
|
||||
.catch(() => false)
|
||||
|
||||
if (!hasGlobalEmail || !hasGlobalName) {
|
||||
const identity = getGitIdentity(database)
|
||||
if (!hasGlobalEmail) {
|
||||
await executeCommand(['git', 'config', '--global', 'user.email', identity.email])
|
||||
logger.info(`Set global git user.email: ${identity.email}`)
|
||||
}
|
||||
if (!hasGlobalName) {
|
||||
await executeCommand(['git', 'config', '--global', 'user.name', identity.name])
|
||||
logger.info(`Set global git user.name: ${identity.name}`)
|
||||
}
|
||||
}
|
||||
|
||||
await executeCommand(['git', '-C', fullPath, 'commit', '--allow-empty', '-m', 'Initial commit'])
|
||||
|
||||
if (branch && branch !== 'main') {
|
||||
await executeCommand(['git', '-C', fullPath, 'checkout', '-b', branch])
|
||||
}
|
||||
|
||||
@@ -77,3 +77,110 @@ export function createGitEnv(credentials: GitCredential[]): Record<string, strin
|
||||
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)
|
||||
return parsed.hostname.toLowerCase() === 'github.com'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}) || null
|
||||
}
|
||||
|
||||
export interface GitIdentity {
|
||||
name: string
|
||||
email: string
|
||||
}
|
||||
|
||||
export async function resolveGitIdentity(
|
||||
manualIdentity: { name?: string; email?: string } | undefined,
|
||||
credentials: GitCredential[]
|
||||
): Promise<GitIdentity | null> {
|
||||
if (manualIdentity?.name && manualIdentity?.email) {
|
||||
return { name: manualIdentity.name, email: manualIdentity.email }
|
||||
}
|
||||
|
||||
const githubCred = findGitHubCredential(credentials)
|
||||
if (githubCred) {
|
||||
const githubUser = await fetchGitHubUserInfo(githubCred.token)
|
||||
if (githubUser) {
|
||||
return {
|
||||
name: manualIdentity?.name || githubUser.name || githubUser.login,
|
||||
email: manualIdentity?.email || githubUser.email
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (manualIdentity?.name || manualIdentity?.email) {
|
||||
return {
|
||||
name: manualIdentity.name || '',
|
||||
email: manualIdentity.email || ''
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function createGitIdentityEnv(identity: GitIdentity): Record<string, string> {
|
||||
return {
|
||||
GIT_AUTHOR_NAME: identity.name,
|
||||
GIT_AUTHOR_EMAIL: identity.email,
|
||||
GIT_COMMITTER_NAME: identity.name,
|
||||
GIT_COMMITTER_EMAIL: identity.email
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchGitHubUserInfo(token: string): Promise<GitHubUserInfo | null> {
|
||||
try {
|
||||
const [userResponse, emailsResponse] = await Promise.all([
|
||||
fetch('https://api.github.com/user', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'X-GitHub-Api-Version': '2022-11-28'
|
||||
}
|
||||
}),
|
||||
fetch('https://api.github.com/user/emails', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'X-GitHub-Api-Version': '2022-11-28'
|
||||
}
|
||||
})
|
||||
])
|
||||
|
||||
if (!userResponse.ok) return null
|
||||
|
||||
const data = await userResponse.json() as { login: string; name: string | null; id: number }
|
||||
|
||||
if (!data.id || !data.login) return null
|
||||
|
||||
let email = `${data.id}+${data.login}@users.noreply.github.com`
|
||||
|
||||
if (emailsResponse.ok) {
|
||||
const emails = await emailsResponse.json() as Array<{ email: string; primary: boolean; verified: boolean }>
|
||||
const primaryEmail = emails.find(e => e.primary && e.verified)
|
||||
if (primaryEmail?.email) {
|
||||
email = primaryEmail.email
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name: data.name,
|
||||
email,
|
||||
login: data.login
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,15 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import * as fs from 'fs/promises'
|
||||
import { logger } from '../../src/utils/logger'
|
||||
|
||||
const mockMkdir = vi.fn()
|
||||
const mockReadFile = vi.fn()
|
||||
const mockWriteFile = vi.fn()
|
||||
const mockReaddir = vi.fn()
|
||||
const mockStat = vi.fn()
|
||||
const mockUnlink = vi.fn()
|
||||
|
||||
const mockLogger = {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
}
|
||||
|
||||
vi.mock('fs/promises', async () => {
|
||||
return {
|
||||
mkdir: mockMkdir,
|
||||
readFile: mockReadFile,
|
||||
writeFile: mockWriteFile,
|
||||
readdir: mockReaddir,
|
||||
stat: mockStat,
|
||||
unlink: mockUnlink,
|
||||
}
|
||||
})
|
||||
vi.mock('fs/promises', () => ({
|
||||
mkdir: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn(),
|
||||
@@ -30,11 +17,20 @@ vi.mock('bun:sqlite', () => ({
|
||||
vi.mock('../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn(),
|
||||
}))
|
||||
vi.mock('../../src/utils/logger', async () => {
|
||||
return {
|
||||
logger: mockLogger,
|
||||
}
|
||||
})
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockMkdir = fs.mkdir as any
|
||||
const mockReadFile = fs.readFile as any
|
||||
const mockWriteFile = fs.writeFile as any
|
||||
const mockReaddir = fs.readdir as any
|
||||
const mockStat = fs.stat as any
|
||||
const mockUnlink = fs.unlink as any
|
||||
|
||||
import { createTTSRoutes, cleanupExpiredCache, getCacheStats, generateCacheKey, ensureCacheDir, getCachedAudio, getCacheSize, cleanupOldestFiles } from '../../src/routes/tts'
|
||||
|
||||
@@ -100,23 +96,19 @@ describe('TTS Routes', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('getCachedAudio', () => {
|
||||
describe('getCachedAudio', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
it('should return cached audio when file exists and is not expired', async () => {
|
||||
const cacheKey = 'test-key'
|
||||
const audioBuffer = Buffer.from('audio data')
|
||||
|
||||
|
||||
mockStat.mockResolvedValue({
|
||||
mtimeMs: Date.now() - 1000, // 1 second ago (not expired)
|
||||
mtimeMs: Date.now() - 1000,
|
||||
size: 1024,
|
||||
})
|
||||
} as any)
|
||||
mockReadFile.mockResolvedValue(audioBuffer)
|
||||
|
||||
const result = await getCachedAudio(cacheKey)
|
||||
@@ -129,11 +121,11 @@ beforeEach(() => {
|
||||
|
||||
it('should return null when cached file has expired', async () => {
|
||||
const cacheKey = 'test-key'
|
||||
|
||||
|
||||
mockStat.mockResolvedValue({
|
||||
mtimeMs: Date.now() - 25 * 60 * 60 * 1000, // 25 hours ago (expired)
|
||||
mtimeMs: Date.now() - 25 * 60 * 60 * 1000,
|
||||
size: 1024,
|
||||
})
|
||||
} as any)
|
||||
mockUnlink.mockResolvedValue(undefined)
|
||||
|
||||
const result = await getCachedAudio(cacheKey)
|
||||
@@ -157,10 +149,10 @@ beforeEach(() => {
|
||||
|
||||
describe('getCacheSize', () => {
|
||||
it('should calculate correct cache size', async () => {
|
||||
mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3', 'readme.txt'])
|
||||
mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3', 'readme.txt'] as any)
|
||||
mockStat
|
||||
.mockResolvedValueOnce({ size: 1024, mtimeMs: Date.now() })
|
||||
.mockResolvedValueOnce({ size: 2048, mtimeMs: Date.now() })
|
||||
.mockResolvedValueOnce({ size: 1024, mtimeMs: Date.now() } as any)
|
||||
.mockResolvedValueOnce({ size: 2048, mtimeMs: Date.now() } as any)
|
||||
|
||||
const size = await getCacheSize()
|
||||
|
||||
@@ -178,11 +170,11 @@ beforeEach(() => {
|
||||
|
||||
describe('cleanupMethods', () => {
|
||||
it('should remove oldest files when cache size limit exceeded', async () => {
|
||||
mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3', 'file3.mp3'])
|
||||
mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3', 'file3.mp3'] as any)
|
||||
mockStat
|
||||
.mockResolvedValueOnce({ size: 1024, mtimeMs: 1000 })
|
||||
.mockResolvedValueOnce({ size: 2048, mtimeMs: 2000 })
|
||||
.mockResolvedValueOnce({ size: 1536, mtimeMs: 3000 })
|
||||
.mockResolvedValueOnce({ size: 1024, mtimeMs: 1000 } as any)
|
||||
.mockResolvedValueOnce({ size: 2048, mtimeMs: 2000 } as any)
|
||||
.mockResolvedValueOnce({ size: 1536, mtimeMs: 3000 } as any)
|
||||
mockUnlink.mockResolvedValue(undefined)
|
||||
|
||||
await cleanupOldestFiles(1500) // Need 1500 bytes freed
|
||||
@@ -194,10 +186,10 @@ beforeEach(() => {
|
||||
|
||||
it('should return cache statistics for files', async () => {
|
||||
const currentTime = Date.now()
|
||||
mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3'])
|
||||
mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3'] as any)
|
||||
mockStat
|
||||
.mockResolvedValueOnce({ size: 1024, mtimeMs: currentTime })
|
||||
.mockResolvedValueOnce({ size: 2048, mtimeMs: currentTime })
|
||||
.mockResolvedValueOnce({ size: 1024, mtimeMs: currentTime } as any)
|
||||
.mockResolvedValueOnce({ size: 2048, mtimeMs: currentTime } as any)
|
||||
|
||||
const stats = await getCacheStats()
|
||||
|
||||
@@ -207,11 +199,11 @@ beforeEach(() => {
|
||||
})
|
||||
|
||||
it('should cleanup expired cache files', async () => {
|
||||
mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3', 'expired.mp3'])
|
||||
mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3', 'expired.mp3'] as any)
|
||||
mockStat
|
||||
.mockResolvedValueOnce({ size: 1024, mtimeMs: Date.now() })
|
||||
.mockResolvedValueOnce({ size: 2048, mtimeMs: Date.now() })
|
||||
.mockResolvedValueOnce({ size: 1536, mtimeMs: Date.now() - 25 * 60 * 60 * 1000 })
|
||||
.mockResolvedValueOnce({ size: 1024, mtimeMs: Date.now() } as any)
|
||||
.mockResolvedValueOnce({ size: 2048, mtimeMs: Date.now() } as any)
|
||||
.mockResolvedValueOnce({ size: 1536, mtimeMs: Date.now() - 25 * 60 * 60 * 1000 } as any)
|
||||
mockUnlink.mockResolvedValue(undefined)
|
||||
|
||||
const cleaned = await cleanupExpiredCache()
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { unlink, mkdir } from 'fs/promises'
|
||||
import { promises as fs } from 'fs'
|
||||
import { AuthService } from '../../src/services/auth'
|
||||
|
||||
const readFile = vi.fn()
|
||||
const writeFile = vi.fn()
|
||||
const mkdirSpy = vi.fn()
|
||||
|
||||
vi.mock('fs', () => ({
|
||||
promises: {
|
||||
readFile,
|
||||
writeFile,
|
||||
mkdir: mkdirSpy,
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const readFile = fs.readFile as any
|
||||
const writeFile = fs.writeFile as any
|
||||
const mkdirSpy = fs.mkdir as any
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
getAuthPath: () => '/test/auth.json',
|
||||
ENV: {
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { fetchGitHubUserInfo, findGitHubCredential, resolveGitIdentity, createGitIdentityEnv } from '../../src/utils/git-auth'
|
||||
import type { GitCredential } from '../../src/utils/git-auth'
|
||||
|
||||
describe('fetchGitHubUserInfo', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should use verified primary email when available', async () => {
|
||||
const userResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
login: 'testuser',
|
||||
name: 'Test User',
|
||||
id: 123456
|
||||
})
|
||||
}
|
||||
const emailsResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue([
|
||||
{ email: 'verified@email.com', primary: true, verified: true }
|
||||
])
|
||||
}
|
||||
global.fetch = vi.fn()
|
||||
.mockResolvedValueOnce(userResponse)
|
||||
.mockResolvedValueOnce(emailsResponse)
|
||||
|
||||
const result = await fetchGitHubUserInfo('test_token')
|
||||
|
||||
expect(result?.email).toBe('verified@email.com')
|
||||
expect(result?.name).toBe('Test User')
|
||||
expect(result?.login).toBe('testuser')
|
||||
})
|
||||
|
||||
it('should fallback to noreply email when no verified primary email', async () => {
|
||||
const userResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
login: 'testuser',
|
||||
name: 'Test User',
|
||||
id: 123456
|
||||
})
|
||||
}
|
||||
const emailsResponse = { ok: false }
|
||||
global.fetch = vi.fn()
|
||||
.mockResolvedValueOnce(userResponse)
|
||||
.mockResolvedValueOnce(emailsResponse)
|
||||
|
||||
const result = await fetchGitHubUserInfo('test_token')
|
||||
|
||||
expect(result?.email).toBe('123456+testuser@users.noreply.github.com')
|
||||
})
|
||||
|
||||
it('should fallback to noreply email when emails API returns empty array', async () => {
|
||||
const userResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
login: 'testuser',
|
||||
name: 'Test User',
|
||||
id: 123456
|
||||
})
|
||||
}
|
||||
const emailsResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue([])
|
||||
}
|
||||
global.fetch = vi.fn()
|
||||
.mockResolvedValueOnce(userResponse)
|
||||
.mockResolvedValueOnce(emailsResponse)
|
||||
|
||||
const result = await fetchGitHubUserInfo('test_token')
|
||||
|
||||
expect(result?.email).toBe('123456+testuser@users.noreply.github.com')
|
||||
})
|
||||
|
||||
it('should fallback to noreply email when no verified email in list', async () => {
|
||||
const userResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
login: 'testuser',
|
||||
name: 'Test User',
|
||||
id: 123456
|
||||
})
|
||||
}
|
||||
const emailsResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue([
|
||||
{ email: 'unverified@email.com', primary: false, verified: false }
|
||||
])
|
||||
}
|
||||
global.fetch = vi.fn()
|
||||
.mockResolvedValueOnce(userResponse)
|
||||
.mockResolvedValueOnce(emailsResponse)
|
||||
|
||||
const result = await fetchGitHubUserInfo('test_token')
|
||||
|
||||
expect(result?.email).toBe('123456+testuser@users.noreply.github.com')
|
||||
})
|
||||
|
||||
it('should return null when user API fails', async () => {
|
||||
const userResponse = { ok: false }
|
||||
global.fetch = vi.fn().mockResolvedValueOnce(userResponse)
|
||||
|
||||
const result = await fetchGitHubUserInfo('invalid_token')
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('should return null when user data is missing id', async () => {
|
||||
const userResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
login: 'testuser',
|
||||
name: 'Test User',
|
||||
id: null
|
||||
})
|
||||
}
|
||||
global.fetch = vi.fn().mockResolvedValueOnce(userResponse)
|
||||
|
||||
const result = await fetchGitHubUserInfo('test_token')
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('should return null when user data is missing login', async () => {
|
||||
const userResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
login: null,
|
||||
name: 'Test User',
|
||||
id: 123456
|
||||
})
|
||||
}
|
||||
global.fetch = vi.fn().mockResolvedValueOnce(userResponse)
|
||||
|
||||
const result = await fetchGitHubUserInfo('test_token')
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('should use login as name when name is null', async () => {
|
||||
const userResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
login: 'testuser',
|
||||
name: null,
|
||||
id: 123456
|
||||
})
|
||||
}
|
||||
const emailsResponse = { ok: false }
|
||||
global.fetch = vi.fn()
|
||||
.mockResolvedValueOnce(userResponse)
|
||||
.mockResolvedValueOnce(emailsResponse)
|
||||
|
||||
const result = await fetchGitHubUserInfo('test_token')
|
||||
|
||||
expect(result?.name).toBeNull()
|
||||
expect(result?.login).toBe('testuser')
|
||||
})
|
||||
|
||||
it('should handle network errors gracefully', async () => {
|
||||
global.fetch = vi.fn().mockRejectedValue(new Error('Network error'))
|
||||
|
||||
const result = await fetchGitHubUserInfo('test_token')
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('should make parallel API calls to user and endpoints', async () => {
|
||||
const userResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
login: 'testuser',
|
||||
name: 'Test User',
|
||||
id: 123456
|
||||
})
|
||||
}
|
||||
const emailsResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue([
|
||||
{ email: 'verified@email.com', primary: true, verified: true }
|
||||
])
|
||||
}
|
||||
global.fetch = vi.fn()
|
||||
.mockResolvedValueOnce(userResponse)
|
||||
.mockResolvedValueOnce(emailsResponse)
|
||||
|
||||
await fetchGitHubUserInfo('test_token')
|
||||
|
||||
expect(fetch).toHaveBeenCalledTimes(2)
|
||||
expect(fetch).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'https://api.github.com/user',
|
||||
expect.any(Object)
|
||||
)
|
||||
expect(fetch).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'https://api.github.com/user/emails',
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('findGitHubCredential', () => {
|
||||
it('should find GitHub credential in credentials array', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'gitlab', host: 'https://gitlab.com/', token: 'gitlab-token' },
|
||||
{ name: 'github', host: 'https://github.com/', token: 'github-token' },
|
||||
{ name: 'private', host: 'https://git.example.com/', token: 'private-token' },
|
||||
]
|
||||
|
||||
const result = findGitHubCredential(credentials)
|
||||
|
||||
expect(result).toEqual({
|
||||
name: 'github',
|
||||
host: 'https://github.com/',
|
||||
token: 'github-token'
|
||||
})
|
||||
})
|
||||
|
||||
it('should not find GitHub credential with www subdomain', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://www.github.com/', token: 'github-token' },
|
||||
]
|
||||
|
||||
const result = findGitHubCredential(credentials)
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('should return null when credentials array is empty', () => {
|
||||
const result = findGitHubCredential([])
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('should return null when no GitHub credential exists', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'gitlab', host: 'https://gitlab.com/', token: 'gitlab-token' },
|
||||
{ name: 'private', host: 'https://git.example.com/', token: 'private-token' },
|
||||
]
|
||||
|
||||
const result = findGitHubCredential(credentials)
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveGitIdentity', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
global.fetch = vi.fn()
|
||||
})
|
||||
|
||||
it('should return manual identity when both name and email provided', async () => {
|
||||
const manual = { name: 'John Doe', email: 'john@example.com' }
|
||||
const credentials: GitCredential[] = []
|
||||
|
||||
const result = await resolveGitIdentity(manual, credentials)
|
||||
|
||||
expect(result).toEqual({
|
||||
name: 'John Doe',
|
||||
email: 'john@example.com'
|
||||
})
|
||||
expect(fetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should prioritize manual name but use GitHub email', async () => {
|
||||
const manual = { name: 'Custom Name', email: undefined }
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/', token: 'gh-token' },
|
||||
]
|
||||
|
||||
const userResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
login: 'testuser',
|
||||
name: 'GitHub User',
|
||||
id: 123456
|
||||
})
|
||||
}
|
||||
const emailsResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue([
|
||||
{ email: 'gh@example.com', primary: true, verified: true }
|
||||
])
|
||||
}
|
||||
|
||||
global.fetch = vi.fn()
|
||||
.mockResolvedValueOnce(userResponse)
|
||||
.mockResolvedValueOnce(emailsResponse)
|
||||
|
||||
const result = await resolveGitIdentity(manual, credentials)
|
||||
|
||||
expect(result).toEqual({
|
||||
name: 'Custom Name',
|
||||
email: 'gh@example.com'
|
||||
})
|
||||
})
|
||||
|
||||
it('should use GitHub identity when no manual identity', async () => {
|
||||
const manual = undefined
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/', token: 'gh-token' },
|
||||
]
|
||||
|
||||
const userResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
login: 'testuser',
|
||||
name: 'Test User',
|
||||
id: 123456
|
||||
})
|
||||
}
|
||||
const emailsResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue([
|
||||
{ email: 'test@example.com', primary: true, verified: true }
|
||||
])
|
||||
}
|
||||
|
||||
global.fetch = vi.fn()
|
||||
.mockResolvedValueOnce(userResponse)
|
||||
.mockResolvedValueOnce(emailsResponse)
|
||||
|
||||
const result = await resolveGitIdentity(manual, credentials)
|
||||
|
||||
expect(result).toEqual({
|
||||
name: 'Test User',
|
||||
email: 'test@example.com'
|
||||
})
|
||||
})
|
||||
|
||||
it('should use login as name when GitHub name is null', async () => {
|
||||
const manual = undefined
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/', token: 'gh-token' },
|
||||
]
|
||||
|
||||
const userResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue({
|
||||
login: 'testuser',
|
||||
name: null,
|
||||
id: 123456
|
||||
})
|
||||
}
|
||||
const emailsResponse = {
|
||||
ok: true,
|
||||
json: vi.fn().mockResolvedValue([
|
||||
{ email: 'test@example.com', primary: true, verified: true }
|
||||
])
|
||||
}
|
||||
|
||||
global.fetch = vi.fn()
|
||||
.mockResolvedValueOnce(userResponse)
|
||||
.mockResolvedValueOnce(emailsResponse)
|
||||
|
||||
const result = await resolveGitIdentity(manual, credentials)
|
||||
|
||||
expect(result).toEqual({
|
||||
name: 'testuser',
|
||||
email: 'test@example.com'
|
||||
})
|
||||
})
|
||||
|
||||
it('should return partial identity when GitHub fails but manual has one field', async () => {
|
||||
const manual = { name: 'Only Name', email: undefined }
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/', token: 'invalid-token' },
|
||||
]
|
||||
|
||||
global.fetch = vi.fn().mockResolvedValueOnce({ ok: false })
|
||||
|
||||
const result = await resolveGitIdentity(manual, credentials)
|
||||
|
||||
expect(result).toEqual({
|
||||
name: 'Only Name',
|
||||
email: ''
|
||||
})
|
||||
})
|
||||
|
||||
it('should return null when no identity available', async () => {
|
||||
const manual = undefined
|
||||
const credentials: GitCredential[] = []
|
||||
|
||||
const result = await resolveGitIdentity(manual, credentials)
|
||||
|
||||
expect(result).toBeNull()
|
||||
expect(fetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should return null when both manual fields are empty and GitHub fails', async () => {
|
||||
const manual = { name: undefined, email: undefined }
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/', token: 'invalid-token' },
|
||||
]
|
||||
|
||||
global.fetch = vi.fn().mockResolvedValueOnce({ ok: false })
|
||||
|
||||
const result = await resolveGitIdentity(manual, credentials)
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('createGitIdentityEnv', () => {
|
||||
it('should create git identity environment variables', () => {
|
||||
const identity = { name: 'John Doe', email: 'john@example.com' }
|
||||
|
||||
const result = createGitIdentityEnv(identity)
|
||||
|
||||
expect(result).toEqual({
|
||||
GIT_AUTHOR_NAME: 'John Doe',
|
||||
GIT_AUTHOR_EMAIL: 'john@example.com',
|
||||
GIT_COMMITTER_NAME: 'John Doe',
|
||||
GIT_COMMITTER_EMAIL: 'john@example.com'
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle empty strings in identity', () => {
|
||||
const identity = { name: '', email: 'email@example.com' }
|
||||
|
||||
const result = createGitIdentityEnv(identity)
|
||||
|
||||
expect(result).toEqual({
|
||||
GIT_AUTHOR_NAME: '',
|
||||
GIT_AUTHOR_EMAIL: 'email@example.com',
|
||||
GIT_COMMITTER_NAME: '',
|
||||
GIT_COMMITTER_EMAIL: 'email@example.com'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -4,24 +4,6 @@ export default defineConfig({
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'node',
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
reporter: ['text', 'json', 'html'],
|
||||
exclude: [
|
||||
'node_modules/',
|
||||
'test/',
|
||||
'**/*.test.ts',
|
||||
'**/*.spec.ts',
|
||||
'**/types/**',
|
||||
'vitest.config.ts'
|
||||
],
|
||||
thresholds: {
|
||||
lines: 80,
|
||||
functions: 80,
|
||||
branches: 80,
|
||||
statements: 80
|
||||
}
|
||||
},
|
||||
setupFiles: ['./test/setup.ts']
|
||||
}
|
||||
})
|
||||
@@ -1,62 +0,0 @@
|
||||
#!/usr/bin/env bun
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { listRepos } from './backend/src/db/queries'
|
||||
import { getReposPath } from './shared/src/config/env'
|
||||
import path from 'path'
|
||||
import { exec } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
async function checkGitConfig(repoPath: string) {
|
||||
try {
|
||||
const localEmail = await execAsync('git config user.email', { cwd: repoPath })
|
||||
const localName = await execAsync('git config user.name', { cwd: repoPath })
|
||||
return {
|
||||
localEmail: localEmail.stdout.trim(),
|
||||
localName: localName.stdout.trim(),
|
||||
source: 'local'
|
||||
}
|
||||
} catch (error) {
|
||||
try {
|
||||
const globalEmail = await execAsync('git config --global user.email')
|
||||
const globalName = await execAsync('git config --global user.name')
|
||||
return {
|
||||
localEmail: globalEmail.stdout.trim(),
|
||||
localName: globalName.stdout.trim(),
|
||||
source: 'global'
|
||||
}
|
||||
} catch {
|
||||
return {
|
||||
localEmail: 'NOT SET',
|
||||
localName: 'NOT SET',
|
||||
source: 'none'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const dbPath = process.env.DATABASE_PATH || './data/opencode.db'
|
||||
console.log(`Checking git config for repos in database: ${dbPath}\n`)
|
||||
|
||||
const db = new Database(dbPath)
|
||||
const repos = listRepos(db)
|
||||
const reposPath = getReposPath()
|
||||
|
||||
console.log(`Found ${repos.length} repos\n`)
|
||||
|
||||
for (const repo of repos) {
|
||||
const fullRepoPath = path.resolve(reposPath, repo.localPath)
|
||||
const config = await checkGitConfig(fullRepoPath)
|
||||
|
||||
console.log(`Repo: ${repo.localPath}`)
|
||||
console.log(` Path: ${fullRepoPath}`)
|
||||
console.log(` User Email: ${config.localEmail}`)
|
||||
console.log(` User Name: ${config.localName}`)
|
||||
console.log(` Source: ${config.source}`)
|
||||
console.log('---')
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error)
|
||||
@@ -77,7 +77,7 @@ export const GitIdentitySchema = z.object({
|
||||
export type GitIdentity = z.infer<typeof GitIdentitySchema>;
|
||||
|
||||
export const DEFAULT_GIT_IDENTITY: GitIdentity = {
|
||||
name: '',
|
||||
name: 'OpenCode Agent',
|
||||
email: '',
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user