multiversx_sc_meta_lib/cargo_toml/
version_req.rs

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
use crate::{
    version::FrameworkVersion,
    version_history::{find_version_by_str, LAST_VERSION},
};

/// Crate version requirements, as expressed in Cargo.toml. A very crude version.
///
/// TODO: replace with semver::VersionReq at some point.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionReq {
    pub semver: FrameworkVersion,
    pub is_strict: bool,
}
impl VersionReq {
    pub fn from_version_str(raw: &str) -> Option<Self> {
        if let Some(stripped_version) = raw.strip_prefix('=') {
            Some(VersionReq {
                semver: find_version_by_str(stripped_version)?.clone(),
                is_strict: true,
            })
        } else {
            Some(VersionReq {
                semver: find_version_by_str(raw)?.clone(),
                is_strict: false,
            })
        }
    }

    pub fn from_version_str_or_latest(raw: &str) -> Self {
        if let Some(stripped_version) = raw.strip_prefix('=') {
            VersionReq {
                semver: find_version_by_str(stripped_version)
                    .unwrap_or(&LAST_VERSION)
                    .clone(),
                is_strict: true,
            }
        } else {
            VersionReq {
                semver: find_version_by_str(raw).unwrap_or(&LAST_VERSION).clone(),
                is_strict: false,
            }
        }
    }

    pub fn strict(self) -> Self {
        Self {
            semver: self.semver,
            is_strict: true,
        }
    }

    pub fn into_string(self) -> String {
        if self.is_strict {
            format!("={}", self.semver)
        } else {
            self.semver.to_string()
        }
    }
}