1use std::fmt;
5use std::path::{Path, PathBuf};
6
7use crate::{CunoError, Env, ExitClass};
8
9pub fn cuno_home(env: &Env) -> Result<PathBuf, HomeError> {
17 let set = |name| env.get(name).filter(|value| !value.is_empty());
18 if let Some(home) = env.set_value("CUNO_HOME") {
19 let home = PathBuf::from(home);
20 return if home.is_absolute() {
21 Ok(home)
22 } else {
23 Err(HomeError::NotAbsolute(home))
24 };
25 }
26 set("USERPROFILE")
27 .or_else(|| set("HOME"))
28 .map(|user| Path::new(user).join(".cuno"))
29 .ok_or(HomeError::NotFound)
30}
31
32#[derive(Debug, PartialEq, Eq)]
34pub enum HomeError {
35 NotFound,
37 NotAbsolute(PathBuf),
39}
40
41impl fmt::Display for HomeError {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 match self {
44 HomeError::NotFound => f.write_str(
45 "cannot tell where the cuno home is: none of CUNO_HOME, USERPROFILE and HOME is set",
46 ),
47 HomeError::NotAbsolute(path) => write!(
48 f,
49 "CUNO_HOME is `{}`, which is not an absolute path",
50 path.display()
51 ),
52 }
53 }
54}
55
56impl std::error::Error for HomeError {}
57
58impl CunoError for HomeError {
59 fn exit_class(&self) -> ExitClass {
60 ExitClass::Setup
61 }
62
63 fn help(&self) -> Option<String> {
64 Some(match self {
65 HomeError::NotFound => "set CUNO_HOME to the directory cuno should use".to_owned(),
66 HomeError::NotAbsolute(_) => {
67 "set CUNO_HOME to an absolute path, including the drive on Windows".to_owned()
68 }
69 })
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76 use crate::NameCase;
77
78 fn env(pairs: &[(&str, &str)]) -> Env {
79 Env::from_pairs(
80 pairs.iter().map(|(k, v)| ((*k).into(), (*v).into())),
81 NameCase::Insensitive,
82 )
83 }
84
85 #[test]
88 fn the_home_follows_cuno_home_then_the_user_directory() {
89 let absolute = std::env::temp_dir().join("cuno-home");
90 let absolute = absolute.to_str().unwrap();
91 let cases: [(&[(&str, &str)], PathBuf); 4] = [
92 (
93 &[("CUNO_HOME", absolute), ("USERPROFILE", "u")],
94 PathBuf::from(absolute),
95 ),
96 (
97 &[("CUNO_HOME", ""), ("HOME", "h")],
98 Path::new("h").join(".cuno"),
99 ),
100 (
101 &[("USERPROFILE", "u"), ("HOME", "h")],
102 Path::new("u").join(".cuno"),
103 ),
104 (&[("HOME", "h")], Path::new("h").join(".cuno")),
105 ];
106 for (pairs, expected) in cases {
107 assert_eq!(cuno_home(&env(pairs)), Ok(expected), "{pairs:?}");
108 }
109 }
110
111 #[test]
114 fn cuno_home_must_be_absolute() {
115 let mut values = vec!["rel", "./x"];
116 if cfg!(windows) {
117 values.extend(["/x", r"\x", "C:x"]);
118 }
119 for value in values {
120 let err = cuno_home(&env(&[("CUNO_HOME", value), ("HOME", "h")])).unwrap_err();
121 assert_eq!(err, HomeError::NotAbsolute(value.into()), "{value}");
122 assert_eq!(
123 err.to_string(),
124 format!("CUNO_HOME is `{value}`, which is not an absolute path")
125 );
126 assert!(err.help().unwrap().contains("absolute path"));
127 }
128 }
129
130 #[test]
133 fn no_home_at_all_is_a_setup_problem_saying_what_to_set() {
134 let err = cuno_home(&env(&[("HOME", "")])).unwrap_err();
135 assert_eq!(err, HomeError::NotFound);
136 assert_eq!(err.exit_class(), ExitClass::Setup);
137 assert!(err.help().unwrap().contains("CUNO_HOME"));
138 assert!(err.to_string().contains("USERPROFILE"));
139 }
140}