✨ feat(utils): create assure_config_dir_exists function
- add utility function to create config directory if it doesn't exist - handle home directory expansion and error conditions
This commit is contained in:
committed by
Jeremiah Russell
parent
3045f0a8f4
commit
f53ffe7d8a
38
src/utils.rs
Normal file
38
src/utils.rs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
use std::{env, fs, io};
|
||||||
|
|
||||||
|
use crate::Error;
|
||||||
|
|
||||||
|
pub(crate) fn assure_config_dir_exists(dir: &str) -> Result<String, Error> {
|
||||||
|
let trdir = dir.trim();
|
||||||
|
if trdir.is_empty() {
|
||||||
|
return Err(Error::DirectoryUnset);
|
||||||
|
}
|
||||||
|
|
||||||
|
let expanded_config_dir = if trdir.as_bytes()[0] == b'~' {
|
||||||
|
match env::var("HOME")
|
||||||
|
.ok()
|
||||||
|
.or_else(|| env::var("UserProfile").ok())
|
||||||
|
{
|
||||||
|
None => {
|
||||||
|
return Err(Error::HomeExpansionFailed(trdir.to_string()));
|
||||||
|
}
|
||||||
|
Some(mut user) => {
|
||||||
|
user.push_str(&trdir[1..]);
|
||||||
|
user
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
trdir.to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(err) = fs::create_dir(&expanded_config_dir) {
|
||||||
|
if err.kind() != io::ErrorKind::AlreadyExists {
|
||||||
|
return Err(Error::DirectoryCreationFailed((
|
||||||
|
expanded_config_dir,
|
||||||
|
Box::new(err),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(expanded_config_dir)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user