1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
use std::fmt::{self, Display, Formatter};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Operating system version.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Version {
    /// Unknown version.
    Unknown,
    /// Semantic version (major.minor.patch).
    Semantic(u64, u64, u64),
    /// Rolling version. Optionally contains the release date in the string format.
    Rolling(Option<String>),
    /// Custom version format.
    Custom(String),
}

impl Version {
    /// Constructs `VersionType` from the given string.
    ///
    /// Returns `VersionType::Unknown` if the string is empty. If it can be parsed as a semantic
    /// version, then `VersionType::Semantic`, otherwise `VersionType::Custom`.
    ///
    /// # Examples
    ///
    /// ```
    /// use os_info::Version;
    ///
    /// let v = Version::from_string("custom");
    /// assert_eq!(Version::Custom("custom".to_owned()), v);
    ///
    /// let v = Version::from_string("1.2.3");
    /// assert_eq!(Version::Semantic(1, 2, 3), v);
    /// ```
    pub fn from_string<S: Into<String> + AsRef<str>>(s: S) -> Self {
        if s.as_ref().is_empty() {
            Self::Unknown
        } else if let Some((major, minor, patch)) = parse_version(s.as_ref()) {
            Self::Semantic(major, minor, patch)
        } else {
            Self::Custom(s.into())
        }
    }
}

impl Default for Version {
    fn default() -> Self {
        Version::Unknown
    }
}

impl Display for Version {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            Self::Unknown => f.write_str("Unknown"),
            Self::Semantic(major, minor, patch) => write!(f, "{major}.{minor}.{patch}"),
            Self::Rolling(ref date) => {
                let date = match date {
                    Some(date) => format!(" ({date})"),
                    None => "".to_owned(),
                };
                write!(f, "Rolling Release{date}")
            }
            Self::Custom(ref version) => write!(f, "{version}"),
        }
    }
}

fn parse_version(s: &str) -> Option<(u64, u64, u64)> {
    let mut iter = s.trim().split_terminator('.').fuse();

    let major = iter.next().and_then(|s| s.parse().ok())?;
    let minor = iter.next().unwrap_or("0").parse().ok()?;
    let patch = iter.next().unwrap_or("0").parse().ok()?;

    if iter.next().is_some() {
        return None;
    }

    Some((major, minor, patch))
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn parse_semantic_version() {
        let data = [
            ("", None),
            ("version", None),
            ("1", Some((1, 0, 0))),
            ("1.", Some((1, 0, 0))),
            ("1.2", Some((1, 2, 0))),
            ("1.2.", Some((1, 2, 0))),
            ("1.2.3", Some((1, 2, 3))),
            ("1.2.3.", Some((1, 2, 3))),
            ("1.2.3.  ", Some((1, 2, 3))),
            ("   1.2.3.", Some((1, 2, 3))),
            ("   1.2.3.  ", Some((1, 2, 3))),
            ("1.2.3.4", None),
            ("1.2.3.4.5.6.7.8.9", None),
        ];

        for (s, expected) in &data {
            let result = parse_version(s);
            assert_eq!(expected, &result);
        }
    }

    #[test]
    fn from_string() {
        let custom_version = "some version";
        let data = [
            ("", Version::Unknown),
            ("1.2.3", Version::Semantic(1, 2, 3)),
            (custom_version, Version::Custom(custom_version.to_owned())),
        ];

        for (s, expected) in &data {
            let version = Version::from_string(*s);
            assert_eq!(expected, &version);
        }
    }

    #[test]
    fn default() {
        assert_eq!(Version::Unknown, Version::default());
    }

    #[test]
    fn display() {
        let data = [
            (Version::Unknown, "Unknown"),
            (Version::Semantic(1, 5, 0), "1.5.0"),
            (Version::Rolling(None), "Rolling Release"),
            (
                Version::Rolling(Some("date".to_owned())),
                "Rolling Release (date)",
            ),
        ];

        for (version, expected) in &data {
            assert_eq!(expected, &version.to_string());
        }
    }
}