Skip to main content

nerdbank_gitversioning/
semantic_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::fmt;
5use std::str::FromStr;
6use std::sync::LazyLock;
7
8use regex::Regex;
9
10use crate::{Error, ReleaseVersionIncrement, Result, Version};
11
12static SEMANTIC_VERSION_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
13    Regex::new(
14        r"(?ix)^v?(?<major>0|[1-9][0-9]*)\.(?<minor>0|[1-9][0-9]*)(?:\.(?<patch>0|[1-9][0-9]*)(?:\.(?<revision>0|[1-9][0-9]*))?)?(?<prerelease>-(?:[0-9a-z-]+|\{height\})(?:\.(?:[0-9a-z-]+|\{height\}))*)?(?<build_metadata>\+(?:[0-9a-z-]+|\{height\})(?:\.(?:[0-9a-z-]+|\{height\}))*)?$",
15    )
16    .expect("the semantic version pattern is valid")
17});
18
19static PRERELEASE_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
20    Regex::new(r"(?i)^-(?:[0-9a-z-]+|\{height\})(?:\.(?:[0-9a-z-]+|\{height\}))*$")
21        .expect("the prerelease pattern is valid")
22});
23
24static BUILD_METADATA_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
25    Regex::new(r"(?i)^\+(?:[0-9a-z-]+|\{height\})(?:\.(?:[0-9a-z-]+|\{height\}))*$")
26        .expect("the build metadata pattern is valid")
27});
28
29/// Identifies positions in a semantic version.
30#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
31#[repr(u8)]
32pub enum VersionPosition {
33    /// The major numeric component.
34    Major,
35    /// The minor numeric component.
36    Minor,
37    /// The build numeric component.
38    Build,
39    /// The revision numeric component.
40    Revision,
41    /// The prerelease portion.
42    Prerelease,
43    /// The build metadata portion.
44    BuildMetadata,
45}
46
47/// Describes a numeric version with optional prerelease and build metadata.
48///
49/// Unlike crates that accept only SemVer 2, this type intentionally supports
50/// the two- to four-part version grammar used by Nerdbank.GitVersioning, along
51/// with the `{height}` macro in prerelease and build metadata identifiers.
52#[derive(Clone, Debug, Eq, Hash, PartialEq)]
53pub struct SemanticVersion {
54    /// The numeric portion of the version.
55    pub version: Version,
56    /// The prerelease portion, including its leading hyphen, or an empty string.
57    pub prerelease: String,
58    /// The build metadata, including its leading plus, or an empty string.
59    pub build_metadata: String,
60}
61
62impl SemanticVersion {
63    /// Initializes a semantic version, validating the prerelease and build
64    /// metadata strings.
65    pub fn new(
66        version: Version,
67        prerelease: impl Into<String>,
68        build_metadata: impl Into<String>,
69    ) -> Result<Self> {
70        let prerelease = prerelease.into();
71        let build_metadata = build_metadata.into();
72        if !prerelease.is_empty() && !PRERELEASE_PATTERN.is_match(&prerelease) {
73            return Err(Error::InvalidFormat(format!(
74                "The prerelease '{prerelease}' is invalid."
75            )));
76        }
77        if !build_metadata.is_empty() && !BUILD_METADATA_PATTERN.is_match(&build_metadata) {
78            return Err(Error::InvalidFormat(format!(
79                "The build metadata '{build_metadata}' is invalid."
80            )));
81        }
82
83        Ok(Self {
84            version,
85            prerelease,
86            build_metadata,
87        })
88    }
89
90    /// Parses a semantic version, returning `None` when the input is invalid.
91    pub fn try_parse(value: &str) -> Option<Self> {
92        value.parse().ok()
93    }
94
95    /// Gets the position where version height should appear.
96    pub fn version_height_position(&self) -> Option<VersionPosition> {
97        if self.prerelease.contains("{height}") {
98            Some(VersionPosition::Prerelease)
99        } else if self.version.build.is_none() {
100            Some(VersionPosition::Build)
101        } else if self.version.revision.is_none() {
102            Some(VersionPosition::Revision)
103        } else {
104            None
105        }
106    }
107
108    /// Gets the position where the first 16 bits of a Git commit ID should
109    /// appear, if any.
110    pub fn git_commit_id_position(&self) -> Option<VersionPosition> {
111        (self.version_height_position() == Some(VersionPosition::Build))
112            .then_some(VersionPosition::Revision)
113    }
114
115    /// Reads one of the four numeric version positions, using `-1` for an
116    /// unspecified build or revision.
117    pub fn read_version_position(&self, position: VersionPosition) -> Result<i64> {
118        Self::read_position(self.version, position)
119    }
120
121    /// Tests whether changing between two semantic versions resets version
122    /// height at the specified position.
123    pub fn will_version_change_reset_version_height(
124        first: &Self,
125        second: &Self,
126        version_height_position: VersionPosition,
127    ) -> Result<bool> {
128        if first == second {
129            return Ok(false);
130        }
131        if version_height_position == VersionPosition::Prerelease {
132            return Ok(first != second);
133        }
134        if version_height_position > VersionPosition::Revision {
135            return Err(Error::InvalidOperation(
136                "Version height must occupy a numeric or prerelease position.".to_owned(),
137            ));
138        }
139
140        for position in [
141            VersionPosition::Major,
142            VersionPosition::Minor,
143            VersionPosition::Build,
144            VersionPosition::Revision,
145        ]
146        .into_iter()
147        .take(version_height_position as usize + 1)
148        {
149            if first.read_version_position(position)? != second.read_version_position(position)? {
150                return Ok(true);
151            }
152        }
153
154        Ok(false)
155    }
156
157    /// Checks whether a numeric version may have been produced by this
158    /// semantic version specification.
159    pub fn is_matching_version(&self, version: &Version) -> bool {
160        let last_position = match self.version_height_position() {
161            Some(position) if position <= VersionPosition::Revision => position as usize,
162            _ => 4,
163        };
164        let positions = [
165            VersionPosition::Major,
166            VersionPosition::Minor,
167            VersionPosition::Build,
168            VersionPosition::Revision,
169        ];
170
171        positions[..last_position].iter().all(|&position| {
172            self.read_version_position(position).ok()
173                == Self::read_position(*version, position).ok()
174        })
175    }
176
177    /// Checks whether a numeric version belongs to the set represented by this
178    /// semantic version specification.
179    pub fn contains(&self, version: &Version) -> bool {
180        self.version.major == version.major
181            && self.version.minor == version.minor
182            && self
183                .version
184                .build
185                .is_none_or(|build| version.build == Some(build))
186            && self
187                .version
188                .revision
189                .is_none_or(|revision| version.revision == Some(revision))
190    }
191
192    /// Gets a new semantic version with the specified numeric component
193    /// incremented.
194    ///
195    /// Incrementing build is invalid when the build component is unspecified.
196    /// Components after the incremented component are reset to zero while the
197    /// original component count, prerelease, and build metadata are preserved.
198    pub fn increment(&self, increment: ReleaseVersionIncrement) -> Result<Self> {
199        if increment == ReleaseVersionIncrement::Build && self.version.build.is_none() {
200            return Err(Error::InvalidOperation(format!(
201                "Cannot apply build increment to version '{self}'."
202            )));
203        }
204
205        let mut major = self.version.major;
206        let mut minor = self.version.minor;
207        let mut build = self.version.build.unwrap_or(0);
208        match increment {
209            ReleaseVersionIncrement::Major => {
210                major = major.checked_add(1).ok_or_else(|| {
211                    Error::InvalidOperation("The major version cannot be incremented.".to_owned())
212                })?;
213                minor = 0;
214                build = 0;
215            }
216            ReleaseVersionIncrement::Minor => {
217                minor = minor.checked_add(1).ok_or_else(|| {
218                    Error::InvalidOperation("The minor version cannot be incremented.".to_owned())
219                })?;
220                build = 0;
221            }
222            ReleaseVersionIncrement::Build => {
223                build = build.checked_add(1).ok_or_else(|| {
224                    Error::InvalidOperation("The build version cannot be incremented.".to_owned())
225                })?;
226            }
227        }
228
229        let version = if self.version.build.is_none() {
230            Version::new(major, minor)
231        } else if self.version.revision.unwrap_or(0) > 0 {
232            Version::new_with_revision(major, minor, build, 0)
233        } else {
234            Version::new_with_build(major, minor, build)
235        };
236        Self::new(
237            version,
238            self.prerelease.clone(),
239            self.build_metadata.clone(),
240        )
241    }
242
243    /// Sets the first prerelease identifier. The leading hyphen may be
244    /// specified or omitted. An empty value removes the first identifier.
245    pub fn set_first_prerelease_tag(&self, new_first_tag: &str) -> Result<Self> {
246        let suffix = self
247            .prerelease
248            .find('.')
249            .map_or("", |index| &self.prerelease[index..]);
250        let mut prerelease = if self.prerelease.is_empty() {
251            new_first_tag.to_owned()
252        } else {
253            format!("{new_first_tag}{suffix}")
254        };
255        if !prerelease.is_empty() && !prerelease.starts_with('-') {
256            prerelease.insert(0, '-');
257        }
258        Self::new(self.version, prerelease, self.build_metadata.clone())
259    }
260
261    /// Returns a copy without any prerelease identifiers.
262    pub fn without_prerelease_tags(&self) -> Self {
263        Self {
264            version: self.version,
265            prerelease: String::new(),
266            build_metadata: self.build_metadata.clone(),
267        }
268    }
269
270    /// Converts a SemVer 2 prerelease such as `-beta.5` to a SemVer 1
271    /// compatible value such as `-beta-0005`.
272    ///
273    /// Numeric identifiers are left-padded to at least `padding_size` digits,
274    /// and dots are replaced by hyphens.
275    pub fn make_prerelease_semver1_compliant(prerelease: &str, padding_size: usize) -> String {
276        if prerelease.is_empty() {
277            return String::new();
278        }
279
280        let body = prerelease.strip_prefix('-').unwrap_or(prerelease);
281        let identifiers = body.split('.').map(|identifier| {
282            if identifier.bytes().all(|byte| byte.is_ascii_digit()) {
283                let normalized = identifier.trim_start_matches('0');
284                let normalized = if normalized.is_empty() {
285                    "0"
286                } else {
287                    normalized
288                };
289                format!("{normalized:0>padding_size$}")
290            } else {
291                identifier.to_owned()
292            }
293        });
294        format!("-{}", identifiers.collect::<Vec<_>>().join("-"))
295    }
296
297    fn read_position(version: Version, position: VersionPosition) -> Result<i64> {
298        match position {
299            VersionPosition::Major => Ok(version.major as i64),
300            VersionPosition::Minor => Ok(version.minor as i64),
301            VersionPosition::Build => Ok(version.build_or_unspecified()),
302            VersionPosition::Revision => Ok(version.revision_or_unspecified()),
303            _ => Err(Error::InvalidOperation(
304                "The position must be one of the four numeric parts.".to_owned(),
305            )),
306        }
307    }
308}
309
310impl fmt::Display for SemanticVersion {
311    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
312        write!(
313            formatter,
314            "{}{}{}",
315            self.version, self.prerelease, self.build_metadata
316        )
317    }
318}
319
320impl FromStr for SemanticVersion {
321    type Err = Error;
322
323    fn from_str(value: &str) -> Result<Self> {
324        let captures = SEMANTIC_VERSION_PATTERN.captures(value).ok_or_else(|| {
325            Error::InvalidFormat(format!(
326                "Unrecognized or unsupported semantic version '{value}'."
327            ))
328        })?;
329        let parse_number = |name: &str| {
330            captures[name]
331                .parse::<i32>()
332                .map(|value| value as u32)
333                .map_err(|_| {
334                    Error::InvalidFormat(format!(
335                        "'{value}' contains an invalid version component."
336                    ))
337                })
338        };
339        let major = parse_number("major")?;
340        let minor = parse_number("minor")?;
341        let version = match (captures.name("patch"), captures.name("revision")) {
342            (None, None) => Version::new(major, minor),
343            (Some(patch), None) => Version::new_with_build(
344                major,
345                minor,
346                patch
347                    .as_str()
348                    .parse::<i32>()
349                    .map(|value| value as u32)
350                    .map_err(|_| {
351                        Error::InvalidFormat(format!(
352                            "'{value}' contains an invalid version component."
353                        ))
354                    })?,
355            ),
356            (Some(patch), Some(revision)) => Version::new_with_revision(
357                major,
358                minor,
359                patch
360                    .as_str()
361                    .parse::<i32>()
362                    .map(|value| value as u32)
363                    .map_err(|_| {
364                        Error::InvalidFormat(format!(
365                            "'{value}' contains an invalid version component."
366                        ))
367                    })?,
368                revision
369                    .as_str()
370                    .parse::<i32>()
371                    .map(|value| value as u32)
372                    .map_err(|_| {
373                        Error::InvalidFormat(format!(
374                            "'{value}' contains an invalid version component."
375                        ))
376                    })?,
377            ),
378            (None, Some(_)) => unreachable!("the regex requires patch before revision"),
379        };
380        Self::new(
381            version,
382            captures
383                .name("prerelease")
384                .map_or("", |capture| capture.as_str()),
385            captures
386                .name("build_metadata")
387                .map_or("", |capture| capture.as_str()),
388        )
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395
396    #[test]
397    fn parses_full_supported_grammar() {
398        let parsed: SemanticVersion = "v1.2.3.4-pre.5.{height}+build-metadata.id1"
399            .parse()
400            .unwrap();
401        assert_eq!(Version::new_with_revision(1, 2, 3, 4), parsed.version);
402        assert_eq!("-pre.5.{height}", parsed.prerelease);
403        assert_eq!("+build-metadata.id1", parsed.build_metadata);
404        assert_eq!(
405            Some(VersionPosition::Prerelease),
406            parsed.version_height_position()
407        );
408        assert_eq!(
409            "1.2.3.4-pre.5.{height}+build-metadata.id1",
410            parsed.to_string()
411        );
412    }
413
414    #[test]
415    fn rejects_bad_grammar_and_leading_zeroes() {
416        for value in [
417            "", "1", "01.2", "1.02", "1.2.03", "1.2-$", "1.2-", "1.2-a.", "1.2+$", "1.2+", "1.2+a.",
418        ] {
419            assert!(SemanticVersion::try_parse(value).is_none(), "{value}");
420        }
421    }
422
423    #[test]
424    fn constructors_validate_suffixes() {
425        assert!(SemanticVersion::new(Version::new(1, 2), "-pre", "+build").is_ok());
426        assert!(SemanticVersion::new(Version::new(1, 2), "pre", "").is_err());
427        assert!(SemanticVersion::new(Version::new(1, 2), "", "build").is_err());
428    }
429
430    #[test]
431    fn computes_height_and_commit_positions() {
432        let two: SemanticVersion = "1.2".parse().unwrap();
433        let three: SemanticVersion = "1.2.3".parse().unwrap();
434        let four: SemanticVersion = "1.2.3.4".parse().unwrap();
435        assert_eq!(Some(VersionPosition::Build), two.version_height_position());
436        assert_eq!(
437            Some(VersionPosition::Revision),
438            two.git_commit_id_position()
439        );
440        assert_eq!(
441            Some(VersionPosition::Revision),
442            three.version_height_position()
443        );
444        assert_eq!(None, four.version_height_position());
445    }
446
447    #[test]
448    fn checks_reset_matching_and_containment() {
449        let spec: SemanticVersion = "1.2".parse().unwrap();
450        assert!(spec.is_matching_version(&Version::new_with_revision(1, 2, 15, 42)));
451        assert!(!spec.is_matching_version(&Version::new_with_build(2, 2, 15)));
452        assert!(spec.contains(&Version::new_with_revision(1, 2, 15, 42)));
453
454        let first: SemanticVersion = "1.2.3".parse().unwrap();
455        let second: SemanticVersion = "1.2.4".parse().unwrap();
456        assert!(
457            SemanticVersion::will_version_change_reset_version_height(
458                &first,
459                &second,
460                VersionPosition::Revision
461            )
462            .unwrap()
463        );
464        assert!(
465            SemanticVersion::will_version_change_reset_version_height(
466                &first,
467                &second,
468                VersionPosition::Build
469            )
470            .unwrap()
471        );
472    }
473
474    #[test]
475    fn edits_and_normalizes_prerelease() {
476        let version: SemanticVersion = "1.2-alpha.preview+metadata".parse().unwrap();
477        assert_eq!(
478            "1.2-beta.preview+metadata",
479            version
480                .set_first_prerelease_tag("beta")
481                .unwrap()
482                .to_string()
483        );
484        assert_eq!(
485            "1.2+metadata",
486            version.without_prerelease_tags().to_string()
487        );
488        assert_eq!(
489            "-beta-0005-0001-foo5",
490            SemanticVersion::make_prerelease_semver1_compliant("-beta.5.00001.foo5", 4)
491        );
492    }
493
494    #[test]
495    fn increments_and_preserves_suffixes_and_precision() {
496        let two: SemanticVersion = "1.2-tag+metadata".parse().unwrap();
497        assert_eq!(
498            "2.0-tag+metadata",
499            two.increment(ReleaseVersionIncrement::Major)
500                .unwrap()
501                .to_string()
502        );
503        assert_eq!(
504            "1.3-tag+metadata",
505            two.increment(ReleaseVersionIncrement::Minor)
506                .unwrap()
507                .to_string()
508        );
509        assert!(two.increment(ReleaseVersionIncrement::Build).is_err());
510
511        let four: SemanticVersion = "1.2.3.4-tag".parse().unwrap();
512        assert_eq!(
513            "1.2.4.0-tag",
514            four.increment(ReleaseVersionIncrement::Build)
515                .unwrap()
516                .to_string()
517        );
518    }
519
520    #[test]
521    fn managed_increment_and_first_tag_compatibility_vectors() {
522        for (input, increment, expected) in [
523            ("1.0", ReleaseVersionIncrement::Minor, "1.1"),
524            ("1.1", ReleaseVersionIncrement::Major, "2.0"),
525            ("1.2.3", ReleaseVersionIncrement::Minor, "1.3.0"),
526            ("1.2.3", ReleaseVersionIncrement::Major, "2.0.0"),
527            ("1.2.3", ReleaseVersionIncrement::Build, "1.2.4"),
528            ("1.2.3.4", ReleaseVersionIncrement::Minor, "1.3.0.0"),
529            ("1.2.3.4", ReleaseVersionIncrement::Major, "2.0.0.0"),
530            ("1.2.3.4", ReleaseVersionIncrement::Build, "1.2.4.0"),
531            (
532                "1.2.3-tag+metadata",
533                ReleaseVersionIncrement::Build,
534                "1.2.4-tag+metadata",
535            ),
536        ] {
537            let actual = input
538                .parse::<SemanticVersion>()
539                .unwrap()
540                .increment(increment)
541                .unwrap();
542            assert_eq!(expected, actual.to_string(), "{input}");
543        }
544
545        for (input, tag, expected) in [
546            ("1.2", "pre", "1.2-pre"),
547            ("1.2+build", "-pre", "1.2-pre+build"),
548            ("1.2-alpha", "beta", "1.2-beta"),
549            ("1.2-alpha.preview", "-beta", "1.2-beta.preview"),
550            (
551                "1.2-alpha.preview+metadata",
552                "beta",
553                "1.2-beta.preview+metadata",
554            ),
555            ("1.2-alpha.{height}", "beta", "1.2-beta.{height}"),
556            ("1.2-pre", "", "1.2"),
557        ] {
558            let actual = input
559                .parse::<SemanticVersion>()
560                .unwrap()
561                .set_first_prerelease_tag(tag)
562                .unwrap();
563            assert_eq!(expected, actual.to_string(), "{input}");
564        }
565    }
566}