subx_cli/commands/
config_command.rs

1use crate::Result;
2use crate::cli::{ConfigAction, ConfigArgs};
3use crate::config::{Config, load_config};
4use crate::error::SubXError;
5
6/// Config 子命令執行
7pub async fn execute(args: ConfigArgs) -> Result<()> {
8    match args.action {
9        ConfigAction::Set { key, value } => {
10            let mut config = load_config()?;
11            let parts: Vec<&str> = key.splitn(2, '.').collect();
12            if parts.len() == 2 {
13                match parts[0] {
14                    "ai" => match parts[1] {
15                        "api_key" => config.ai.api_key = Some(value),
16                        "model" => config.ai.model = value,
17                        _ => {
18                            return Err(SubXError::config(format!("無效的 AI 配置鍵: {}", key)));
19                        }
20                    },
21                    "formats" => match parts[1] {
22                        "default_output" => config.formats.default_output = value,
23                        _ => {
24                            return Err(SubXError::config(format!(
25                                "無效的 Formats 配置鍵: {}",
26                                key
27                            )));
28                        }
29                    },
30                    _ => {
31                        return Err(SubXError::config(format!("無效的配置區段: {}", parts[0])));
32                    }
33                }
34            } else {
35                return Err(SubXError::config(format!(
36                    "無效的配置鍵格式: {} (應為 section.field)",
37                    key
38                )));
39            }
40            config.save()?;
41            println!("設定 {} = {}", key, config.get_value(&key)?);
42        }
43        ConfigAction::Get { key } => {
44            let config = load_config()?;
45            let value = config.get_value(&key)?;
46            println!("{}", value);
47        }
48        ConfigAction::List => {
49            let config = load_config()?;
50            if let Some(path) = &config.loaded_from {
51                println!("# 配置檔案路徑: {}\n", path.display());
52            }
53            println!(
54                "{}",
55                toml::to_string_pretty(&config)
56                    .map_err(|e| SubXError::config(format!("TOML 序列化錯誤: {}", e)))?
57            );
58        }
59        ConfigAction::Reset => {
60            let default_config = Config::default();
61            default_config.save()?;
62            println!("配置已重置為預設值");
63            if let Ok(path) = Config::config_file_path() {
64                println!("預設配置已儲存至: {}", path.display());
65            }
66        }
67    }
68    Ok(())
69}