use std::{
env,
ffi::OsString,
path::{Path, PathBuf},
};
use crate::{Error, Result, platform::HOME_VAR};
const APP_DIR: &str = ".allot";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Paths {
home: PathBuf,
root: PathBuf,
}
impl Paths {
pub fn from_env() -> Result<Self> {
Self::from_home(env::var_os(HOME_VAR))
}
fn from_home(home: Option<OsString>) -> Result<Self> {
match home {
Some(home) if !home.is_empty() => Ok(Self::under(home)),
_ => Err(Error::Config(format!("{HOME_VAR} is not set"))),
}
}
pub fn under(base: impl Into<PathBuf>) -> Self {
let home = base.into();
Self {
root: home.join(APP_DIR),
home,
}
}
pub fn home(&self) -> &Path {
&self.home
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn bin_dir(&self) -> PathBuf {
self.root.join("bin")
}
pub fn config_file(&self) -> PathBuf {
self.root.join("config.toml")
}
pub fn token_file(&self) -> PathBuf {
self.root.join("token")
}
pub fn database_file(&self) -> PathBuf {
self.root.join("allot.db")
}
pub fn lock_file(&self) -> PathBuf {
self.root.join("allotd.lock")
}
pub fn log_dir(&self) -> PathBuf {
self.root.join("logs")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_paths_from_home_roots_under_dot_dir() {
let home = PathBuf::from(r"C:\Users\someone");
let paths = Paths::from_home(Some(home.clone().into_os_string())).unwrap();
let root = home.join(".allot");
assert_eq!(paths.home(), home);
assert_eq!(paths.root(), root);
assert_eq!(paths.bin_dir(), root.join("bin"));
assert_eq!(paths.config_file(), root.join("config.toml"));
assert_eq!(paths.token_file(), root.join("token"));
assert_eq!(paths.database_file(), root.join("allot.db"));
assert_eq!(paths.log_dir(), root.join("logs"));
assert_eq!(paths.lock_file(), root.join("allotd.lock"));
}
#[test]
fn test_paths_from_home_unset_or_empty_is_config_error() {
for home in [None, Some(OsString::new())] {
let result = Paths::from_home(home);
assert!(matches!(result, Err(Error::Config(message)) if message.contains(HOME_VAR)));
}
}
#[test]
fn test_paths_from_env_matches_user_profile() {
if let Some(home) = env::var_os(HOME_VAR).filter(|home| !home.is_empty()) {
assert_eq!(Paths::from_env().unwrap(), Paths::under(home));
}
}
}