| // Copyright 2026 The Bazel Authors. All rights reserved. | |
| // | |
| // Licensed under the Apache License, Version 2.0 (the "License"); | |
| // you may not use this file except in compliance with the License. | |
| // You may obtain a copy of the License at | |
| // | |
| // http://www.apache.org/licenses/LICENSE-2.0 | |
| // | |
| // Unless required by applicable law or agreed to in writing, software | |
| // distributed under the License is distributed on an "AS IS" BASIS, | |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| // See the License for the specific language governing permissions and | |
| // limitations under the License. | |
| //! Semantic Version 2.0.0 parsing and precedence comparison. | |
| use std::cmp::Ordering; | |
| /// A parsed semantic version per <https://semver.org/>. | |
| /// | |
| /// Equality and ordering follow SemVer 2.0.0 precedence rules, so build metadata | |
| /// is validated during parsing and ignored during comparison. | |
| #[derive(Clone, Debug)] | |
| pub struct SemVer { | |
| major: u32, | |
| minor: u32, | |
| patch: u32, | |
| prerelease: String, | |
| } | |
| impl SemVer { | |
| /// Parses `version` as a strict SemVer 2.0.0 string, returning `None` if | |
| /// invalid. | |
| #[must_use] | |
| pub fn parse(version: &str) -> Option<Self> { | |
| // Strip build metadata before prerelease: build metadata may contain | |
| // '-' (e.g. `1.0.0+build-1`), while prerelease cannot contain '+'. | |
| // Build metadata is validated here and discarded because SemVer 2.0.0 | |
| // ignores it for precedence and no caller inspects it. | |
| let (without_build, build_metadata) = match version.split_once('+') { | |
| Some((prefix, build)) => (prefix, Some(build)), | |
| None => (version, None), | |
| }; | |
| if let Some(build) = build_metadata | |
| && !is_valid_build_metadata(build) | |
| { | |
| return None; | |
| } | |
| let (core, prerelease) = match without_build.split_once('-') { | |
| Some((prefix, pre)) => (prefix, Some(pre)), | |
| None => (without_build, None), | |
| }; | |
| if let Some(pre) = prerelease | |
| && !is_valid_prerelease(pre) | |
| { | |
| return None; | |
| } | |
| // Core version must be exactly three dot-separated numeric identifiers | |
| // (`MAJOR.MINOR.PATCH`). | |
| let mut parts = core.split('.'); | |
| let major = parse_numeric_identifier(parts.next()?)?; | |
| let minor = parse_numeric_identifier(parts.next()?)?; | |
| let patch = parse_numeric_identifier(parts.next()?)?; | |
| if parts.next().is_some() { | |
| return None; | |
| } | |
| Some(Self { major, minor, patch, prerelease: prerelease.unwrap_or_default().to_owned() }) | |
| } | |
| /// Returns a new `SemVer` with the next major version (e.g. `8.3.4` -> | |
| /// `9.0.0`), or `None` if the major component is `u32::MAX`. | |
| #[must_use] | |
| pub fn next_major_version(&self) -> Option<Self> { | |
| Some(Self { | |
| major: self.major.checked_add(1)?, | |
| minor: 0, | |
| patch: 0, | |
| prerelease: String::new(), | |
| }) | |
| } | |
| /// Returns a new `SemVer` with the next minor version (e.g. `8.3.4` -> | |
| /// `8.4.0`), or `None` if the minor component is `u32::MAX`. | |
| #[must_use] | |
| pub fn next_minor_version(&self) -> Option<Self> { | |
| Some(Self { | |
| major: self.major, | |
| minor: self.minor.checked_add(1)?, | |
| patch: 0, | |
| prerelease: String::new(), | |
| }) | |
| } | |
| } | |
| impl PartialEq for SemVer { | |
| fn eq(&self, other: &Self) -> bool { | |
| self.cmp(other) == Ordering::Equal | |
| } | |
| } | |
| impl Eq for SemVer {} | |
| impl PartialOrd for SemVer { | |
| fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | |
| Some(self.cmp(other)) | |
| } | |
| } | |
| impl Ord for SemVer { | |
| fn cmp(&self, other: &Self) -> Ordering { | |
| self.major | |
| .cmp(&other.major) | |
| .then_with(|| self.minor.cmp(&other.minor)) | |
| .then_with(|| self.patch.cmp(&other.patch)) | |
| .then_with(|| compare_prerelease(&self.prerelease, &other.prerelease)) | |
| } | |
| } | |
| /// Parses a SemVer 2.0.0 numeric identifier (non-negative integer with no | |
| /// leading zeros, except `"0"` itself). | |
| fn parse_numeric_identifier(identifier: &str) -> Option<u32> { | |
| if identifier.is_empty() || !identifier.bytes().all(|b| b.is_ascii_digit()) { | |
| return None; | |
| } | |
| if identifier.len() > 1 && identifier.starts_with('0') { | |
| return None; | |
| } | |
| identifier.parse::<u32>().ok() | |
| } | |
| fn is_valid_identifier_byte(b: u8) -> bool { | |
| b.is_ascii_alphanumeric() || b == b'-' | |
| } | |
| /// Validates dot-separated pre-release identifiers per SemVer 2.0.0 rule 9. | |
| fn is_valid_prerelease(prerelease: &str) -> bool { | |
| prerelease.split('.').all(|identifier| { | |
| if identifier.is_empty() || !identifier.bytes().all(is_valid_identifier_byte) { | |
| return false; | |
| } | |
| // Leading zeros are forbidden only for numeric-only identifiers (e.g. | |
| // `01`); alphanumeric identifiers containing a letter or '-' (e.g. | |
| // `01a`, `0-alpha`) are valid. | |
| let all_digits = identifier.bytes().all(|b| b.is_ascii_digit()); | |
| !(all_digits && identifier.len() > 1 && identifier.starts_with('0')) | |
| }) | |
| } | |
| /// Validates dot-separated build metadata identifiers per SemVer 2.0.0 rule 10 | |
| /// (unlike pre-release, leading zeros are allowed). | |
| fn is_valid_build_metadata(build_metadata: &str) -> bool { | |
| build_metadata.split('.').all(|identifier| { | |
| !identifier.is_empty() && identifier.bytes().all(is_valid_identifier_byte) | |
| }) | |
| } | |
| /// Compares two validated pre-release strings per SemVer 2.0.0 rule 11. | |
| fn compare_prerelease(lhs: &str, rhs: &str) -> Ordering { | |
| if lhs == rhs { | |
| return Ordering::Equal; | |
| } | |
| // A normal version has higher precedence than a pre-release version. | |
| if lhs.is_empty() { | |
| return Ordering::Greater; | |
| } | |
| if rhs.is_empty() { | |
| return Ordering::Less; | |
| } | |
| let mut lhs_parts = lhs.split('.'); | |
| let mut rhs_parts = rhs.split('.'); | |
| loop { | |
| match (lhs_parts.next(), rhs_parts.next()) { | |
| (Some(part_lhs), Some(part_rhs)) => { | |
| if part_lhs == part_rhs { | |
| continue; | |
| } | |
| let lhs_is_numeric = part_lhs.bytes().all(|b| b.is_ascii_digit()); | |
| let rhs_is_numeric = part_rhs.bytes().all(|b| b.is_ascii_digit()); | |
| return match (lhs_is_numeric, rhs_is_numeric) { | |
| // Numeric identifiers always have lower precedence than | |
| // non-numeric identifiers. | |
| (true, false) => Ordering::Less, | |
| (false, true) => Ordering::Greater, | |
| // Valid numeric prerelease identifiers have no leading | |
| // zeros, so length then ASCII order is exact numeric order. | |
| (true, true) => { | |
| part_lhs.len().cmp(&part_rhs.len()).then_with(|| part_lhs.cmp(part_rhs)) | |
| } | |
| (false, false) => part_lhs.cmp(part_rhs), | |
| }; | |
| } | |
| // A larger set of pre-release fields has higher precedence. | |
| (None, Some(_)) => return Ordering::Less, | |
| (Some(_), None) => return Ordering::Greater, | |
| (None, None) => return Ordering::Equal, | |
| } | |
| } | |
| } |