#
cargo_util_schemas/core/
partial_version.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
    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
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248

    use std::fmt::{self, Display};

    use semver::{Comparator, Version, VersionReq};
    use serde_untagged::UntaggedEnumVisitor;

    #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Debug)]
    pub struct PartialVersion {
        pub major: u64,
        pub minor: Option<u64>,
        pub patch: Option<u64>,
        pub pre: Option<semver::Prerelease>,
        pub build: Option<semver::BuildMetadata>,
    }

    impl PartialVersion {
        pub fn to_version(&self) -> Option<Version> {
            Some(Version {
                major: self.major,
                minor: self.minor?,
                patch: self.patch?,
                pre: self.pre.clone().unwrap_or_default(),
                build: self.build.clone().unwrap_or_default(),
            })
        }

        pub fn to_caret_req(&self) -> VersionReq {
            VersionReq {
                comparators: vec![Comparator {
                    op: semver::Op::Caret,
                    major: self.major,
                    minor: self.minor,
                    patch: self.patch,
                    pre: self.pre.as_ref().cloned().unwrap_or_default(),
                }],
            }
        }

        /// Check if this matches a version, including build metadata
        ///
        /// Build metadata does not affect version precedence but may be necessary for uniquely
        /// identifying a package.
        pub fn matches(&self, version: &Version) -> bool {
            if !version.pre.is_empty() && self.pre.is_none() {
                // Pre-release versions must be explicitly opted into, if for no other reason than to
                // give us room to figure out and define the semantics
                return false;
            }
            self.major == version.major
                && self.minor.map(|f| f == version.minor).unwrap_or(true)
                && self.patch.map(|f| f == version.patch).unwrap_or(true)
                && self.pre.as_ref().map(|f| f == &version.pre).unwrap_or(true)
                && self
                    .build
                    .as_ref()
                    .map(|f| f == &version.build)
                    .unwrap_or(true)
        }
    }

    impl From<semver::Version> for PartialVersion {
        fn from(ver: semver::Version) -> Self {
            let pre = if ver.pre.is_empty() {
                None
            } else {
                Some(ver.pre)
            };
            let build = if ver.build.is_empty() {
                None
            } else {
                Some(ver.build)
            };
            Self {
                major: ver.major,
                minor: Some(ver.minor),
                patch: Some(ver.patch),
                pre,
                build,
            }
        }
    }

    impl std::str::FromStr for PartialVersion {
        type Err = PartialVersionError;

        fn from_str(value: &str) -> Result<Self, Self::Err> {
            match semver::Version::parse(value) {
                Ok(ver) => Ok(ver.into()),
                Err(_) => {
                    // HACK: Leverage `VersionReq` for partial version parsing
                    let mut version_req = match semver::VersionReq::parse(value) {
                        Ok(req) => req,
                        Err(_) if value.contains('-') => return Err(ErrorKind::Prerelease.into()),
                        Err(_) if value.contains('+') => return Err(ErrorKind::BuildMetadata.into()),
                        Err(_) => return Err(ErrorKind::Unexpected.into()),
                    };
                    if version_req.comparators.len() != 1 {
                        return Err(ErrorKind::VersionReq.into());
                    }
                    let comp = version_req.comparators.pop().unwrap();
                    if comp.op != semver::Op::Caret {
                        return Err(ErrorKind::VersionReq.into());
                    } else if value.starts_with('^') {
                        // Can't distinguish between `^` present or not
                        return Err(ErrorKind::VersionReq.into());
                    }
                    let pre = if comp.pre.is_empty() {
                        None
                    } else {
                        Some(comp.pre)
                    };
                    Ok(Self {
                        major: comp.major,
                        minor: comp.minor,
                        patch: comp.patch,
                        pre,
                        build: None,
                    })
                }
            }
        }
    }

    impl Display for PartialVersion {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            let major = self.major;
            write!(f, "{major}")?;
            if let Some(minor) = self.minor {
                write!(f, ".{minor}")?;
            }
            if let Some(patch) = self.patch {
                write!(f, ".{patch}")?;
            }
            if let Some(pre) = self.pre.as_ref() {
                write!(f, "-{pre}")?;
            }
            if let Some(build) = self.build.as_ref() {
                write!(f, "+{build}")?;
            }
            Ok(())
        }
    }

    impl serde::Serialize for PartialVersion {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: serde::Serializer,
        {
            serializer.collect_str(self)
        }
    }

    impl<'de> serde::Deserialize<'de> for PartialVersion {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            UntaggedEnumVisitor::new()
                .expecting("SemVer version")
                .string(|value| value.parse().map_err(serde::de::Error::custom))
                .deserialize(deserializer)
        }
    }

    /// Error parsing a [`PartialVersion`].
    #[derive(Debug, thiserror::Error)]
    #[error(transparent)]
    pub struct PartialVersionError(#[from] ErrorKind);

    /// Non-public error kind for [`PartialVersionError`].
    #[non_exhaustive]
    #[derive(Debug, thiserror::Error)]
    enum ErrorKind {
        #[error("unexpected version requirement, expected a version like \"1.32\"")]
        VersionReq,

        #[error("unexpected prerelease field, expected a version like \"1.32\"")]
        Prerelease,

        #[error("unexpected build field, expected a version like \"1.32\"")]
        BuildMetadata,

        #[error("expected a version like \"1.32\"")]
        Unexpected,
    }

    #[cfg(test)]
    mod test {
        use super::*;
        use snapbox::prelude::*;
        use snapbox::str;

        #[test]
        fn parse_success() {
            let cases = &[
                // Valid pre-release
                ("1.43.0-beta.1", str!["1.43.0-beta.1"]),
                // Valid pre-release with wildcard
                ("1.43.0-beta.1.x", str!["1.43.0-beta.1.x"]),
            ];
            for (input, expected) in cases {
                let actual: Result<PartialVersion, _> = input.parse();
                let actual = match actual {
                    Ok(result) => result.to_string(),
                    Err(err) => format!("didn't pass: {err}"),
                };
                snapbox::assert_data_eq!(actual, expected.clone().raw());
            }
        }

        #[test]
        fn parse_errors() {
            let cases = &[
                // Disallow caret
                (
                    "^1.43",
                    str![[r#"unexpected version requirement, expected a version like "1.32""#]],
                ),
                // Bad pre-release
                (
                    "1.43-beta.1",
                    str![[r#"unexpected prerelease field, expected a version like "1.32""#]],
                ),
                // Weird wildcard
                (
                    "x",
                    str![[r#"unexpected version requirement, expected a version like "1.32""#]],
                ),
                (
                    "1.x",
                    str![[r#"unexpected version requirement, expected a version like "1.32""#]],
                ),
                (
                    "1.1.x",
                    str![[r#"unexpected version requirement, expected a version like "1.32""#]],
                ),
                // Non-sense
                ("foodaddle", str![[r#"expected a version like "1.32""#]]),
            ];
            for (input, expected) in cases {
                let actual: Result<PartialVersion, _> = input.parse();
                let actual = match actual {
                    Ok(result) => format!("didn't fail: {result:?}"),
                    Err(err) => err.to_string(),
                };
                snapbox::assert_data_eq!(actual, expected.clone().raw());
            }
        }
    }