use std::env;
use std::fs;
use std::path::PathBuf;
use std::sync::OnceLock;
fn has_env_var(key: &str) -> bool {
match env::var(key) {
Ok(var) => !var.is_empty(),
Err(_) => false,
}
}
fn has_proc_config(path: &str, value: &str) -> bool {
match fs::read_to_string(path) {
Ok(contents) => contents.to_lowercase().contains(value),
Err(_) => false,
}
}
pub fn is_ci() -> bool {
static CI_CACHE: OnceLock<bool> = OnceLock::new();
*CI_CACHE.get_or_init(|| has_env_var("CI"))
}
pub fn is_docker() -> bool {
static DOCKER_CACHE: OnceLock<bool> = OnceLock::new();
*DOCKER_CACHE.get_or_init(|| {
if PathBuf::from("/.dockerenv").exists() {
return true;
}
has_proc_config("/proc/self/cgroup", "docker")
})
}
pub fn is_wsl() -> bool {
static WSL_CACHE: OnceLock<bool> = OnceLock::new();
*WSL_CACHE.get_or_init(|| {
if env::consts::OS != "linux" || is_docker() {
return false;
}
if has_proc_config("/proc/sys/kernel/osrelease", "microsoft") {
return true;
}
has_proc_config("/proc/version", "microsoft")
})
}
pub fn is_test() -> bool {
static TEST_CACHE: OnceLock<bool> = OnceLock::new();
*TEST_CACHE.get_or_init(|| has_env_var("STARBASE_TEST"))
}
#[inline]
pub fn paths() -> Vec<PathBuf> {
let Some(path) = env::var_os("PATH") else {
return vec![];
};
env::split_paths(&path).collect::<Vec<_>>()
}
#[inline]
pub fn bool_var(key: &str) -> bool {
match env::var(key) {
Ok(value) => {
value == "1"
|| value.eq_ignore_ascii_case("true")
|| value.eq_ignore_ascii_case("yes")
|| value.eq_ignore_ascii_case("on")
|| value.eq_ignore_ascii_case("enable")
}
Err(_) => false,
}
}
#[inline]
pub fn path_var(key: &str) -> Option<PathBuf> {
match env::var(key) {
Ok(value) => {
if value.is_empty() {
return None;
}
let path = PathBuf::from(value);
Some(if path.is_absolute() {
path
} else {
env::current_dir()
.expect("Unable to get working directory!")
.join(path)
})
}
Err(_) => None,
}
}
#[inline]
pub fn vendor_home_var<F: FnOnce(PathBuf) -> PathBuf>(key: &str, fallback: F) -> PathBuf {
match path_var(key) {
Some(path) => path,
None => fallback(dirs::home_dir().expect("Unable to get home directory!")),
}
}