Skip to main content

nerdbank_gitversioning/
version.rs

1// Copyright (c) .NET Foundation and Contributors. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4use std::cmp::Ordering;
5use std::fmt;
6use std::str::FromStr;
7
8use crate::{Error, Result};
9
10/// A two-, three-, or four-part numeric version.
11///
12/// This type follows the important `System.Version` conventions used by
13/// Nerdbank.GitVersioning: major and minor are always present, while build and
14/// revision may be unspecified. An unspecified component compares less than
15/// zero, just as the corresponding `System.Version` component (whose value is
16/// `-1`) does.
17#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
18pub struct Version {
19    /// The major version.
20    pub major: u32,
21    /// The minor version.
22    pub minor: u32,
23    /// The build component, or `None` when it is unspecified.
24    pub build: Option<u32>,
25    /// The revision component, or `None` when it is unspecified.
26    pub revision: Option<u32>,
27}
28
29impl Version {
30    /// Creates a version with major and minor components.
31    pub const fn new(major: u32, minor: u32) -> Self {
32        Self {
33            major,
34            minor,
35            build: None,
36            revision: None,
37        }
38    }
39
40    /// Creates a version with major, minor, and build components.
41    pub const fn new_with_build(major: u32, minor: u32, build: u32) -> Self {
42        Self {
43            major,
44            minor,
45            build: Some(build),
46            revision: None,
47        }
48    }
49
50    /// Creates a version with all four components.
51    pub const fn new_with_revision(major: u32, minor: u32, build: u32, revision: u32) -> Self {
52        Self {
53            major,
54            minor,
55            build: Some(build),
56            revision: Some(revision),
57        }
58    }
59
60    /// Creates a version from component values using `-1` for unspecified
61    /// build and revision components.
62    pub fn from_system_version_parts(
63        major: i32,
64        minor: i32,
65        build: i32,
66        revision: i32,
67    ) -> Result<Self> {
68        if major < 0 || minor < 0 || build < -1 || revision < -1 || (build == -1 && revision != -1)
69        {
70            return Err(Error::InvalidFormat(
71                "Version components must be non-negative, except that build and revision may be -1."
72                    .to_owned(),
73            ));
74        }
75
76        Ok(match (build, revision) {
77            (-1, -1) => Self::new(major as u32, minor as u32),
78            (build, -1) => Self::new_with_build(major as u32, minor as u32, build as u32),
79            (build, revision) => {
80                Self::new_with_revision(major as u32, minor as u32, build as u32, revision as u32)
81            }
82        })
83    }
84
85    /// Gets the build component using the `System.Version` value `-1` when it
86    /// is unspecified.
87    pub const fn build_or_unspecified(self) -> i64 {
88        match self.build {
89            Some(value) => value as i64,
90            None => -1,
91        }
92    }
93
94    /// Gets the revision component using the `System.Version` value `-1` when
95    /// it is unspecified.
96    pub const fn revision_or_unspecified(self) -> i64 {
97        match self.revision {
98            Some(value) => value as i64,
99            None => -1,
100        }
101    }
102
103    /// Returns a version where the specified number of components are
104    /// guaranteed to be present. Applicable unspecified components become
105    /// zero.
106    ///
107    /// `field_count` must be between zero and four.
108    pub fn ensure_non_negative_components(self, field_count: usize) -> Result<Self> {
109        if field_count > 4 {
110            return Err(Error::InvalidOperation(
111                "The field count must be between 0 and 4.".to_owned(),
112            ));
113        }
114
115        let build = if field_count >= 3 {
116            Some(self.build.unwrap_or(0))
117        } else {
118            self.build
119        };
120        let revision = if field_count >= 4 {
121            Some(self.revision.unwrap_or(0))
122        } else {
123            self.revision
124        };
125
126        Ok(Self {
127            build,
128            revision,
129            ..self
130        })
131    }
132
133    /// Converts this version to a string containing exactly `field_count`
134    /// components, replacing unspecified requested components with zero.
135    ///
136    /// `field_count` must be between zero and four.
137    pub fn to_string_safe(self, field_count: usize) -> Result<String> {
138        if field_count > 4 {
139            return Err(Error::InvalidOperation(
140                "The field count must be between 0 and 4.".to_owned(),
141            ));
142        }
143
144        let version = self.ensure_non_negative_components(field_count)?;
145        let mut fields = [
146            version.major,
147            version.minor,
148            version.build.unwrap_or(0),
149            version.revision.unwrap_or(0),
150        ]
151        .into_iter();
152        Ok((0..field_count)
153            .map(|_| fields.next().expect("field count is bounded").to_string())
154            .collect::<Vec<_>>()
155            .join("."))
156    }
157
158    /// Gets the number of specified components.
159    pub const fn component_count(self) -> usize {
160        if self.revision.is_some() {
161            4
162        } else if self.build.is_some() {
163            3
164        } else {
165            2
166        }
167    }
168}
169
170impl Default for Version {
171    fn default() -> Self {
172        Self::new(0, 0)
173    }
174}
175
176impl fmt::Display for Version {
177    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
178        write!(formatter, "{}.{}", self.major, self.minor)?;
179        if let Some(build) = self.build {
180            write!(formatter, ".{build}")?;
181        }
182        if let Some(revision) = self.revision {
183            write!(formatter, ".{revision}")?;
184        }
185
186        Ok(())
187    }
188}
189
190impl FromStr for Version {
191    type Err = Error;
192
193    fn from_str(value: &str) -> Result<Self> {
194        let fields: Vec<_> = value.split('.').collect();
195        if !(2..=4).contains(&fields.len())
196            || fields
197                .iter()
198                .any(|field| field.is_empty() || !field.bytes().all(|byte| byte.is_ascii_digit()))
199        {
200            return Err(Error::InvalidFormat(format!(
201                "'{value}' is not a two- to four-component version."
202            )));
203        }
204
205        let parse = |field: &str| {
206            field.parse::<i32>().map(|value| value as u32).map_err(|_| {
207                Error::InvalidFormat(format!("'{value}' contains an invalid version component."))
208            })
209        };
210        let major = parse(fields[0])?;
211        let minor = parse(fields[1])?;
212        Ok(match fields.len() {
213            2 => Self::new(major, minor),
214            3 => Self::new_with_build(major, minor, parse(fields[2])?),
215            4 => Self::new_with_revision(major, minor, parse(fields[2])?, parse(fields[3])?),
216            _ => unreachable!(),
217        })
218    }
219}
220
221impl Ord for Version {
222    fn cmp(&self, other: &Self) -> Ordering {
223        (
224            self.major,
225            self.minor,
226            self.build_or_unspecified(),
227            self.revision_or_unspecified(),
228        )
229            .cmp(&(
230                other.major,
231                other.minor,
232                other.build_or_unspecified(),
233                other.revision_or_unspecified(),
234            ))
235    }
236}
237
238impl PartialOrd for Version {
239    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
240        Some(self.cmp(other))
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    #[test]
249    fn parses_and_displays_two_to_four_components() {
250        for text in ["1.2", "1.2.3", "1.2.3.4"] {
251            let version: Version = text.parse().unwrap();
252            assert_eq!(text, version.to_string());
253            assert_eq!(text.split('.').count(), version.component_count());
254        }
255    }
256
257    #[test]
258    fn rejects_invalid_versions() {
259        for text in ["", "1", "1.", "1.2.", "1.2.3.4.5", "-1.2", "1. 2"] {
260            assert!(text.parse::<Version>().is_err(), "{text}");
261        }
262    }
263
264    #[test]
265    fn unspecified_components_affect_equality_and_ordering() {
266        assert_ne!(Version::new(1, 2), Version::new_with_build(1, 2, 0));
267        assert!(Version::new(1, 2) < Version::new_with_build(1, 2, 0));
268        assert!(Version::new_with_build(1, 2, 3) < Version::new_with_revision(1, 2, 3, 0));
269    }
270
271    #[test]
272    fn safe_format_fills_unspecified_components() {
273        let version = Version::new(1, 2);
274        assert_eq!("", version.to_string_safe(0).unwrap());
275        assert_eq!("1", version.to_string_safe(1).unwrap());
276        assert_eq!("1.2", version.to_string_safe(2).unwrap());
277        assert_eq!("1.2.0", version.to_string_safe(3).unwrap());
278        assert_eq!("1.2.0.0", version.to_string_safe(4).unwrap());
279        assert!(version.to_string_safe(5).is_err());
280    }
281
282    #[test]
283    fn creates_from_system_version_parts() {
284        assert_eq!(
285            Version::new(1, 2),
286            Version::from_system_version_parts(1, 2, -1, -1).unwrap()
287        );
288        assert!(Version::from_system_version_parts(1, 2, -1, 0).is_err());
289    }
290}