Browse Source

打开Claude Code配置文件

黄中银 2 tuần trước cách đây
mục cha
commit
6ad4c01f71

+ 1 - 0
shared/types.ts

@@ -202,6 +202,7 @@ export interface ElectronAPI {
   checkClaudeCode: () => Promise<{ installed: boolean; version: string | null }>
   launchClaudeCode: () => Promise<{ success: boolean }>
   installClaudeCode: () => Promise<{ success: boolean; error?: string }>
+  openClaudeCodeConfig: () => Promise<{ success: boolean; error?: string }>
 
   // VS Code Extensions
   checkVscodeExtension: (extensionId: string) => Promise<{ installed: boolean; version?: string }>

+ 118 - 0
src-tauri/src/commands/claude_code.rs

@@ -1,5 +1,7 @@
 use crate::utils::shell::{run_shell_hidden, spawn_process, CommandOptions};
 use serde::{Deserialize, Serialize};
+use std::fs;
+use std::path::PathBuf;
 
 #[derive(Serialize, Deserialize)]
 pub struct ClaudeCodeStatus {
@@ -135,3 +137,119 @@ pub async fn launch_claude_code() -> CommandResult {
         }
     }
 }
+
+/// 获取 Claude Code 配置文件路径
+fn get_claude_config_path() -> Option<PathBuf> {
+    dirs::home_dir().map(|home| home.join(".claude").join("settings.json"))
+}
+
+/// 打开 Claude Code 配置文件
+#[tauri::command]
+pub async fn open_claude_code_config() -> CommandResult {
+    let config_path = match get_claude_config_path() {
+        Some(path) => path,
+        None => {
+            return CommandResult {
+                success: false,
+                error: Some("Cannot determine home directory".to_string()),
+            }
+        }
+    };
+
+    // 确保 .claude 目录存在
+    if let Some(parent) = config_path.parent() {
+        if !parent.exists() {
+            if let Err(e) = fs::create_dir_all(parent) {
+                return CommandResult {
+                    success: false,
+                    error: Some(format!("Failed to create .claude directory: {}", e)),
+                };
+            }
+        }
+    }
+
+    // 如果配置文件不存在,创建带有默认内容的配置文件
+    if !config_path.exists() {
+        let default_config = r#"{
+  "alwaysThinkingEnabled": true,
+  "env": {
+    "ANTHROPIC_AUTH_TOKEN": "你的Key",
+    "ANTHROPIC_BASE_URL": "https://xiaoheiai.tiantianyy.com",
+    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "claude-opus-4-5-20251101",
+    "ANTHROPIC_DEFAULT_OPUS_MODEL": "claude-opus-4-5-20251101",
+    "ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-opus-4-5-20251101",
+    "ANTHROPIC_MODEL": "claude-opus-4-5-20251101"
+  },
+  "compression": {
+    "defaultLevel": "light"
+  }
+}"#;
+        if let Err(e) = fs::write(&config_path, default_config) {
+            return CommandResult {
+                success: false,
+                error: Some(format!("Failed to create config file: {}", e)),
+            };
+        }
+    }
+
+    // 使用系统默认程序打开配置文件
+    #[cfg(target_os = "windows")]
+    {
+        let result = spawn_process(
+            "cmd",
+            &["/c", "start", "", config_path.to_str().unwrap_or("")],
+            CommandOptions::hidden(),
+        );
+
+        match result {
+            Ok(_) => CommandResult {
+                success: true,
+                error: None,
+            },
+            Err(e) => CommandResult {
+                success: false,
+                error: Some(e),
+            },
+        }
+    }
+
+    #[cfg(target_os = "macos")]
+    {
+        let result = spawn_process(
+            "open",
+            &[config_path.to_str().unwrap_or("")],
+            CommandOptions::hidden(),
+        );
+
+        match result {
+            Ok(_) => CommandResult {
+                success: true,
+                error: None,
+            },
+            Err(e) => CommandResult {
+                success: false,
+                error: Some(e),
+            },
+        }
+    }
+
+    #[cfg(target_os = "linux")]
+    {
+        let result = spawn_process(
+            "xdg-open",
+            &[config_path.to_str().unwrap_or("")],
+            CommandOptions::hidden(),
+        );
+
+        match result {
+            Ok(_) => CommandResult {
+                success: true,
+                error: None,
+            },
+            Err(e) => CommandResult {
+                success: false,
+                error: Some(e),
+            },
+        }
+    }
+}

+ 1 - 0
src-tauri/src/lib.rs

@@ -62,6 +62,7 @@ pub fn run() {
             commands::claude_code::check_claude_code,
             commands::claude_code::install_claude_code,
             commands::claude_code::launch_claude_code,
+            commands::claude_code::open_claude_code_config,
             // VS Code 扩展
             commands::vscode::check_vscode_extension,
             commands::vscode::install_vscode_extension,

+ 4 - 0
src/api/tauri.ts

@@ -272,6 +272,10 @@ export const tauriAPI = {
     return await invoke('install_claude_code')
   },
 
+  async openClaudeCodeConfig(): Promise<{ success: boolean; error?: string }> {
+    return await invoke('open_claude_code_config')
+  },
+
   // ==================== VS Code Extensions ====================
 
   async checkVscodeExtension(extensionId: string): Promise<{ installed: boolean; version?: string }> {

+ 2 - 0
src/i18n/en-US.ts

@@ -119,6 +119,8 @@ export default {
     installHint: 'Please run npm install -g @anthropic-ai/claude-code to install Claude Code first',
     installHintWithButton: 'Click the "Install Claude Code" button below to install',
     refresh: 'Refresh Status',
+    openConfig: 'Open Config File',
+    openConfigFailed: 'Failed to open config file',
     requiresNodejsGit: 'Requires Node.js and Git'
   },
   install: {

+ 2 - 0
src/i18n/zh-CN.ts

@@ -119,6 +119,8 @@ export default {
     installHint: '请先运行 npm install -g @anthropic-ai/claude-code 安装 Claude Code',
     installHintWithButton: '点击下方"安装 Claude Code"按钮进行安装',
     refresh: '刷新状态',
+    openConfig: '打开配置文件',
+    openConfigFailed: '打开配置文件失败',
     requiresNodejsGit: '需要 Node.js 和 Git'
   },
   install: {

+ 14 - 0
src/views/ClaudeCodeView.vue

@@ -116,6 +116,17 @@ async function handleUninstall() {
     isUninstalling.value = false
   }
 }
+
+async function handleOpenConfig() {
+  try {
+    const result = await window.electronAPI.openClaudeCodeConfig()
+    if (!result.success) {
+      installStore.addLog(`${t('claudeCode.openConfigFailed')}: ${result.error}`, 'error')
+    }
+  } catch (error) {
+    installStore.addLog(`${t('claudeCode.openConfigFailed')}: ${(error as Error).message}`, 'error')
+  }
+}
 </script>
 
 <template>
@@ -180,6 +191,9 @@ async function handleUninstall() {
         <el-button :disabled="isChecking || isInstalling || isUninstalling" @click="refreshStatus">
           {{ t('claudeCode.refresh') }}
         </el-button>
+        <el-button v-if="claudeCodeInstalled" @click="handleOpenConfig">
+          {{ t('claudeCode.openConfig') }}
+        </el-button>
       </div>
 
       <div class="status-container">