use std::env;
use std::error::Error;
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OsKind {
Linux,
Windows,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OsDetectionError {
NotFound,
InvalidValue(String),
}
impl fmt::Display for OsDetectionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
OsDetectionError::NotFound => {
write!(f, "environment variable \"os\" was not found")
}
OsDetectionError::InvalidValue(v) => {
write!(
f,
"environment variable \"os\" had invalid value \"{}\"; expected \"linux\" or \"windows\"",
v
)
}
}
}
}
impl Error for OsDetectionError {}
pub fn detect_os_from_env() -> Result<OsKind, OsDetectionError> {
let raw = env::var("os").map_err(|_| OsDetectionError::NotFound)?;
let value = raw.trim().to_lowercase();
match value.as_str() {
"linux" => Ok(OsKind::Linux),
"windows" => Ok(OsKind::Windows),
_ => Err(OsDetectionError::InvalidValue(raw)),
}
}