use std::path::MAIN_SEPARATOR;
use std::fs::create_dir_all;
use std::env::var;
use anyhow::Result;
pub struct Config {
database_file: String,
script_file: String,
projects_dir: String,
}
impl Config {
pub fn database_file(&self) -> String {
self.database_file.clone()
}
pub fn script_file(&self) -> String {
self.script_file.clone()
}
pub fn projects_dir(&self) -> String {
self.projects_dir.clone()
}
}
#[cfg(unix)]
impl Config {
pub fn new() -> Result<Self> {
let home = var("HOME")?;
create_dir_all(home.clone())?;
Ok(Config {
database_file: format!("{}{}.gcd{}gcd.db", home, MAIN_SEPARATOR, MAIN_SEPARATOR),
script_file: format!("{}{}.gcd{}gcd-cd.sh", home, MAIN_SEPARATOR, MAIN_SEPARATOR),
projects_dir: format!("{}{}", home, MAIN_SEPARATOR),
})
}
}
#[cfg(windows)]
impl Config {
pub fn new() -> Result<Self> {
let appdata = var("APPDATA")?;
let home = format!(
"{}{}",
var("HOMEDRIVE")?,
var("HOMEPATH")?
);
create_dir_all(appdata.clone())?;
Ok(Config {
database_file: format!("{}{}.gcd{}gcd.db", appdata, MAIN_SEPARATOR, MAIN_SEPARATOR),
script_file: format!(
"{}{}.gcd{}gcd-cd.bat",
appdata, MAIN_SEPARATOR, MAIN_SEPARATOR
),
projects_dir: format!("{}{}", home, MAIN_SEPARATOR),
})
}
}
#[cfg(test)]
mod test {
use std::env::set_var;
use super::*;
#[cfg(unix)]
#[test]
fn test_config() {
set_var("HOME", "target/tmp/testhome");
let config = Config::new().unwrap();
assert_eq!(config.database_file(), "target/tmp/testhome/.gcd/gcd.db");
assert_eq!(config.script_file(), "target/tmp/testhome/.gcd/gcd-cd.sh");
assert_eq!(config.projects_dir(), "target/tmp/testhome/");
}
#[cfg(windows)]
#[test]
fn test_config() {
set_var("APPDATA", "target\\tmp\\appdata");
set_var("HOMEDRIVE", "c:\\");
set_var("HOMEPATH", "home");
let config = Config::new().unwrap();
assert_eq!(config.database_file(), "target\\tmp\\appdata\\.gcd\\gcd.db");
assert_eq!(config.script_file(), "target\\tmp\\appdata\\.gcd\\gcd-cd.bat");
assert_eq!(config.projects_dir(), "c:\\home\\");
}
}