semantic_versions/lib.rs
1//! # semantic-versions
2//!
3//! The Rust reference implementation of [Semantic Versions](https://semver.xyz):
4//! parse, validate, compare and range-match versions.
5//!
6//! It follows the specification at <https://semver.xyz/spec/> and its published
7//! [BNF grammars](https://semver.xyz/grammar/), and passes the same shared
8//! conformance suite as the JavaScript reference parser (`semantic-versions` on
9//! npm). Where it differs from Semantic Versioning 2.0.0 and from `node-semver`:
10//!
11//! - **Builds participate in precedence**: `1.0.0 < 1.0.0+build.1`.
12//! - **Pre-release channels**: `^1.0.0-rc` admits `1.0.0-rc.1`, never
13//! `1.0.0-beta`; `X.Y.Z-*` and `*-*` opt in explicitly.
14//! - **Build channels**: `^1.0.0+win` admits `1.4.2+win.x64` only.
15//! - **Contexts**: `npm:react@18.2.0` and `npm:react@^18` scope a version or
16//! range to an identity.
17//!
18//! ```
19//! use semantic_versions::{satisfies, valid_range, Version, Range};
20//!
21//! let v: Version = "1.2.3-beta.4+build.7".parse().unwrap();
22//! assert_eq!(v.major, 1);
23//! assert!(Version::parse("1.0.0").unwrap() < Version::parse("1.0.0+build.1").unwrap());
24//!
25//! assert!(satisfies("1.4.0", "^1.2.3"));
26//! assert!(satisfies("1.0.0-rc.1", "^1.0.0-rc"));
27//! assert!(!satisfies("1.0.0-beta", "^1.0.0-rc"));
28//! assert!(satisfies("1.4.2+win.x64", "^1.0.0+win"));
29//! assert_eq!(valid_range("~>1.2").as_deref(), Some(">=1.2.0 <1.3.0-0"));
30//!
31//! let r = Range::parse("npm:react@^18").unwrap();
32//! assert!(r.test(&"npm:react@18.2.0".parse().unwrap()));
33//! assert!(!r.test(&"18.2.0".parse().unwrap()));
34//! ```
35
36#![forbid(unsafe_code)]
37#![warn(missing_docs)]
38
39mod error;
40mod identifier;
41mod range;
42mod version;
43
44pub use error::Error;
45pub use identifier::{Identifier, Identifiers};
46pub use range::{Comparator, Op, Range};
47pub use version::{split_reference, Version};
48
49// Compile and run the README's example as a doctest.
50#[cfg(doctest)]
51#[doc = include_str!("../README.md")]
52struct ReadmeDoctests;
53
54use std::cmp::Ordering;
55
56/// Maximum length of a version or range string, matching the JavaScript reference.
57pub const MAX_LENGTH: usize = 256;
58/// Largest numeric identifier accepted (JavaScript's `Number.MAX_SAFE_INTEGER`),
59/// so both reference implementations accept exactly the same inputs.
60pub const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
61
62/// Parse a version (optionally context-qualified, e.g. `npm:react@1.2.3`).
63pub fn parse(version: &str) -> Result<Version, Error> {
64 Version::parse(version)
65}
66
67/// The normalized version string, or `None` if `version` is not a valid version.
68/// The context, if any, is not part of the normalized string.
69pub fn valid(version: &str) -> Option<String> {
70 Version::parse(version).ok().map(|v| v.to_string())
71}
72
73/// The desugared range (primitive comparators), or `None` if invalid. An
74/// unbounded range is `"*"`.
75pub fn valid_range(range: &str) -> Option<String> {
76 Range::parse(range).ok().map(|r| {
77 let s = r.to_string();
78 if s.is_empty() {
79 "*".to_string()
80 } else {
81 s
82 }
83 })
84}
85
86/// Compare two versions by precedence. Errors if either is invalid.
87pub fn compare(a: &str, b: &str) -> Result<Ordering, Error> {
88 Ok(Version::parse(a)?.cmp(&Version::parse(b)?))
89}
90
91/// True if `version` satisfies `range`. Invalid input never satisfies.
92pub fn satisfies(version: &str, range: &str) -> bool {
93 if version == range {
94 // Mirrors the JavaScript reference: an identical string trivially matches.
95 return Version::parse(version).is_ok();
96 }
97 let Ok(range) = Range::parse(range) else {
98 return false;
99 };
100 let Ok(version) = Version::parse(version) else {
101 return false;
102 };
103 range.test(&version)
104}
105
106/// The highest version in `versions` that satisfies `range`.
107pub fn max_satisfying<'a, I>(versions: I, range: &str) -> Option<&'a str>
108where
109 I: IntoIterator<Item = &'a str>,
110{
111 let range = Range::parse(range).ok()?;
112 let mut best: Option<(&'a str, Version)> = None;
113 for s in versions {
114 let Ok(v) = Version::parse(s) else { continue };
115 if !range.test(&v) {
116 continue;
117 }
118 match &best {
119 Some((_, b)) if *b >= v => {}
120 _ => best = Some((s, v)),
121 }
122 }
123 best.map(|(s, _)| s)
124}
125
126/// The lowest version in `versions` that satisfies `range`.
127pub fn min_satisfying<'a, I>(versions: I, range: &str) -> Option<&'a str>
128where
129 I: IntoIterator<Item = &'a str>,
130{
131 let range = Range::parse(range).ok()?;
132 let mut best: Option<(&'a str, Version)> = None;
133 for s in versions {
134 let Ok(v) = Version::parse(s) else { continue };
135 if !range.test(&v) {
136 continue;
137 }
138 match &best {
139 Some((_, b)) if *b <= v => {}
140 _ => best = Some((s, v)),
141 }
142 }
143 best.map(|(s, _)| s)
144}
145
146/// Sort versions ascending by precedence.
147pub fn sort(versions: &mut [Version]) {
148 versions.sort();
149}
150
151/// Sort versions descending by precedence.
152pub fn rsort(versions: &mut [Version]) {
153 versions.sort_by(|a, b| b.cmp(a));
154}