From f1512e01c9022dbdb29cab2204d73ed4cd3eb68a Mon Sep 17 00:00:00 2001 From: yuni Date: Thu, 13 Jun 2024 02:18:58 +0200 Subject: [PATCH] create config file/directory if it doesn't exist yet --- src/var.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/var.rs b/src/var.rs index 98a71ee..7b96684 100644 --- a/src/var.rs +++ b/src/var.rs @@ -31,6 +31,7 @@ pub const TOKEN_LESS_EQUALS: &str = "<="; pub const TOKEN_NEGATE: &str = "~"; pub const DEFAULT_CHAT_SPEED: f32 = 10.0; +pub const DEFAULT_CONFIG_TOML: &str = include_str!("data/outfly.toml"); #[derive(Resource)] pub struct Settings { @@ -472,6 +473,12 @@ fn file_is_readable(file_path: &str) -> bool { .unwrap_or(false) } +fn path_is_directory(file_path: &str) -> bool { + fs::metadata(file_path) + .map(|metadata| metadata.is_dir()) + .unwrap_or(false) +} + fn get_prefs_path() -> Option { let test = CONF_FILE; if file_is_readable(test) { @@ -479,7 +486,30 @@ fn get_prefs_path() -> Option { } if let Some(mut conf) = dirs::config_dir() { conf.push("OutFly"); + if !conf.exists() { + match fs::create_dir_all(&conf) { + Ok(_) => {} + Err(error) => { + eprintln!("Failed creating configuration directory: {error}"); + } + } + } + if let Some(test) = conf.to_str() { + if !path_is_directory(test) { + eprintln!("Failed creating configuration directory"); + return None; + } + } + conf.push(CONF_FILE); + if !conf.exists() { + match fs::write(&conf, DEFAULT_CONFIG_TOML.to_string()) { + Ok(_) => {} + Err(error) => { + eprintln!("Failed creating configuration file: {error}"); + } + } + } if let Some(test) = conf.to_str() { if file_is_readable(test) { return Some(test.to_string()); @@ -503,7 +533,7 @@ pub fn load_prefs() -> Preferences { } None => { println!("Found no preference file, using default preferences."); - (include_str!("data/outfly.toml").to_string(), None) + (DEFAULT_CONFIG_TOML.to_string(), None) } }; match toml.parse::() {