use std::{
ffi::OsString,
io,
path::{Path, PathBuf},
};
pub trait Env {
fn home_dir(&self) -> Option<PathBuf>;
fn current_dir(&self) -> io::Result<PathBuf>;
fn var_os(&self, key: &str) -> Option<OsString>;
}
pub struct OsEnv;
impl Env for OsEnv {
fn home_dir(&self) -> Option<PathBuf> {
crate::home_dir_inner()
}
fn current_dir(&self) -> io::Result<PathBuf> {
std::env::current_dir()
}
fn var_os(&self, key: &str) -> Option<OsString> {
std::env::var_os(key)
}
}
pub const OS_ENV: OsEnv = OsEnv {};
pub fn home_dir_with_env(env: &dyn Env) -> Option<PathBuf> {
env.home_dir()
}
pub fn cargo_home_with_env(env: &dyn Env) -> io::Result<PathBuf> {
let cwd = env.current_dir()?;
cargo_home_with_cwd_env(env, &cwd)
}
pub fn cargo_home_with_cwd_env(env: &dyn Env, cwd: &Path) -> io::Result<PathBuf> {
match env.var_os("CARGO_HOME").filter(|h| !h.is_empty()) {
Some(home) => {
let home = PathBuf::from(home);
if home.is_absolute() {
Ok(home)
} else {
Ok(cwd.join(&home))
}
}
_ => home_dir_with_env(env)
.map(|p| p.join(".cargo"))
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "could not find cargo home dir")),
}
}
pub fn rustup_home_with_env(env: &dyn Env) -> io::Result<PathBuf> {
let cwd = env.current_dir()?;
rustup_home_with_cwd_env(env, &cwd)
}
pub fn rustup_home_with_cwd_env(env: &dyn Env, cwd: &Path) -> io::Result<PathBuf> {
match env.var_os("RUSTUP_HOME").filter(|h| !h.is_empty()) {
Some(home) => {
let home = PathBuf::from(home);
if home.is_absolute() {
Ok(home)
} else {
Ok(cwd.join(&home))
}
}
_ => home_dir_with_env(env)
.map(|d| d.join(".rustup"))
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "could not find rustup home dir")),
}
}