1use std::path::MAIN_SEPARATOR;
2use std::fs::create_dir_all;
3use std::env::var;
4use anyhow::Result;
5
6pub struct Config {
7 database_file: String,
8 script_file: String,
9 projects_dir: String,
10}
11impl Config {
12 pub fn database_file(&self) -> String {
13 self.database_file.clone()
14 }
15
16 pub fn script_file(&self) -> String {
17 self.script_file.clone()
18 }
19
20 pub fn projects_dir(&self) -> String {
21 self.projects_dir.clone()
22 }
23}
24
25#[cfg(unix)]
26impl Config {
27 pub fn new() -> Result<Self> {
28 let home = var("HOME")?;
29 create_dir_all(home.clone())?;
30 Ok(Config {
31 database_file: format!("{}{}.gcd{}gcd.db", home, MAIN_SEPARATOR, MAIN_SEPARATOR),
32 script_file: format!("{}{}.gcd{}gcd-cd.sh", home, MAIN_SEPARATOR, MAIN_SEPARATOR),
33 projects_dir: format!("{}{}", home, MAIN_SEPARATOR),
34 })
35 }
36}
37
38#[cfg(windows)]
39impl Config {
40 pub fn new() -> Result<Self> {
41 let appdata = var("APPDATA")?;
42 let home = format!(
43 "{}{}",
44 var("HOMEDRIVE")?,
45 var("HOMEPATH")?
46 );
47 create_dir_all(appdata.clone())?;
48 Ok(Config {
49 database_file: format!("{}{}.gcd{}gcd.db", appdata, MAIN_SEPARATOR, MAIN_SEPARATOR),
50 script_file: format!(
51 "{}{}.gcd{}gcd-cd.bat",
52 appdata, MAIN_SEPARATOR, MAIN_SEPARATOR
53 ),
54 projects_dir: format!("{}{}", home, MAIN_SEPARATOR),
55 })
56 }
57}
58
59#[cfg(test)]
60mod test {
61 use std::env::set_var;
62 use super::*;
63
64 #[cfg(unix)]
65 #[test]
66 fn test_config() {
67 set_var("HOME", "target/tmp/testhome");
68 let config = Config::new().unwrap();
69
70 assert_eq!(config.database_file(), "target/tmp/testhome/.gcd/gcd.db");
71 assert_eq!(config.script_file(), "target/tmp/testhome/.gcd/gcd-cd.sh");
72 assert_eq!(config.projects_dir(), "target/tmp/testhome/");
73 }
74
75 #[cfg(windows)]
76 #[test]
77 fn test_config() {
78 set_var("APPDATA", "target\\tmp\\appdata");
79 set_var("HOMEDRIVE", "c:\\");
80 set_var("HOMEPATH", "home");
81
82 let config = Config::new().unwrap();
83
84 assert_eq!(config.database_file(), "target\\tmp\\appdata\\.gcd\\gcd.db");
85 assert_eq!(config.script_file(), "target\\tmp\\appdata\\.gcd\\gcd-cd.bat");
86 assert_eq!(config.projects_dir(), "c:\\home\\");
87
88 }
89}