Files
cc-switch/src/main/services.ts

56 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-08-04 22:16:26 +08:00
import fs from 'fs/promises'
import path from 'path'
import os from 'os'
import { Provider } from '../shared/types'
2025-08-04 22:16:26 +08:00
interface ClaudeCodeConfig {
env?: {
ANTHROPIC_AUTH_TOKEN?: string
ANTHROPIC_BASE_URL?: string
[key: string]: string | undefined
}
[key: string]: any
}
2025-08-04 22:16:26 +08:00
export function getClaudeCodeConfig() {
// Claude Code 配置文件路径
const configDir = path.join(os.homedir(), '.claude')
const configPath = path.join(configDir, 'settings.json')
2025-08-04 22:16:26 +08:00
return { path: configPath, dir: configDir }
}
export async function switchProvider(provider: Provider): Promise<boolean> {
try {
const { path: configPath, dir: configDir } = getClaudeCodeConfig()
2025-08-04 22:16:26 +08:00
// 确保目录存在
await fs.mkdir(configDir, { recursive: true })
2025-08-04 22:16:26 +08:00
// 读取现有配置
let config: ClaudeCodeConfig = {}
2025-08-04 22:16:26 +08:00
try {
const content = await fs.readFile(configPath, 'utf-8')
config = JSON.parse(content)
} catch {
// 文件不存在或解析失败,使用空配置
}
// 确保 env 对象存在
if (!config.env) {
config.env = {}
2025-08-04 22:16:26 +08:00
}
// 更新环境变量配置
config.env.ANTHROPIC_AUTH_TOKEN = provider.apiKey
config.env.ANTHROPIC_BASE_URL = provider.apiUrl
2025-08-04 22:16:26 +08:00
// 写回配置文件
await fs.writeFile(configPath, JSON.stringify(config, null, 2))
2025-08-04 22:16:26 +08:00
return true
} catch (error) {
console.error('切换供应商失败:', error)
return false
}
}