Skip to main content

ghactions_toolcache/
platform.rs

1//! # Tool Cache Platform
2
3use std::fmt::Display;
4
5/// Tool Cache Platform
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum ToolPlatform {
8    /// Windows
9    Windows,
10    /// Linux
11    Linux,
12    /// MacOS
13    MacOS,
14    /// Any
15    Any,
16}
17
18impl ToolPlatform {
19    /// Get the platform from the current OS
20    pub fn from_current_os() -> Self {
21        match std::env::consts::OS {
22            "windows" => ToolPlatform::Windows,
23            "linux" => ToolPlatform::Linux,
24            "macos" => ToolPlatform::MacOS,
25            _ => ToolPlatform::Any,
26        }
27    }
28}
29
30impl Display for ToolPlatform {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        match self {
33            ToolPlatform::Linux => write!(f, "linux"),
34            ToolPlatform::MacOS => write!(f, "macos"),
35            ToolPlatform::Windows => write!(f, "windows"),
36            ToolPlatform::Any => write!(f, "any"),
37        }
38    }
39}
40
41impl From<&str> for ToolPlatform {
42    fn from(value: &str) -> Self {
43        match value {
44            "windows" => ToolPlatform::Windows,
45            "linux" => ToolPlatform::Linux,
46            "macos" => ToolPlatform::MacOS,
47            _ => ToolPlatform::Any,
48        }
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn test_from_current_os() {
58        // This will depend on the OS running the test
59        let platform = ToolPlatform::from_current_os();
60        match std::env::consts::OS {
61            "windows" => assert_eq!(platform, ToolPlatform::Windows),
62            "linux" => assert_eq!(platform, ToolPlatform::Linux),
63            "macos" => assert_eq!(platform, ToolPlatform::MacOS),
64            _ => assert_eq!(platform, ToolPlatform::Any),
65        }
66    }
67
68    #[test]
69    fn test_to_string() {
70        assert_eq!(ToolPlatform::Windows.to_string(), "windows");
71        assert_eq!(ToolPlatform::Linux.to_string(), "linux");
72        assert_eq!(ToolPlatform::MacOS.to_string(), "macos");
73        assert_eq!(ToolPlatform::Any.to_string(), "any");
74    }
75
76    #[test]
77    fn test_from_str() {
78        assert_eq!(ToolPlatform::from("windows"), ToolPlatform::Windows);
79        assert_eq!(ToolPlatform::from("linux"), ToolPlatform::Linux);
80        assert_eq!(ToolPlatform::from("macos"), ToolPlatform::MacOS);
81        assert_eq!(ToolPlatform::from("unknown"), ToolPlatform::Any);
82        assert_eq!(ToolPlatform::from(""), ToolPlatform::Any);
83    }
84}