Add configurable global git identity settings with new Git tab (#43)

This commit is contained in:
Chris Scott authored and GitHub committed 2025-12-31 13:52:55 -05:00
1 parent 1382916b97
commit f1a7d36433
7 files changed
+378 -171

No files matched your search

+20 -2
View File
@@ -12,10 +12,10 @@ import {
import { logger } from '../utils/logger'
import { opencodeServerManager } from '../services/opencode-single-server'
import { DEFAULT_AGENTS_MD } from '../index'
import { exec } from 'child_process'
import { execFile } from 'child_process'
import { promisify } from 'util'
const execAsync = promisify(exec)
const execFileAsync = promisify(execFile)
const UpdateSettingsSchema = z.object({
preferences: UserPreferencesSchema.partial(),
@@ -93,6 +93,24 @@ export function createSettingsRoutes(db: Database) {
}
}
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')
}
}
return c.json({ ...settings, serverRestarted })
} catch (error) {
logger.error('Failed to update settings:', error)
+48
View File
@@ -108,6 +108,35 @@ 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,
@@ -151,6 +180,25 @@ 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') {
+6
View File
@@ -28,6 +28,11 @@ export interface GitCredential {
username?: string
}
export interface GitIdentity {
name: string
email: string
}
export interface UserPreferences {
theme: 'dark' | 'light' | 'system'
mode: 'plan' | 'build'
@@ -41,6 +46,7 @@ export interface UserPreferences {
customCommands: CustomCommand[]
customAgents: CustomAgent[]
gitCredentials?: GitCredential[]
gitIdentity?: GitIdentity
tts?: TTSConfig
}
@@ -1,68 +1,12 @@
import { useState, useEffect } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { Loader2, Plus, Trash2, Save } from 'lucide-react'
import { Loader2 } from 'lucide-react'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { TTSSettings } from './TTSSettings'
import { showToast } from '@/lib/toast'
import type { GitCredential } from '@/api/types/settings'
export function GeneralSettings() {
const { preferences, isLoading, updateSettings, updateSettingsAsync, isUpdating } = useSettings()
const [gitCredentials, setGitCredentials] = useState<GitCredential[]>([])
const [isSaving, setIsSaving] = useState(false)
const [hasChanges, setHasChanges] = useState(false)
useEffect(() => {
if (preferences) {
setGitCredentials(preferences.gitCredentials || [])
setHasChanges(false)
}
}, [preferences])
const checkForChanges = (newCredentials: GitCredential[]) => {
const currentCreds = JSON.stringify(preferences?.gitCredentials || [])
const newCreds = JSON.stringify(newCredentials)
setHasChanges(currentCreds !== newCreds)
}
const addCredential = () => {
const newCredentials = [...gitCredentials, { name: '', host: '', token: '', username: '' }]
setGitCredentials(newCredentials)
checkForChanges(newCredentials)
}
const updateCredential = (index: number, field: keyof GitCredential, value: string) => {
const newCredentials = [...gitCredentials]
newCredentials[index] = { ...newCredentials[index], [field]: value }
setGitCredentials(newCredentials)
checkForChanges(newCredentials)
}
const removeCredential = (index: number) => {
const newCredentials = gitCredentials.filter((_, i) => i !== index)
setGitCredentials(newCredentials)
checkForChanges(newCredentials)
}
const saveCredentials = async () => {
const validCredentials = gitCredentials.filter(cred => cred.name && cred.host && cred.token)
setIsSaving(true)
try {
showToast.loading('Saving credentials and restarting server...', { id: 'git-credentials' })
await updateSettingsAsync({ gitCredentials: validCredentials })
setHasChanges(false)
showToast.success('Git credentials updated', { id: 'git-credentials' })
} catch {
showToast.error('Failed to update git credentials', { id: 'git-credentials' })
} finally {
setIsSaving(false)
}
}
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
if (isLoading) {
return (
@@ -172,114 +116,6 @@ export function GeneralSettings() {
/>
</div>
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<h3 className="text-base font-semibold text-foreground">Git Credentials</h3>
<p className="text-sm text-muted-foreground">
Add credentials for cloning private repositories from any Git host
</p>
</div>
<div className="flex gap-2">
{hasChanges && (
<Button
type="button"
variant="default"
size="sm"
onClick={saveCredentials}
disabled={isSaving}
>
{isSaving ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Save className="h-4 w-4 mr-2" />}
Save
</Button>
)}
<Button
type="button"
variant="outline"
size="sm"
onClick={addCredential}
disabled={isSaving}
>
<Plus className="h-4 w-4 mr-2" />
Add
</Button>
</div>
</div>
{gitCredentials.length === 0 ? (
<div className="rounded-lg border border-dashed border-border p-6 text-center">
<p className="text-sm text-muted-foreground">
No git credentials configured. Click "Add" to add credentials for GitHub, GitLab, Gitea, or other Git hosts.
</p>
</div>
) : (
<div className="space-y-4">
{gitCredentials.map((cred, index) => (
<div key={index} className="rounded-lg border border-border p-4 space-y-3">
<div className="flex items-center justify-between">
<Input
placeholder="Credential name (e.g., GitHub Personal, Work GitLab)"
value={cred.name}
onChange={(e) => updateCredential(index, 'name', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground font-medium"
/>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => removeCredential(index)}
disabled={isSaving}
className="ml-2 text-destructive hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Host URL</Label>
<Input
placeholder="https://github.com/"
value={cred.host}
onChange={(e) => updateCredential(index, 'host', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Username (optional)</Label>
<Input
placeholder="Auto-detected if empty"
value={cred.username || ''}
onChange={(e) => updateCredential(index, 'username', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
</div>
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Access Token</Label>
<Input
type="password"
placeholder="Personal access token"
value={cred.token}
onChange={(e) => updateCredential(index, 'token', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
</div>
))}
</div>
)}
<p className="text-xs text-muted-foreground">
Username defaults: github.com uses "x-access-token", gitlab.com uses "oauth2". For other hosts, specify your username if required.
</p>
</div>
{isUpdating && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
@@ -0,0 +1,278 @@
import { useState, useEffect } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { Loader2, Plus, Trash2, Save } from 'lucide-react'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { showToast } from '@/lib/toast'
import type { GitCredential, GitIdentity } from '@/api/types/settings'
export function GitSettings() {
const { preferences, isLoading, updateSettingsAsync, isUpdating } = useSettings()
const [gitCredentials, setGitCredentials] = useState<GitCredential[]>([])
const [gitIdentity, setGitIdentity] = useState<GitIdentity>({ name: '', email: '' })
const [isSaving, setIsSaving] = useState(false)
const [hasCredentialChanges, setHasCredentialChanges] = useState(false)
const [hasIdentityChanges, setHasIdentityChanges] = useState(false)
useEffect(() => {
if (preferences) {
setGitCredentials(preferences.gitCredentials || [])
setGitIdentity(preferences.gitIdentity || { name: '', email: '' })
setHasCredentialChanges(false)
setHasIdentityChanges(false)
}
}, [preferences])
const checkForCredentialChanges = (newCredentials: GitCredential[]) => {
const currentCreds = JSON.stringify(preferences?.gitCredentials || [])
const newCreds = JSON.stringify(newCredentials)
setHasCredentialChanges(currentCreds !== newCreds)
}
const checkForIdentityChanges = (newIdentity: GitIdentity) => {
const currentIdentity = preferences?.gitIdentity || { name: '', email: '' }
setHasIdentityChanges(
currentIdentity.name !== newIdentity.name ||
currentIdentity.email !== newIdentity.email
)
}
const addCredential = () => {
const newCredentials = [...gitCredentials, { name: '', host: '', token: '', username: '' }]
setGitCredentials(newCredentials)
checkForCredentialChanges(newCredentials)
}
const updateCredential = (index: number, field: keyof GitCredential, value: string) => {
const newCredentials = [...gitCredentials]
newCredentials[index] = { ...newCredentials[index], [field]: value }
setGitCredentials(newCredentials)
checkForCredentialChanges(newCredentials)
}
const removeCredential = (index: number) => {
const newCredentials = gitCredentials.filter((_, i) => i !== index)
setGitCredentials(newCredentials)
checkForCredentialChanges(newCredentials)
}
const updateIdentity = (field: keyof GitIdentity, value: string) => {
const newIdentity = { ...gitIdentity, [field]: value }
setGitIdentity(newIdentity)
checkForIdentityChanges(newIdentity)
}
const saveCredentials = async () => {
const validCredentials = gitCredentials.filter(cred => cred.name && cred.host && cred.token)
setIsSaving(true)
try {
showToast.loading('Saving credentials and restarting server...', { id: 'git-credentials' })
await updateSettingsAsync({ gitCredentials: validCredentials })
setHasCredentialChanges(false)
showToast.success('Git credentials updated', { id: 'git-credentials' })
} catch {
showToast.error('Failed to update git credentials', { id: 'git-credentials' })
} finally {
setIsSaving(false)
}
}
const saveIdentity = async () => {
setIsSaving(true)
try {
showToast.loading('Saving git identity...', { id: 'git-identity' })
await updateSettingsAsync({ gitIdentity })
setHasIdentityChanges(false)
showToast.success('Git identity updated', { id: 'git-identity' })
} catch {
showToast.error('Failed to update git identity', { id: 'git-identity' })
} finally {
setIsSaving(false)
}
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="space-y-6">
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">Git Identity</h2>
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
Configure the default author identity used for git commits in local repositories.
Leave empty to use system defaults.
</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="git-name">Name</Label>
<Input
id="git-name"
placeholder="Your Name"
value={gitIdentity.name}
onChange={(e) => updateIdentity('name', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
<div className="space-y-2">
<Label htmlFor="git-email">Email</Label>
<Input
id="git-email"
type="email"
placeholder="you@example.com"
value={gitIdentity.email}
onChange={(e) => updateIdentity('email', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
</div>
{hasIdentityChanges && (
<div className="flex justify-end">
<Button
type="button"
variant="default"
size="sm"
onClick={saveIdentity}
disabled={isSaving}
>
{isSaving ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Save className="h-4 w-4 mr-2" />}
Save Identity
</Button>
</div>
)}
<p className="text-xs text-muted-foreground">
If not configured, defaults to "OpenCode User" and "opencode@localhost" for new local repositories.
</p>
</div>
</div>
<div className="bg-card border border-border rounded-lg p-6">
<div className="flex items-center justify-between mb-6">
<div>
<h2 className="text-lg font-semibold text-foreground">Git Credentials</h2>
<p className="text-sm text-muted-foreground">
Add credentials for cloning private repositories from any Git host
</p>
</div>
<div className="flex gap-2">
{hasCredentialChanges && (
<Button
type="button"
variant="default"
size="sm"
onClick={saveCredentials}
disabled={isSaving}
>
{isSaving ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Save className="h-4 w-4 mr-2" />}
Save
</Button>
)}
<Button
type="button"
variant="outline"
size="sm"
onClick={addCredential}
disabled={isSaving}
>
<Plus className="h-4 w-4 mr-2" />
Add
</Button>
</div>
</div>
{gitCredentials.length === 0 ? (
<div className="rounded-lg border border-dashed border-border p-6 text-center">
<p className="text-sm text-muted-foreground">
No git credentials configured. Click "Add" to add credentials for GitHub, GitLab, Gitea, or other Git hosts.
</p>
</div>
) : (
<div className="space-y-4">
{gitCredentials.map((cred, index) => (
<div key={index} className="rounded-lg border border-border p-4 space-y-3">
<div className="flex items-center justify-between">
<Input
placeholder="Credential name (e.g., GitHub Personal, Work GitLab)"
value={cred.name}
onChange={(e) => updateCredential(index, 'name', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground font-medium"
/>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => removeCredential(index)}
disabled={isSaving}
className="ml-2 text-destructive hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Host URL</Label>
<Input
placeholder="https://github.com/"
value={cred.host}
onChange={(e) => updateCredential(index, 'host', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Username (optional)</Label>
<Input
placeholder="Auto-detected if empty"
value={cred.username || ''}
onChange={(e) => updateCredential(index, 'username', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
</div>
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Access Token</Label>
<Input
type="password"
placeholder="Personal access token"
value={cred.token}
onChange={(e) => updateCredential(index, 'token', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
</div>
))}
</div>
)}
<p className="text-xs text-muted-foreground mt-4">
Username defaults: github.com uses "x-access-token", gitlab.com uses "oauth2". For other hosts, specify your username if required.
</p>
{isUpdating && (
<div className="flex items-center gap-2 text-sm text-muted-foreground mt-4">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Saving...</span>
</div>
)}
</div>
</div>
)
}
@@ -1,11 +1,12 @@
import { useState, useRef, useEffect, useCallback } from 'react'
import { GeneralSettings } from '@/components/settings/GeneralSettings'
import { GitSettings } from '@/components/settings/GitSettings'
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager'
import { ProviderSettings } from '@/components/settings/ProviderSettings'
import { Dialog, DialogContent } from '@/components/ui/dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Settings2, Keyboard, Code, ChevronLeft, X, Key } from 'lucide-react'
import { Settings2, Keyboard, Code, ChevronLeft, X, Key, GitBranch } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useSwipeBack } from '@/hooks/useMobile'
@@ -14,7 +15,7 @@ interface SettingsDialogProps {
onOpenChange: (open: boolean) => void
}
type SettingsView = 'menu' | 'general' | 'shortcuts' | 'opencode' | 'providers'
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers'
export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
const [mobileView, setMobileView] = useState<SettingsView>('menu')
@@ -39,6 +40,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
const menuItems = [
{ id: 'general', icon: Settings2, label: 'General Settings', description: 'App preferences and behavior' },
{ id: 'git', icon: GitBranch, label: 'Git', description: 'Git identity and credentials for repositories' },
{ id: 'shortcuts', icon: Keyboard, label: 'Keyboard Shortcuts', description: 'Customize keyboard shortcuts' },
{ id: 'opencode', icon: Code, label: 'OpenCode Config', description: 'Manage OpenCode configurations, commands, and agents' },
{ id: 'providers', icon: Key, label: 'Providers', description: 'Manage AI provider API keys' },
@@ -65,10 +67,13 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
</div>
<Tabs defaultValue="general" className="w-full flex flex-col flex-1 min-h-0">
<div className="px-6 pt-6 pb-4 flex-shrink-0">
<TabsList className="grid w-full grid-cols-4 bg-card border border-border p-1">
<TabsList className="grid w-full grid-cols-5 bg-card border border-border p-1">
<TabsTrigger value="general" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
General
</TabsTrigger>
<TabsTrigger value="git" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
Git
</TabsTrigger>
<TabsTrigger value="shortcuts" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
Shortcuts
</TabsTrigger>
@@ -84,6 +89,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
<div className="flex-1 overflow-y-auto">
<div className="px-6 pb-6">
<TabsContent value="general" className="mt-0"><GeneralSettings /></TabsContent>
<TabsContent value="git" className="mt-0"><GitSettings /></TabsContent>
<TabsContent value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
<TabsContent value="opencode" className="mt-0"><OpenCodeConfigManager /></TabsContent>
<TabsContent value="providers" className="mt-0"><ProviderSettings /></TabsContent>
@@ -143,6 +149,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
)}
{mobileView === 'general' && <GeneralSettings />}
{mobileView === 'git' && <GitSettings />}
{mobileView === 'shortcuts' && <KeyboardShortcuts />}
{mobileView === 'opencode' && <OpenCodeConfigManager />}
{mobileView === 'providers' && <ProviderSettings />}
+14
View File
@@ -69,6 +69,18 @@ export const GitCredentialSchema = z.object({
export type GitCredential = z.infer<typeof GitCredentialSchema>;
export const GitIdentitySchema = z.object({
name: z.string(),
email: z.string(),
});
export type GitIdentity = z.infer<typeof GitIdentitySchema>;
export const DEFAULT_GIT_IDENTITY: GitIdentity = {
name: '',
email: '',
};
export const UserPreferencesSchema = z.object({
theme: z.enum(["dark", "light", "system"]),
mode: z.enum(["plan", "build"]),
@@ -82,6 +94,7 @@ export const UserPreferencesSchema = z.object({
customCommands: z.array(CustomCommandSchema),
customAgents: z.array(CustomAgentSchema),
gitCredentials: z.array(GitCredentialSchema).optional(),
gitIdentity: GitIdentitySchema.optional(),
tts: TTSConfigSchema.optional(),
lastKnownGoodConfig: z.string().optional(),
});
@@ -111,6 +124,7 @@ export const DEFAULT_USER_PREFERENCES = {
customCommands: [],
customAgents: [],
gitCredentials: [] as GitCredential[],
gitIdentity: DEFAULT_GIT_IDENTITY,
tts: DEFAULT_TTS_CONFIG,
};