Skip to main content

ipcez/
os.rs

1//! OS detection from the `os` environment variable.
2//!
3//! Single responsibility: detect operating system (Linux or Windows) from environment.
4
5use std::env;
6use std::error::Error;
7use std::fmt;
8
9/// Detected operating system from the environment.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum OsKind {
12    Linux,
13    Windows,
14}
15
16/// Error when detecting OS from the `os` environment variable.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum OsDetectionError {
19    /// The `os` environment variable was not set.
20    NotFound,
21    /// The `os` environment variable had an invalid value.
22    InvalidValue(String),
23}
24
25impl fmt::Display for OsDetectionError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            OsDetectionError::NotFound => {
29                write!(f, "environment variable \"os\" was not found")
30            }
31            OsDetectionError::InvalidValue(v) => {
32                write!(
33                    f,
34                    "environment variable \"os\" had invalid value \"{}\"; expected \"linux\" or \"windows\"",
35                    v
36                )
37            }
38        }
39    }
40}
41
42impl Error for OsDetectionError {}
43
44/// Detects the OS by reading the `os` environment variable.
45///
46/// Expects the variable to be set to `"linux"` or `"windows"` (case-insensitive).
47/// Returns an error if the variable is missing or has any other value.
48pub fn detect_os_from_env() -> Result<OsKind, OsDetectionError> {
49    let raw = env::var("os").map_err(|_| OsDetectionError::NotFound)?;
50    let value = raw.trim().to_lowercase();
51    match value.as_str() {
52        "linux" => Ok(OsKind::Linux),
53        "windows" => Ok(OsKind::Windows),
54        _ => Err(OsDetectionError::InvalidValue(raw)),
55    }
56}