From f410eb719941941d93ab17dc7094b4a9400acff5 Mon Sep 17 00:00:00 2001 From: shenjack-5600u <3695888@qq.com> Date: Mon, 29 Jan 2024 11:44:31 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=B8=80=E6=B3=A2=E4=BD=8D?= =?UTF-8?q?=E7=BD=AE=E5=8F=AF=E9=80=89=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.toml | 2 +- src/config.rs | 31 ++++++++++++++++++++++++++++--- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a2f4a5a..e9d62c0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,7 +29,7 @@ zstd = "0.13.0" log = "0.4.20" [dependencies.simple_logger] version = "4.3.3" -features = ["colors", "threads", "timestamps", "stderr"] +features = ["colors", "threads", "timestamps"] # [dependencies.db_logger] # version = "0.1" # optional = true diff --git a/src/config.rs b/src/config.rs index dd9799f..9b7e951 100644 --- a/src/config.rs +++ b/src/config.rs @@ -121,6 +121,14 @@ impl Config { }); } + /// 保存至文件 + pub fn save_to_file(&self, path: &str) { + fs::write(path, toml::to_string(&self).unwrap()).unwrap_or_else(|err| { + fatal!(("Failed to save config: {}", err), ("{}", err)); + }); + } + + /// 从文件加载 pub fn update_from_config(&mut self) { if Path::new(CONFIG_PATH).exists() { let raw_data: Config = toml::from_str(&fs::read_to_string(CONFIG_PATH).unwrap()) @@ -140,6 +148,22 @@ impl Config { } } + /// 从文件加载 + pub fn update_from_file(&mut self, path: &str) { + let raw_data: Config = toml::from_str(&fs::read_to_string(path).unwrap()) + .unwrap_or_else(|err| { + fatal!(("Failed to load config: {}", err), ("{}", err)); + }); + self.center_url = raw_data.center_url; + self.host_ip = raw_data.host_ip; + self.host_port = raw_data.host_port; + self.cluster_id = raw_data.cluster_id; + self.cluster_secret = raw_data.cluster_secret; + self.no_demaon = raw_data.no_demaon; + self.cache_dir = raw_data.cache_dir; + info!("Config loaded"); + } + pub fn join_center_url(&self, path: &str) -> String { format!("{}{}", self.center_url, path) } @@ -147,6 +171,7 @@ impl Config { #[test] fn test_save_and_load_config() { + let tmp_file = Path::new("tmp.toml"); let config: Config = Config::new( Some("https://example.com".to_string()), "0.0.0.0".to_string(), @@ -165,8 +190,8 @@ fn test_save_and_load_config() { None, None, ); - config.save(); - test_config.update_from_config(); + config.save_to_file(tmp_file.to_str().unwrap()); + test_config.update_from_file(tmp_file.to_str().unwrap()); assert_eq!(test_config.center_url, "https://example.com"); assert_eq!(test_config.host_ip, "0.0.0.0"); assert_eq!(test_config.host_port, 23333); @@ -176,5 +201,5 @@ fn test_save_and_load_config() { assert_eq!(test_config.cache_dir, PathBuf::from("cache")); // Clean up the temporary config file - fs::remove_file(CONFIG_PATH).unwrap(); + fs::remove_file(tmp_file).unwrap(); }