use std::{collections::HashMap, path::PathBuf}; use toml::Table; #[derive(Debug)] pub struct Config { pub pictures_dir: Option, pub videos_dir: Option, pub music_dir: Option, pub books_dir: Option, pub sources: HashMap, } pub const PICTURE_EXTENTIONS: [&str; 17] = [ ".jpg", ".jpeg", ".png", ".gif", ".webp", ".jfif", ".bmp", ".apng", ".avif", ".tif", ".tga", ".psd", ".eps", ".ai", ".indd", ".raw", ".ico", ]; pub const SOUND_EXTENTIONS: [&str; 10] = [ ".mp3", ".wav", ".flac", ".ogg", ".aac", ".m4a", ".wma", ".aiff", ".au", ".opus", ]; pub const BOOK_EXTENTIONS: [&str; 11] = [ ".pdf", ".epub", ".mobi", ".cbz", ".cbr", ".chm", ".djvu", ".fb2", ".lit", ".prc", ".xps", ]; pub const VIDEO_EXTENTIONS: [&str; 11] = [ ".mp4", ".mkv", ".avi", ".flv", ".webm", ".wmv", ".mov", ".m4v", ".3gp", ".3g2", ".swf", ]; impl Config { // TODO: refactor this nested match mess pub fn parse(path: PathBuf) -> Result> { let mut sources: HashMap = HashMap::new(); let config_str = std::fs::read_to_string(path)?; let config_parsed = &config_str.parse::()?; let pictures_dir = get_path(config_parsed, "pictures_dir"); let videos_dir = get_path(config_parsed, "videos_dir"); let music_dir = get_path(config_parsed, "music_dir"); let books_dir = get_path(config_parsed, "books_dir"); match config_parsed.get("sources") { Some(sources_value) => { match sources_value { toml::Value::Table(sources_value) => { for (key, value) in sources_value.iter() { sources.insert(key.clone(),PathBuf::from(value.as_str().unwrap())); } } _ => { return Err("sources should be a table".into()); } } } None => { return Err("sources not found".into()); } }; Ok(Self { pictures_dir, videos_dir, music_dir, books_dir, 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 { config .get(key) .map(|value| PathBuf::from(value.as_str().unwrap())) }