use crate::WallSwitchResult;
use std::{
borrow::Cow,
env,
path::{Path, PathBuf},
};
#[cfg(unix)]
const DEFAULT_TEMP_DIR: &str = "/tmp";
#[cfg(windows)]
const DEFAULT_TEMP_DIR: &str = "C:\\Windows\\Temp";
#[cfg(not(any(unix, windows)))]
const DEFAULT_TEMP_DIR: &str = ".";
#[cfg(unix)]
const DEFAULT_HOME_DIR: &str = "/";
#[cfg(windows)]
const DEFAULT_HOME_DIR: &str = "C:\\Users";
#[cfg(not(any(unix, windows)))]
const DEFAULT_HOME_DIR: &str = ".";
pub struct Environment<'a> {
pub home_dir: Cow<'a, Path>,
pub temp_dir: Cow<'a, Path>,
pub pkg_name: Cow<'a, str>,
}
impl Environment<'_> {
pub fn fallback() -> Environment<'static> {
Environment {
home_dir: Cow::Borrowed(Path::new(DEFAULT_HOME_DIR)),
temp_dir: Cow::Borrowed(Path::new(DEFAULT_TEMP_DIR)),
pkg_name: Cow::Borrowed("wallswitch"),
}
}
pub fn new() -> WallSwitchResult<Environment<'static>> {
let home_dir = fetch_home_dir();
let temp_dir = fetch_temp_dir();
let pkg_name = fetch_pkg_name();
Ok(Environment {
home_dir: Cow::Owned(home_dir),
temp_dir: Cow::Owned(temp_dir),
pkg_name: Cow::Owned(pkg_name),
})
}
pub fn get_home_dir(&self) -> &Path {
&self.home_dir
}
pub fn get_temp_dir(&self) -> &Path {
&self.temp_dir
}
pub fn get_pkg_name(&self) -> &str {
&self.pkg_name
}
}
fn fetch_temp_dir() -> PathBuf {
env::temp_dir()
}
fn fetch_pkg_name() -> String {
env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "wallswitch".to_string())
}
fn fetch_home_dir() -> PathBuf {
#[cfg(unix)]
{
env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_else(env::temp_dir)
}
#[cfg(windows)]
{
env::var_os("USERPROFILE")
.map(PathBuf::from)
.unwrap_or_else(env::temp_dir)
}
#[cfg(not(any(unix, windows)))]
{
env::temp_dir()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fallback_initialization() {
let env = Environment::fallback();
assert!(!env.get_home_dir().as_os_str().is_empty());
assert!(!env.get_temp_dir().as_os_str().is_empty());
assert_eq!(env.get_pkg_name(), "wallswitch");
}
#[test]
fn test_new_initialization() {
let env_result = Environment::new();
assert!(env_result.is_ok());
let env = env_result.unwrap();
assert!(env.get_home_dir().exists());
assert!(
env.get_temp_dir().exists() || cfg!(any(target_os = "none", target_arch = "wasm32"))
);
}
}