aboutsummaryrefslogtreecommitdiff
path: root/lib/src/session.rs
diff options
context:
space:
mode:
Diffstat (limited to 'lib/src/session.rs')
-rw-r--r--lib/src/session.rs103
1 files changed, 103 insertions, 0 deletions
diff --git a/lib/src/session.rs b/lib/src/session.rs
new file mode 100644
index 0000000..8d142ec
--- /dev/null
+++ b/lib/src/session.rs
@@ -0,0 +1,103 @@
1use std::{cmp::Ordering, str::FromStr};
2
3#[derive(Copy, Clone, Debug, Eq, PartialEq)]
4pub struct Version {
5 major: u16,
6 minor: u16,
7 patch: Option<u16>,
8}
9
10impl Ord for Version {
11 fn cmp(&self, other: &Self) -> Ordering {
12 let score = |v: &Version| v.major * 100 + v.minor * 10 + v.patch.unwrap_or(0);
13 score(self).cmp(&score(other))
14 }
15}
16
17impl PartialOrd for Version {
18 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
19 Some(self.cmp(other))
20 }
21}
22
23fn parse_number(s: &str) -> Option<u16> {
24 s.chars()
25 .take_while(|c| c.is_digit(10))
26 .collect::<String>()
27 .parse::<u16>()
28 .ok()
29}
30
31fn parse_version(s: &str) -> Option<Version> {
32 match s.split(' ').collect::<Vec<_>>().as_slice() {
33 [_, _, version] => {
34 let mut parts = version.split('.');
35 let major = parse_number(parts.next()?)?;
36 let minor = parse_number(parts.next()?)?;
37 let patch = parts.next().map(|p| parse_number(p)).flatten();
38 Some(Version {
39 major,
40 minor,
41 patch,
42 })
43 }
44 _ => None,
45 }
46}
47
48impl FromStr for Version {
49 type Err = ();
50 fn from_str(s: &str) -> Result<Self, Self::Err> {
51 parse_version(s).ok_or(())
52 }
53}
54
55#[non_exhaustive]
56pub struct SessionInfo {
57 nix_version: Version,
58}
59
60impl SessionInfo {
61 pub fn from_version(nix_version: Version) -> Self {
62 Self { nix_version }
63 }
64
65 pub fn version(&self) -> &Version {
66 &self.nix_version
67 }
68}
69
70pub fn get_nix_version() -> Option<Version> {
71 "nix (Nix) 2.4pre20211006_53e4794".parse::<Version>().ok()
72}
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77
78 #[test]
79 fn parse_trivial() {
80 let v = "nix (Nix) 1.6.1".parse::<Version>().ok();
81 assert!(v.is_some())
82 }
83
84 #[test]
85 fn parse() {
86 let v = "nix (Nix) 2.4pre20211006_53e4794".parse::<Version>().ok();
87 assert!(v.is_some())
88 }
89
90 #[test]
91 fn compare_trivial() {
92 let v1 = "nix (Nix) 1.6.1".parse::<Version>().ok();
93 let v2 = "nix (Nix) 1.7.2".parse::<Version>().ok();
94 assert!(v2 > v1);
95 }
96
97 #[test]
98 fn compare() {
99 let v1 = "nix (Nix) 1.7".parse::<Version>().ok();
100 let v2 = "nix (Nix) 2.4pre20211006_53e4794".parse::<Version>().ok();
101 assert!(v2 >= v1);
102 }
103}