diff --git a/src/lib.rs b/src/lib.rs index 6e49251..2814359 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -28,10 +28,10 @@ pub const VIDEO_EXTENTIONS: [&str; 11] = [ impl Config { // TODO: refactor this nested match mess - pub fn parse() -> Result> { + pub fn parse(path: PathBuf) -> Result> { let mut sources: HashMap = HashMap::new(); - let config_str = std::fs::read_to_string("sorter_config.toml")?; + let config_str = std::fs::read_to_string(path)?; let config_parsed = &config_str.parse::()?; let pictures_dir = get_path(config_parsed, "pictures_dir"); @@ -65,6 +65,21 @@ impl Config { sources, }) } + + pub fn create(path: &PathBuf) -> Result<(), Box> { + let config_str = r#" +pictures_dir = "/home/vavakado/Pictures" +videos_dir = "/home/vavakado/Videos" +music_dir = "/home/vavakado/Music" +books_dir = "/home/vavakado/Books" + +[sources] # put your own sources here +"Pictures" = "/home/vavakado/Pictures" +"#; + std::fs::write(path, config_str)?; + + Ok(()) + } } fn get_path(config: &Table, key: &str) -> Option { diff --git a/src/main.rs b/src/main.rs index b8b3d25..a9dcfc6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,16 @@ -fn main() { - println!("Hello, world!"); +use std::{env, path::PathBuf}; - match filesorters::Config::parse() { +fn main() { + let config_path = get_config_path(); + + println!("Using config file: {}", config_path.display()); + + if !config_path.exists() { + println!("Config file does not exist, creating..."); + filesorters::Config::create(&config_path).unwrap(); + } + + match filesorters::Config::parse(config_path) { Ok(config) => { println!("{:#?}", config); } @@ -10,3 +19,22 @@ fn main() { } } } + +fn get_config_path() -> PathBuf { + if cfg!(target_os = "windows") { + let username = env::var("USERNAME").unwrap_or_else(|_| "Default".to_string()); + PathBuf::from(format!( + "C:\\Users\\{}\\AppData\\Local\\filesorters\\filesorters.toml", + username + )) + } else { + let xdg_config_home = env::var("XDG_CONFIG_HOME").ok(); + let home = env::var("HOME").ok(); + let user = env::var("USER").unwrap_or_else(|_| "default".to_string()); + + xdg_config_home + .map(|x| PathBuf::from(format!("{}/filesorters.toml", x))) + .or_else(|| home.map(|h| PathBuf::from(format!("{}/.config/filesorters.toml", h)))) + .unwrap_or_else(|| PathBuf::from(format!("/home/{}/.config/filesorters.toml", user))) + } +}