From 8120a7cd9a6a8163cb7035c7de511494e8ade1f8 Mon Sep 17 00:00:00 2001 From: Valerie Date: Tue, 8 Aug 2023 11:11:02 -0400 Subject: [PATCH] config init now creates directory structure as fallback --- src/config.rs | 38 ++++++++++++++++++++++++++++++++++++-- src/error.rs | 10 +++++++++- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/config.rs b/src/config.rs index a33950b..097e83a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,8 +3,10 @@ use std::{ collections::HashMap, env::var, - fs::read_to_string, - path::PathBuf + fs::{ create_dir, read_to_string, File }, + io::Error, + path::PathBuf, + process::exit }; use tera::Context; @@ -13,6 +15,8 @@ use toml::{ Value }; +use crate::error; + /// configuration struct pub struct Config { pub dir: String, @@ -27,6 +31,14 @@ impl Config { let mut dir = PathBuf::from(&home); dir.push(".config/oink"); + if !dir.exists() { + println!("missing directory at {dir:?}, creating..."); + let setup = setup_dirs(&dir); + if setup.is_err() { error::setup_dirs(&dir); } + println!("created configuration directory, exiting..."); + exit(0); + } + // read toml file let mut toml_path = dir.clone(); toml_path.push("oink.toml"); @@ -81,3 +93,25 @@ impl Config { } } +fn setup_dirs(path: &PathBuf) -> Result<(), Error> { + // create main directory + create_dir(path)?; + + // create template directory + let mut templates = path.clone(); + templates.push("templates/"); + create_dir(templates)?; + + // create generated directory + let mut generated = path.clone(); + generated.push("generated/"); + create_dir(generated)?; + + // create main toml + let mut toml = path.clone(); + toml.push("oink.toml"); + File::create(toml)?; + + Ok(()) +} + diff --git a/src/error.rs b/src/error.rs index b2662a2..2446fe5 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,7 +1,15 @@ -use std::process::exit; +use std::{ + path::PathBuf, + process::exit +}; pub fn no_targets() { println!("oink: configuration has no targets"); exit(2); } +pub fn setup_dirs(path: &PathBuf) { + println!("oink: failed to create directory structure at {path:?}"); + exit(3); +} +