1use std::env;
6use std::error::Error;
7use std::fmt;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum OsKind {
12 Linux,
13 Windows,
14}
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum OsDetectionError {
19 NotFound,
21 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
44pub 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}