nimbus_cli/
version_utils.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5use anyhow::Result;
6
7pub(crate) fn is_before(current_version: &Option<String>, upto_version: usize) -> bool {
8    if current_version.is_none() {
9        false
10    } else {
11        let current_version = current_version.as_deref().unwrap();
12        is_between(0, current_version, upto_version).unwrap_or(false)
13    }
14}
15
16fn is_between(min_version: usize, current_version: &str, max_version: usize) -> Result<bool> {
17    let (major, _) = current_version
18        .split_once('.')
19        .unwrap_or((current_version, ""));
20    let v = major.parse::<usize>()?;
21    Ok(min_version <= v && v < max_version)
22}
23
24/// The following are dumb string manipulations to pad out a version number.
25/// We might use a version library if we need much more functionality, but right now
26/// it's isolated in a single file where it can be replaced as/when necessary.
27///
28/// pad_major_minor_patch will zero pad the minor and patch versions if they are not present.
29/// 112.1.3 --> 112.1.3
30/// 112.1   --> 112.1.0
31/// 112     --> 112.0.0
32pub(crate) fn pad_major_minor_patch(version: &str) -> String {
33    match version_split(version) {
34        (Some(_), Some(_), Some(_)) => version.to_owned(),
35        (Some(major), Some(minor), None) => format!("{major}.{minor}.0"),
36        (Some(major), None, None) => format!("{major}.0.0"),
37        _ => format!("{version}.0.0"),
38    }
39}
40
41/// pad_major_minor will zero pad the minor version if it is not present.
42/// If the patch version is present, then it is left intact.
43/// 112.1.3 --> 112.1.3
44/// 112.1   --> 112.1
45/// 112     --> 112.0
46pub(crate) fn pad_major_minor(version: &str) -> String {
47    match version_split(version) {
48        (Some(_), Some(_), Some(_)) => version.to_owned(),
49        (Some(major), Some(minor), None) => format!("{major}.{minor}"),
50        (Some(major), None, None) => format!("{major}.0"),
51        _ => format!("{version}.0"),
52    }
53}
54
55/// pad_major will keep the string as it is.
56/// If the minor and/or patch versions are present, then they are left intact.
57/// 112.1.3 --> 112.1.3
58/// 112.1   --> 112.1
59/// 112     --> 112
60pub(crate) fn pad_major(version: &str) -> String {
61    version.to_owned()
62}
63
64fn version_split(version: &str) -> (Option<&str>, Option<&str>, Option<&str>) {
65    let mut split = version.splitn(3, '.');
66    (split.next(), split.next(), split.next())
67}