1use std::{
2 env,
3 ffi::OsString,
4 path::{Path, PathBuf},
5};
6
7use crate::{Error, Result, platform::HOME_VAR};
8
9const APP_DIR: &str = ".allot";
10
11#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Paths {
21 home: PathBuf,
22 root: PathBuf,
23}
24
25impl Paths {
26 pub fn from_env() -> Result<Self> {
33 Self::from_home(env::var_os(HOME_VAR))
34 }
35
36 fn from_home(home: Option<OsString>) -> Result<Self> {
37 match home {
38 Some(home) if !home.is_empty() => Ok(Self::under(home)),
39 _ => Err(Error::Config(format!("{HOME_VAR} is not set"))),
40 }
41 }
42
43 pub fn under(base: impl Into<PathBuf>) -> Self {
45 let home = base.into();
46 Self {
47 root: home.join(APP_DIR),
48 home,
49 }
50 }
51
52 pub fn home(&self) -> &Path {
55 &self.home
56 }
57
58 pub fn root(&self) -> &Path {
60 &self.root
61 }
62
63 pub fn bin_dir(&self) -> PathBuf {
65 self.root.join("bin")
66 }
67
68 pub fn config_file(&self) -> PathBuf {
70 self.root.join("config.toml")
71 }
72
73 pub fn token_file(&self) -> PathBuf {
75 self.root.join("token")
76 }
77
78 pub fn database_file(&self) -> PathBuf {
80 self.root.join("allot.db")
81 }
82
83 pub fn lock_file(&self) -> PathBuf {
85 self.root.join("allotd.lock")
86 }
87
88 pub fn log_dir(&self) -> PathBuf {
90 self.root.join("logs")
91 }
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97
98 #[test]
99 fn test_paths_from_home_roots_under_dot_dir() {
100 let home = PathBuf::from(r"C:\Users\someone");
101 let paths = Paths::from_home(Some(home.clone().into_os_string())).unwrap();
102 let root = home.join(".allot");
103 assert_eq!(paths.home(), home);
104 assert_eq!(paths.root(), root);
105 assert_eq!(paths.bin_dir(), root.join("bin"));
106 assert_eq!(paths.config_file(), root.join("config.toml"));
107 assert_eq!(paths.token_file(), root.join("token"));
108 assert_eq!(paths.database_file(), root.join("allot.db"));
109 assert_eq!(paths.log_dir(), root.join("logs"));
110 assert_eq!(paths.lock_file(), root.join("allotd.lock"));
111 }
112
113 #[test]
114 fn test_paths_from_home_unset_or_empty_is_config_error() {
115 for home in [None, Some(OsString::new())] {
116 let result = Paths::from_home(home);
117 assert!(matches!(result, Err(Error::Config(message)) if message.contains(HOME_VAR)));
118 }
119 }
120
121 #[test]
122 fn test_paths_from_env_matches_user_profile() {
123 if let Some(home) = env::var_os(HOME_VAR).filter(|home| !home.is_empty()) {
124 assert_eq!(Paths::from_env().unwrap(), Paths::under(home));
125 }
126 }
127}