feat: create config if not found
This commit is contained in:
parent
cf5999a1c7
commit
3569592684
2 changed files with 48 additions and 5 deletions
19
src/lib.rs
19
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<Self, Box<dyn std::error::Error>> {
|
||||
pub fn parse(path: PathBuf) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let mut sources: HashMap<String, PathBuf> = 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::<Table>()?;
|
||||
|
||||
let pictures_dir = get_path(config_parsed, "pictures_dir");
|
||||
|
@ -65,6 +65,21 @@ impl Config {
|
|||
sources,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn create(path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
|
||||
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<PathBuf> {
|
||||
|
|
34
src/main.rs
34
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)))
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue