Skip to main content

btcli_lib/
conf.rs

1// Copyright (C) 2026 S.A. (@snoware)
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
7use serde::{Deserialize, Serialize};
8
9#[derive(Serialize, Deserialize, Debug, Clone)]
10pub struct AppConfig {
11    pub appid: String,
12    pub key: String,
13    pub source_lang: String,
14    pub target_lang: String,
15    pub enable_logging: bool,
16}
17
18const EXAMPLE_CONF: &str = r#"
19appid = "your appid"
20key = "your key"
21source_lang = "auto"
22target_lang = "zh"
23enable_logging = false
24"#;
25
26use std::fs::write;
27
28fn create_conf() -> Result<(), std::io::Error> {
29    write("config.toml", EXAMPLE_CONF)
30}
31
32use toml;
33
34pub fn save_conf_with_debug(
35    appid: &str,
36    key: &str,
37    source_lang: &str,
38    target_lang: &str,
39    enable_logging: bool,
40) -> Result<(), Box<dyn std::error::Error>> {
41    let conf = AppConfig {
42        appid: appid.to_string(),
43        key: key.to_string(),
44        source_lang: source_lang.to_string(),
45        target_lang: target_lang.to_string(),
46        enable_logging,
47    };
48    let conf_str = toml::to_string(&conf)?;
49    write("config.toml", conf_str)?;
50    Ok(())
51}
52
53pub enum ConfigResult {
54    Ok(AppConfig),
55    Err(String),
56}
57
58fn load_file() -> ConfigResult {
59    if !std::path::Path::new("config.toml").exists() {
60        return ConfigResult::Err("config.toml not found, generating...".to_string());
61    } else if std::path::Path::new("config.toml").is_dir() {
62        return ConfigResult::Err(
63            "config.toml is not a file, please delete it and try again.".to_string(),
64        );
65    }
66
67    let raw = std::fs::read_to_string("config.toml");
68    let raw_c = match raw {
69        Ok(raw) => raw,
70        Err(e) => return ConfigResult::Err(format!(":( Unable to read config.toml: {}", e)),
71    };
72    let read_result = toml::from_str::<AppConfig>(&raw_c);
73    match read_result {
74        Ok(config) => ConfigResult::Ok(config),
75        Err(e) => ConfigResult::Err(format!(":( Unable to parse config.toml: {}", e)),
76    }
77}
78
79pub fn try_init_conf() -> Result<AppConfig, String> {
80    match load_file() {
81        ConfigResult::Ok(config) => Ok(config),
82        ConfigResult::Err(e) => {
83            // 如果配置文件不存在,尝试创建示例配置文件
84            if e.contains("not found") {
85                match create_conf() {
86                    Ok(_) => {
87                        // 创建成功后,解析示例配置并返回
88                        match toml::from_str::<AppConfig>(EXAMPLE_CONF) {
89                            Ok(default_config) => Ok(default_config),
90                            Err(parse_err) => {
91                                Err(format!(":( Unable to parse example config: {}", parse_err))
92                            }
93                        }
94                    }
95                    Err(create_err) => {
96                        Err(format!(":( Unable to create config.toml: {}", create_err))
97                    }
98                }
99            } else {
100                // 其他错误情况,直接返回错误
101                Err(e)
102            }
103        }
104    }
105}