Standardcore
Semantic Versioning
Also called SemVer.
Semantic Versioning is a set of rules for version numbers of the form MAJOR.MINOR.PATCH. The number that changes tells the user if a release breaks the public API, adds to it or only fixes bugs.
What it is
Semantic Versioning (SemVer) is a set of rules for version numbers. A version has three numbers, MAJOR.MINOR.PATCH. The specification says what each number means.1
- Increase MAJOR when you make incompatible API changes.
- Increase MINOR when you add functionality that is backward compatible.
- Increase PATCH when you make bug fixes that are backward compatible.
The specification starts from a problem that it calls "dependency hell". A system with many dependencies has two risks. If the dependency specifications are too tight, you get version lock: you cannot upgrade one package without a release of each package that depends on it. If they are too loose, you get version promiscuity: you assume that more future versions are compatible than is reasonable.1 SemVer gives the version number a meaning, so a tool can choose a range of versions that are safe.
The rules apply to a public API. Item 1 of the specification says that software that uses SemVer MUST declare a public API, in the code or in documentation.1 The version number describes changes to that API and nothing else. A change to private code does not need a major release. A change to documented behaviour can need one, even if no function signature changes. The Go modules reference asks for a major version after an incompatible change to the "public interface or documented functionality".9
The specification is the document "Semantic Versioning 2.0.0" on the site semver.org. It uses the key words of RFC 2119, such as MUST, SHOULD and MAY. It has eleven numbered items, a grammar in Backus-Naur form, two regular expressions and a FAQ.1 The text is under the licence Creative Commons CC BY 3.0. The About section says that Tom Preston-Werner, the inventor of Gravatar and a cofounder of GitHub, wrote the original text.1
SemVer is a convention, not a law of the package managers. npm, Cargo, Composer, NuGet and the Go module system use SemVer version numbers. Each of them adds its own range syntax and its own rules for releases before 1.0.0 and for pre-releases. The section Versions compares them.
History
Tom Preston-Werner made the first commit of the repository semver.org on 14 December 2009. The file index.md of that commit already has the rules for the three numbers and a rule that a tag has the form "vX.Y.Z".3
Version 1.0.0 of the specification had integers with no rule about leading zeros. A pre-release version was "an arbitrary string" after a dash, ordered by an ASCII sort. Its example is 1.0.0-alpha1 < 1.0.0-beta1 < 1.0.0-beta2 < 1.0.0-rc1 < 1.0.0. Version 1.0.0 had no build metadata. It also had a second part, the Tagging Specification (SemVerTag). That part said a tag in version control MUST be "vX.Y.Z", for example v3.1.0.2
On 8 June 2011, the specification moved to its own repository, semver/semver, with the commit message "Extract spec from https://github.com/mojombo/semver.org."4 The repository has the tags v1.0.0-beta, v1.0.0-rc.1, v1.0.0 and v2.0.0. The tag v2.0.0 points to the merge commit of pull request 120, "Mark 2.0.0 as RTM", of 18 June 2013.5
Version 2.0.0 made five main changes to version 1.0.0.12
- Numbers MUST NOT have leading zeros.
- A pre-release is a list of identifiers separated by dots, not one string.
- Numeric identifiers compare as numbers, so beta.11 comes after beta.2.
- Build metadata after a plus sign is part of the syntax and has no effect on precedence.
- The Tagging Specification is gone. The FAQ says that "v1.2.3" is not a semantic version. It is a tag name, and the semantic version is "1.2.3".
Syntax or structure
A version has a version core, an optional pre-release and optional build metadata. The order is fixed.
1.4.2-beta.11+exp.sha.5114f85
| | | | |
| | | | build metadata: exp, sha, 5114f85
| | | pre-release: beta, 11
| | patch: 2
| minor: 4
major: 1
The rules for each part come from items 2, 9 and 10.1
- Version core. The form is X.Y.Z. Each of X, Y and Z is a non-negative integer with no leading zeros. So 0 is valid, but 00 and 01 are not. Each number MUST increase numerically: 1.9.0 is followed by 1.10.0.
- Pre-release. A hyphen follows the patch number, then one or more identifiers separated by dots. An identifier has only ASCII letters, digits and hyphens,
[0-9A-Za-z-]. It MUST NOT be empty. A numeric identifier MUST NOT have leading zeros. The examples in the specification are 1.0.0-alpha, 1.0.0-alpha.1, 1.0.0-0.3.7, 1.0.0-x.7.z.92 and 1.0.0-x-y-z.--. - Build metadata. A plus sign follows the patch number or the pre-release, then one or more identifiers separated by dots. The character set is the same, and an identifier MUST NOT be empty. A build identifier can have leading zeros, as in 1.0.0-alpha+001.
The grammar defines an alphanumeric identifier as a sequence that has at least one letter or hyphen. A numeric identifier is "0", or a positive digit followed by zero or more digits.1 The top rules of the grammar are below.
<valid semver> ::= <version core>
| <version core> "-" <pre-release>
| <version core> "+" <build>
| <version core> "-" <pre-release> "+" <build>
<version core> ::= <major> "." <minor> "." <patch>
<pre-release identifier> ::= <alphanumeric identifier>
| <numeric identifier>
<build identifier> ::= <alphanumeric identifier>
| <digits>
<numeric identifier> ::= "0"
| <positive digit>
| <positive digit> <digits>
There is no prefix. The text "v1.2.3" is not a semantic version.1 There is no size limit. The FAQ says that a version string of 255 characters is "probably overkill", and that a system can set its own limit.1
The official regular expressions
The FAQ gives two regular expressions. The first has named groups. The FAQ says that it works in PCRE, Python and Go. The second has numbered groups, and the FAQ adds ECMAScript to the list.1 The program below uses the first one. It runs with the flag re.ASCII. Without this flag, \d in a Python str pattern matches any Unicode decimal digit, and the specification allows only ASCII.17
import re
SEMVER = re.compile(
r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)"
r"(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?"
r"(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$",
re.ASCII,
)
samples = [
"1.2.3",
"1.0.0-alpha.1+exp.sha.5114f85",
"1.0.0-x-y-z.--",
"1.0.0+001",
"v1.2.3",
"1.2",
"01.2.3",
"1.0.0-01",
"1.0.0-alpha..1",
"1.0.0+",
]
for text in samples:
match = SEMVER.match(text)
if match:
parts = {name: value for name, value in match.groupdict().items() if value is not None}
print(f"{text:30} {parts}")
else:
print(f"{text:30} invalid")
1.2.3 {'major': '1', 'minor': '2', 'patch': '3'}
1.0.0-alpha.1+exp.sha.5114f85 {'major': '1', 'minor': '0', 'patch': '0', 'prerelease': 'alpha.1', 'buildmetadata': 'exp.sha.5114f85'}
1.0.0-x-y-z.-- {'major': '1', 'minor': '0', 'patch': '0', 'prerelease': 'x-y-z.--'}
1.0.0+001 {'major': '1', 'minor': '0', 'patch': '0', 'buildmetadata': '001'}
v1.2.3 invalid
1.2 invalid
01.2.3 invalid
1.0.0-01 invalid
1.0.0-alpha..1 invalid
1.0.0+ invalid
A regular expression can check the syntax and split the parts. It cannot compute precedence. For that, the program must compare the parts with the rules of item 11.
Examples
Precedence
Item 11 defines precedence, the order of two versions.1
- Split the version into major, minor, patch and pre-release identifiers, in that order. Build metadata has no effect (item 11.1).
- Compare major, minor and patch as numbers, from left to right. The first difference decides (item 11.2). Example: 1.0.0 < 2.0.0 < 2.1.0 < 2.1.1.
- When the three numbers are equal, a pre-release has lower precedence than the normal version (item 11.3). Example: 1.0.0-alpha < 1.0.0.
- When both are pre-releases, compare the identifiers from left to right until one differs (item 11.4).
- Identifiers of digits only compare as numbers (11.4.1).
- Identifiers with letters or hyphens compare in ASCII order (11.4.2).
- A numeric identifier has lower precedence than an alphanumeric one (11.4.3).
- If all earlier identifiers are equal, the longer list has higher precedence (11.4.4).
The specification gives this example of the full order:1
1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0
Each step of the example tests one rule. alpha < alpha.1 is rule 11.4.4. alpha.1 < alpha.beta is rule 11.4.3. beta.2 < beta.11 is rule 11.4.1. rc.1 < 1.0.0 is rule 11.3.
The program below turns each version into a Python tuple, so that the built-in tuple order gives SemVer precedence. A normal version gets the flag 1 and a pre-release gets the flag 0, so the pre-release sorts first. Each pre-release identifier becomes (0, number) or (1, text). The first element puts numbers before text. Two identifiers of the same kind compare by the second element. A shorter tuple sorts before a longer tuple with the same start, which is rule 11.4.4. The key ignores the build metadata.
import random
import re
SEMVER = re.compile(
r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)"
r"(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?"
r"(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$",
re.ASCII,
)
def precedence_key(text):
match = SEMVER.match(text)
if match is None:
raise ValueError(f"not a semantic version: {text!r}")
core = (int(match["major"]), int(match["minor"]), int(match["patch"]))
if match["prerelease"] is None:
return (*core, 1, ())
identifiers = tuple(
(0, int(part)) if part.isdigit() else (1, part)
for part in match["prerelease"].split(".")
)
return (*core, 0, identifiers)
ordered = [
"1.0.0-alpha",
"1.0.0-alpha.1",
"1.0.0-alpha.beta",
"1.0.0-beta",
"1.0.0-beta.2",
"1.0.0-beta.11",
"1.0.0-rc.1",
"1.0.0",
]
shuffled = random.Random(7).sample(ordered, len(ordered))
by_precedence = sorted(shuffled, key=precedence_key)
print("precedence:", " < ".join(by_precedence))
print("same as the specification:", by_precedence == ordered)
print("string sort:", " < ".join(sorted(shuffled)))
print("string sort of cores:", sorted(["1.9.0", "1.10.0", "1.2.0"]))
print("key sort of cores:", sorted(["1.9.0", "1.10.0", "1.2.0"], key=precedence_key))
left, right = "1.0.0+build.1", "1.0.0+build.2"
print(f"{left} and {right}: same precedence {precedence_key(left) == precedence_key(right)}, same text {left == right}")
precedence: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0
same as the specification: True
string sort: 1.0.0 < 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.11 < 1.0.0-beta.2 < 1.0.0-rc.1
string sort of cores: ['1.10.0', '1.2.0', '1.9.0']
key sort of cores: ['1.2.0', '1.9.0', '1.10.0']
1.0.0+build.1 and 1.0.0+build.2: same precedence True, same text False
A plain string sort puts 1.0.0 first, because it is a prefix of the other strings. It also puts beta.11 before beta.2 and 1.10.0 before 1.9.0. The two versions with different build metadata have the same precedence but are different strings.
The examples for other languages show the same rules with their standard libraries or their SemVer libraries. The Rust and Java examples also check version ranges with the rules of Cargo and npm.
import re
CORE = r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$"
text = "1٠.2.3"
print(text, [f"U+{ord(character):04X}" for character in text])
print("str pattern:", bool(re.match(CORE, text)))
print("re.ASCII:", bool(re.match(CORE, text, re.ASCII)))
print("int() of the major part:", int(text.split(".")[0]))
1٠.2.3 ['U+0031', 'U+0660', 'U+002E', 'U+0032', 'U+002E', 'U+0033']
str pattern: True
re.ASCII: False
int() of the major part: 10
The dataclass below keeps the build metadata in a field with compare=False. So == and hash ignore it, and two builds of one version fall into one set entry. The order comes from a key with the rules of item 11.
import functools
import re
from dataclasses import dataclass, field
SEMVER = re.compile(
r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)"
r"(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?"
r"(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$",
re.ASCII,
)
@functools.total_ordering
@dataclass(frozen=True)
class Version:
major: int
minor: int
patch: int
prerelease: tuple[str, ...] = ()
build: tuple[str, ...] = field(default=(), compare=False)
@classmethod
def parse(cls, text):
match = SEMVER.match(text)
if match is None:
raise ValueError(f"not a semantic version: {text!r}")
prerelease = match["prerelease"]
build = match["buildmetadata"]
return cls(
int(match["major"]),
int(match["minor"]),
int(match["patch"]),
tuple(prerelease.split(".")) if prerelease else (),
tuple(build.split(".")) if build else (),
)
def _key(self):
identifiers = tuple((0, int(part)) if part.isdigit() else (1, part) for part in self.prerelease)
return (self.major, self.minor, self.patch, 0 if self.prerelease else 1, identifiers)
def __lt__(self, other):
return self._key() < other._key()
def __str__(self):
text = f"{self.major}.{self.minor}.{self.patch}"
if self.prerelease:
text += "-" + ".".join(self.prerelease)
if self.build:
text += "+" + ".".join(self.build)
return text
releases = [Version.parse(text) for text in ["2.0.0", "1.10.0", "1.9.0", "1.10.0-rc.1", "1.10.0+linux", "1.10.0+macos"]]
print([str(version) for version in sorted(releases)])
print(Version.parse("1.10.0+linux") == Version.parse("1.10.0+macos"))
print(sorted(str(version) for version in set(releases)))
print(max(releases))
['1.9.0', '1.10.0-rc.1', '1.10.0', '1.10.0+linux', '1.10.0+macos', '2.0.0']
True
['1.10.0', '1.10.0-rc.1', '1.9.0', '2.0.0']
2.0.0
The program below computes the npm bounds of a caret range for a full version. The upper bound moves the left-most non-zero number, and -0 makes it the lowest pre-release of that version. A candidate that is a pre-release matches only if the lower bound is a pre-release with the same major, minor and patch. This is the npm rule for pre-releases.
def split(text):
core, _, prerelease = text.partition("-")
return tuple(int(part) for part in core.split(".")), prerelease
def precedence_key(text):
core, prerelease = split(text)
if not prerelease:
return (*core, 1, ())
identifiers = tuple((0, int(part)) if part.isdigit() else (1, part) for part in prerelease.split("."))
return (*core, 0, identifiers)
def caret_upper(lower):
(major, minor, patch), _ = split(lower)
if major > 0:
return f"{major + 1}.0.0-0"
if minor > 0:
return f"0.{minor + 1}.0-0"
return f"0.0.{patch + 1}-0"
def caret_matches(lower, candidate):
lower_core, lower_pre = split(lower)
candidate_core, candidate_pre = split(candidate)
if candidate_pre and not (lower_pre and candidate_core == lower_core):
return False
return precedence_key(lower) <= precedence_key(candidate) < precedence_key(caret_upper(lower))
candidates = ["0.2.9", "0.3.0", "1.2.9", "1.9.0", "2.0.0-alpha", "2.0.0"]
for lower in ["1.2.3", "0.2.3", "0.0.3"]:
allowed = [candidate for candidate in candidates if caret_matches(lower, candidate)]
print(f"^{lower} := >={lower} <{caret_upper(lower)} -> {allowed}")
for candidate in ["1.2.3-beta.4", "1.2.3-beta.10", "1.2.3", "1.2.4-beta.2"]:
print(f"^1.2.3-beta.2 matches {candidate}: {caret_matches('1.2.3-beta.2', candidate)}")
^1.2.3 := >=1.2.3 <2.0.0-0 -> ['1.2.9', '1.9.0']
^0.2.3 := >=0.2.3 <0.3.0-0 -> ['0.2.9']
^0.0.3 := >=0.0.3 <0.0.4-0 -> []
^1.2.3-beta.2 matches 1.2.3-beta.4: True
^1.2.3-beta.2 matches 1.2.3-beta.10: True
^1.2.3-beta.2 matches 1.2.3: True
^1.2.3-beta.2 matches 1.2.4-beta.2: False
- Verdict: idiom. The Python standard library has no SemVer type. The official regex with the named groups works with
re, and a tuple key gives the order of item 11. - In a
strpattern,\dmatches any Unicode decimal digit, andint()accepts these digits too. The flagre.ASCIImakes\dmatch only[0-9]. - A
dataclassfield withcompare=Falseis left out of==andhash. This gives build metadata the SemVer meaning in sets and dictionaries. - The function
caret_matcheshandles only a full version after the caret. npm also accepts partial versions such as^1.2and^0.x, and the npm packagesemverimplements all of these forms.
#include <algorithm>
#include <compare>
#include <optional>
#include <print>
#include <ranges>
#include <regex>
#include <string>
#include <vector>
struct Version {
std::string major, minor, patch;
std::vector<std::string> pre;
std::string build;
std::string text;
};
const std::regex semver(
R"(^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*))"
R"((?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?)"
R"((?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$)");
std::optional<Version> parse(const std::string& text) {
std::smatch m;
if (!std::regex_match(text, m, semver)) return std::nullopt;
Version v{m[1], m[2], m[3], {}, m[5], text};
if (m[4].matched) {
for (auto part : std::views::split(m[4].str(), '.')) v.pre.emplace_back(part.begin(), part.end());
}
return v;
}
bool numeric(const std::string& s) {
return std::ranges::all_of(s, [](char c) { return c >= '0' && c <= '9'; });
}
// Decimal strings with no leading zeros: the longer one is larger.
std::strong_ordering compare_numeric(const std::string& a, const std::string& b) {
if (auto c = a.size() <=> b.size(); c != 0) return c;
return a <=> b;
}
std::strong_ordering compare_identifier(const std::string& a, const std::string& b) {
bool an = numeric(a), bn = numeric(b);
if (an && bn) return compare_numeric(a, b);
if (an != bn) return an ? std::strong_ordering::less : std::strong_ordering::greater;
return a <=> b;
}
std::strong_ordering precedence(const Version& a, const Version& b) {
if (auto c = compare_numeric(a.major, b.major); c != 0) return c;
if (auto c = compare_numeric(a.minor, b.minor); c != 0) return c;
if (auto c = compare_numeric(a.patch, b.patch); c != 0) return c;
if (a.pre.empty() && b.pre.empty()) return std::strong_ordering::equal;
if (a.pre.empty()) return std::strong_ordering::greater;
if (b.pre.empty()) return std::strong_ordering::less;
for (std::size_t i = 0; i < std::min(a.pre.size(), b.pre.size()); ++i) {
if (auto c = compare_identifier(a.pre[i], b.pre[i]); c != 0) return c;
}
return a.pre.size() <=> b.pre.size();
}
int main() {
std::vector<std::string> texts{"1.0.0", "1.0.0-rc.1", "1.0.0-beta.11", "1.0.0-beta.2", "1.0.0-beta",
"1.0.0-alpha.beta", "1.0.0-alpha.1", "1.0.0-alpha"};
std::vector<Version> versions;
for (const auto& text : texts) versions.push_back(*parse(text));
std::ranges::sort(versions, [](const Version& a, const Version& b) { return precedence(a, b) < 0; });
for (const auto& v : versions) std::print("{} ", v.text);
std::println("");
std::ranges::sort(texts);
std::print("string sort:");
for (const auto& text : texts) std::print(" {}", text);
std::println("");
auto a = *parse("1.4.2+build.7");
auto b = *parse("1.4.2+build.8");
std::println("same precedence: {}, same text: {}", precedence(a, b) == 0, a.text == b.text);
for (std::string text : {"v1.2.3", "1.2", "01.2.3", "1.0.0-alpha..1"}) {
std::println("{}: {}", text, parse(text) ? "valid" : "invalid");
}
}
1.0.0-alpha 1.0.0-alpha.1 1.0.0-alpha.beta 1.0.0-beta 1.0.0-beta.2 1.0.0-beta.11 1.0.0-rc.1 1.0.0
string sort: 1.0.0 1.0.0-alpha 1.0.0-alpha.1 1.0.0-alpha.beta 1.0.0-beta 1.0.0-beta.11 1.0.0-beta.2 1.0.0-rc.1
same precedence: true, same text: false
v1.2.3: invalid
1.2: invalid
01.2.3: invalid
1.0.0-alpha..1: invalid
- Verdict: idiom. The C++ standard library has no SemVer type.
std::regexwith the default ECMAScript grammar accepts the numbered regex of the specification, andstd::ranges::sorttakes a comparison. - The example keeps each number as a string and compares the length first, so it has no integer overflow.
- A plain sort of the strings puts 1.0.0 first and beta.11 before beta.2, as the second line of the output shows.
import java.util.List;
import org.semver4j.Semver;
public class Main {
public static void main(String[] args) {
List<Semver> versions = List.of("1.0.0", "1.0.0-rc.1", "1.0.0-beta.11", "1.0.0-beta.2", "1.0.0-alpha.beta", "1.0.0-alpha")
.stream()
.map(Semver::parse)
.sorted()
.toList();
System.out.println(versions);
Semver release = Semver.parse("1.4.2+build.7");
System.out.println(release.getMajor() + " " + release.getMinor() + " " + release.getPatch() + " " + release.getBuild());
System.out.println("isEqualTo: " + release.isEqualTo("1.4.2+build.8"));
System.out.println("isEquivalentTo: " + release.isEquivalentTo("1.4.2+build.8"));
for (String text : List.of("v1.2.3", "1.2", "01.2.3")) {
System.out.println(text + " valid: " + Semver.isValid(text) + ", parse: " + Semver.parse(text) + ", coerce: " + Semver.coerce(text));
}
String[] candidates = {"0.2.9", "0.3.0", "1.2.9", "1.3.0", "2.0.0-rc.1", "2.0.0"};
for (String range : List.of("^1.2.3", "^0.2.3", "~1.2.3", "1.x", "1.2.3", ">=1.2.0 <1.3.0 || >=2.0.0-rc.1")) {
StringBuilder line = new StringBuilder(range + " ->");
for (String candidate : candidates) {
if (Semver.parse(candidate).satisfies(range)) {
line.append(" ").append(candidate);
}
}
System.out.println(line);
}
}
}
[1.0.0-alpha, 1.0.0-alpha.beta, 1.0.0-beta.2, 1.0.0-beta.11, 1.0.0-rc.1, 1.0.0]
1 4 2 [build, 7]
isEqualTo: false
isEquivalentTo: true
v1.2.3 valid: true, parse: 1.2.3, coerce: 1.2.3
1.2 valid: false, parse: null, coerce: 1.2.0
01.2.3 valid: false, parse: null, coerce: 1.2.3
^1.2.3 -> 1.2.9 1.3.0
^0.2.3 -> 0.2.9
~1.2.3 -> 1.2.9
1.x -> 1.2.9 1.3.0
1.2.3 ->
>=1.2.0 <1.3.0 || >=2.0.0-rc.1 -> 1.2.9 2.0.0-rc.1 2.0.0
- Verdict: library. Java SE has no SemVer type. The example uses semver4j 6.0.0.
SemverimplementsComparablewith SemVer precedence, sosorted()gives the order of item 11.isEqualTocompares the build metadata too.isEquivalentToignores it.Semver.isValidaccepts "v1.2.3", although the specification says it is not a semantic version.Semver.parsereturnsnullfor text that is not valid.Semver.coerceturns loose text into a version, so it accepts input that the specification rejects.satisfiesreads npm-style ranges, with caret, tilde, X-ranges and||. A bare version such as1.2.3is an exact match, as in npm, so it matches none of the candidates.
using System;
var two = Version.Parse("1.2");
var three = Version.Parse("1.2.0");
Console.WriteLine($"{two}: Build={two.Build}, Revision={two.Revision}");
Console.WriteLine($"1.2 < 1.2.0: {two < three}, Equals: {two.Equals(three)}");
Console.WriteLine(Version.Parse("1.2.3.4"));
Console.WriteLine(Version.Parse("01.002.3"));
foreach (var text in new[] { "1.2.3-beta", "1.2.3+build.7" })
{
try
{
Version.Parse(text);
}
catch (FormatException error)
{
Console.WriteLine($"{text}: {error.GetType().Name}");
}
}
1.2: Build=-1, Revision=-1
1.2 < 1.2.0: True, Equals: False
1.2.3.4
1.2.3
1.2.3-beta: FormatException
1.2.3+build.7: FormatException
The record below implements SemVer precedence with IComparable. The parser uses [0-9] and not \d, because \d in .NET also matches digits outside ASCII.
using System;
using System.Linq;
using System.Numerics;
using System.Text.RegularExpressions;
var ordered = new[] { "1.0.0", "1.0.0-rc.1", "1.0.0-beta.11", "1.0.0-beta.2", "1.0.0-beta",
"1.0.0-alpha.beta", "1.0.0-alpha.1", "1.0.0-alpha" }
.Select(SemVersion.Parse)
.Order()
.Select(v => v.ToString());
Console.WriteLine(string.Join(" < ", ordered));
var a = SemVersion.Parse("1.4.2+build.7");
var b = SemVersion.Parse("1.4.2+build.8");
Console.WriteLine($"CompareTo: {a.CompareTo(b)}, builds: {a.Build} {b.Build}");
foreach (var text in new[] { "v1.2.3", "1.2", "01.2.3", "١.٢.٣" })
{
Console.WriteLine($"{text}: {SemVersion.TryParse(text, out _)}");
}
Console.WriteLine($"\\d matches ١: {Regex.IsMatch("١", @"^\d$")}");
sealed record SemVersion(BigInteger Major, BigInteger Minor, BigInteger Patch, string[] Pre, string Build)
: IComparable<SemVersion>
{
const string Num = "0|[1-9][0-9]*";
const string Pid = "0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*";
static readonly Regex Pattern = new(
$@"^({Num})\.({Num})\.({Num})(?:-((?:{Pid})(?:\.(?:{Pid}))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$");
public static bool TryParse(string text, out SemVersion? version)
{
var m = Pattern.Match(text);
version = m.Success
? new SemVersion(BigInteger.Parse(m.Groups[1].Value), BigInteger.Parse(m.Groups[2].Value),
BigInteger.Parse(m.Groups[3].Value),
m.Groups[4].Success ? m.Groups[4].Value.Split('.') : [], m.Groups[5].Value)
: null;
return m.Success;
}
public static SemVersion Parse(string text) =>
TryParse(text, out var version) ? version! : throw new FormatException(text);
static bool IsNumeric(string s) => s.All(char.IsAsciiDigit);
static int CompareIdentifier(string x, string y) => (IsNumeric(x), IsNumeric(y)) switch
{
(true, true) => BigInteger.Parse(x).CompareTo(BigInteger.Parse(y)),
(true, false) => -1,
(false, true) => 1,
_ => string.CompareOrdinal(x, y),
};
public int CompareTo(SemVersion? other)
{
if (other is null) return 1;
int c = Major.CompareTo(other.Major);
if (c == 0) c = Minor.CompareTo(other.Minor);
if (c == 0) c = Patch.CompareTo(other.Patch);
if (c != 0) return c;
if (Pre.Length == 0 && other.Pre.Length == 0) return 0;
if (Pre.Length == 0) return 1;
if (other.Pre.Length == 0) return -1;
for (int i = 0; i < Math.Min(Pre.Length, other.Pre.Length); i++)
{
c = CompareIdentifier(Pre[i], other.Pre[i]);
if (c != 0) return Math.Sign(c);
}
return Pre.Length.CompareTo(other.Pre.Length);
}
public override string ToString() =>
$"{Major}.{Minor}.{Patch}" + (Pre.Length > 0 ? "-" + string.Join('.', Pre) : "") + (Build != "" ? "+" + Build : "");
}
1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0
CompareTo: 0, builds: build.7 build.8
v1.2.3: False
1.2: False
01.2.3: False
١.٢.٣: False
\d matches ١: True
- Verdict: library. .NET has no SemVer type in the base class library.
System.Versionrepresents the version number of an assembly, an operating system or the runtime. It has up to four numbers, no pre-release and no build metadata. Version.Parse("1.2")givesBuildandRevisionthe value -1, so 1.2 sorts before 1.2.0, and the two are not equal.Version.Parsealso accepts leading zeros.- The NuGet package
NuGet.VersioninghasNuGetVersion.ParseandVersionComparer. NuGet adds a fourth number and compares pre-release labels without case, so it differs from SemVer 2.0.0 in a few places. - In PowerShell, the type accelerator
[semver]isSystem.Management.Automation.SemanticVersion. That type is part of the PowerShell SDK, not of .NET. - The record
SemVersioncompares by precedence inCompareTo. Its generatedEqualscompares the arrayPreby reference, so do not useEqualsor==on it for precedence.
const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
function parse(text) {
const match = SEMVER.exec(text);
if (match === null) {
throw new SyntaxError(`not a semantic version: ${text}`);
}
const [, major, minor, patch, prerelease, build] = match;
return {
core: [BigInt(major), BigInt(minor), BigInt(patch)],
prerelease: prerelease === undefined ? [] : prerelease.split("."),
build: build ?? "",
};
}
const isNumeric = (identifier) => /^[0-9]+$/.test(identifier);
function compareIdentifiers(a, b) {
if (isNumeric(a) && isNumeric(b)) {
const [x, y] = [BigInt(a), BigInt(b)];
return x < y ? -1 : x > y ? 1 : 0;
}
if (isNumeric(a)) return -1;
if (isNumeric(b)) return 1;
return a < b ? -1 : a > b ? 1 : 0;
}
function compare(left, right) {
const a = parse(left);
const b = parse(right);
for (let i = 0; i < 3; i++) {
if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
}
if (a.prerelease.length === 0 || b.prerelease.length === 0) {
return (a.prerelease.length === 0) - (b.prerelease.length === 0);
}
for (let i = 0; i < Math.min(a.prerelease.length, b.prerelease.length); i++) {
const result = compareIdentifiers(a.prerelease[i], b.prerelease[i]);
if (result !== 0) return result;
}
return Math.sign(a.prerelease.length - b.prerelease.length);
}
const versions = ["1.0.0", "1.0.0-rc.1", "1.0.0-beta.11", "1.0.0-beta.2", "1.0.0-beta",
"1.0.0-alpha.beta", "1.0.0-alpha.1", "1.0.0-alpha", "1.10.0", "1.9.0"];
console.log("compare: ", [...versions].sort(compare).join(" "));
console.log("sort(): ", [...versions].sort().join(" "));
const collator = new Intl.Collator("en", { numeric: true });
console.log("collator: ", [...versions].sort(collator.compare).join(" "));
console.log(compare("1.4.2+build.7", "1.4.2+build.8"));
console.log(compare("9007199254740993.0.0", "9007199254740992.0.0"));
console.log(Number("9007199254740993") === Number("9007199254740992"));
for (const text of ["v1.2.3", "1.2", "01.2.3"]) {
try {
parse(text);
} catch (error) {
console.log(error.message);
}
}
compare: 1.0.0-alpha 1.0.0-alpha.1 1.0.0-alpha.beta 1.0.0-beta 1.0.0-beta.2 1.0.0-beta.11 1.0.0-rc.1 1.0.0 1.9.0 1.10.0
sort(): 1.0.0 1.0.0-alpha 1.0.0-alpha.1 1.0.0-alpha.beta 1.0.0-beta 1.0.0-beta.11 1.0.0-beta.2 1.0.0-rc.1 1.10.0 1.9.0
collator: 1.0.0 1.0.0-alpha 1.0.0-alpha.1 1.0.0-alpha.beta 1.0.0-beta 1.0.0-beta.2 1.0.0-beta.11 1.0.0-rc.1 1.9.0 1.10.0
0
1
true
not a semantic version: v1.2.3
not a semantic version: 1.2
not a semantic version: 01.2.3
- Verdict: idiom. JavaScript has no SemVer type. The numbered regex of the specification works in ECMAScript, and
Array.prototype.sorttakes a comparison function. - The default
sort()compares strings, so it gets the order wrong. A collator withnumeric: truefixes 1.9.0 and 1.10.0, but it still puts the release before its pre-releases and does not follow item 11.4. - The example parses numbers as
BigInt. ANumbercannot tell 9007199254740993 from 9007199254740992. - The npm package
semver(node-semver) calls itself "the semantic versioner for npm". It hasvalid,compare,sort,satisfies,coerceand a command-line toolsemver. Its parser removes a leading "v" or "=" by default.
type Version = {
major: number;
minor: number;
patch: number;
prerelease: string[];
};
const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
function parse(text: string): Version | undefined {
const match = SEMVER.exec(text);
if (match === null) return undefined;
const [, major, minor, patch, prerelease] = match;
return {
major: Number(major),
minor: Number(minor),
patch: Number(patch),
prerelease: prerelease === undefined ? [] : prerelease.split("."),
};
}
function compareIdentifiers(a: string, b: string): number {
const an = /^[0-9]+$/.test(a);
const bn = /^[0-9]+$/.test(b);
if (an && bn) return Math.sign(Number(a) - Number(b));
if (an !== bn) return an ? -1 : 1;
return a < b ? -1 : a > b ? 1 : 0;
}
function compare(a: Version, b: Version): number {
const core = Math.sign(a.major - b.major) || Math.sign(a.minor - b.minor) || Math.sign(a.patch - b.patch);
if (core !== 0) return core;
if (a.prerelease.length === 0 || b.prerelease.length === 0) {
return Number(a.prerelease.length === 0) - Number(b.prerelease.length === 0);
}
for (let i = 0; i < Math.min(a.prerelease.length, b.prerelease.length); i++) {
const result = compareIdentifiers(a.prerelease[i], b.prerelease[i]);
if (result !== 0) return result;
}
return Math.sign(a.prerelease.length - b.prerelease.length);
}
const sameCore = (a: Version, b: Version): boolean =>
a.major === b.major && a.minor === b.minor && a.patch === b.patch;
function caretUpper(v: Version): Version {
if (v.major > 0) return { major: v.major + 1, minor: 0, patch: 0, prerelease: ["0"] };
if (v.minor > 0) return { major: 0, minor: v.minor + 1, patch: 0, prerelease: ["0"] };
return { major: 0, minor: 0, patch: v.patch + 1, prerelease: ["0"] };
}
// npm rule: a pre-release matches only if the lower bound is a
// pre-release of the same major, minor and patch.
function satisfiesCaret(candidate: Version, lower: Version): boolean {
if (candidate.prerelease.length > 0 && !(lower.prerelease.length > 0 && sameCore(candidate, lower))) {
return false;
}
return compare(candidate, lower) >= 0 && compare(candidate, caretUpper(lower)) < 0;
}
const candidates = ["1.2.3-beta.4", "1.2.3", "1.2.9", "1.3.0-alpha", "2.0.0-alpha", "2.0.0", "0.2.9", "0.3.0"];
for (const range of ["1.2.3", "1.2.3-beta.2", "0.2.3"]) {
const lower = parse(range);
if (lower === undefined) continue;
const matching = candidates.filter((text) => {
const candidate = parse(text);
return candidate !== undefined && satisfiesCaret(candidate, lower);
});
console.log(`^${range}: ${matching.join(" ")}`);
}
console.log(`v1.2.3: ${parse("v1.2.3") === undefined ? "invalid" : "valid"}`);
^1.2.3: 1.2.3 1.2.9
^1.2.3-beta.2: 1.2.3-beta.4 1.2.3 1.2.9
^0.2.3: 0.2.9
v1.2.3: invalid
- Verdict: idiom. TypeScript has no SemVer type of its own. The numbered regex works in TypeScript as in JavaScript, and a type describes the parsed parts.
- The function
satisfiesCaretfollows the npm rules for a caret range with a full version: the upper bound moves the left-most non-zero number, and-0excludes the pre-releases of the upper bound. - For ranges with all the npm forms, use the npm package
semver. Numberloses precision above 2^53. UseBigIntor compare decimal strings when a version can have larger numbers.
package main
import (
"cmp"
"fmt"
"regexp"
"slices"
"strconv"
"strings"
)
var semver = regexp.MustCompile(`^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)` +
`(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?` +
`(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$`)
type Version struct {
Major, Minor, Patch string
Pre []string
Build string
}
func Parse(text string) (Version, error) {
m := semver.FindStringSubmatch(text)
if m == nil {
return Version{}, fmt.Errorf("not a semantic version: %q", text)
}
v := Version{Major: m[1], Minor: m[2], Patch: m[3], Build: m[5]}
if m[4] != "" {
v.Pre = strings.Split(m[4], ".")
}
return v, nil
}
func isNumeric(s string) bool {
return strings.Trim(s, "0123456789") == ""
}
// compareNumeric compares two decimal strings with no leading zeros.
// A longer string is a larger number, so no integer type can overflow.
func compareNumeric(a, b string) int {
return cmp.Or(cmp.Compare(len(a), len(b)), strings.Compare(a, b))
}
func compareIdentifier(a, b string) int {
switch an, bn := isNumeric(a), isNumeric(b); {
case an && bn:
return compareNumeric(a, b)
case an:
return -1
case bn:
return 1
default:
return strings.Compare(a, b)
}
}
// Compare returns the precedence of a and b. It ignores build metadata.
func Compare(a, b Version) int {
if c := cmp.Or(compareNumeric(a.Major, b.Major), compareNumeric(a.Minor, b.Minor), compareNumeric(a.Patch, b.Patch)); c != 0 {
return c
}
switch {
case len(a.Pre) == 0 && len(b.Pre) == 0:
return 0
case len(a.Pre) == 0:
return 1
case len(b.Pre) == 0:
return -1
}
for i := range min(len(a.Pre), len(b.Pre)) {
if c := compareIdentifier(a.Pre[i], b.Pre[i]); c != 0 {
return c
}
}
return cmp.Compare(len(a.Pre), len(b.Pre))
}
func main() {
texts := []string{"1.0.0", "1.0.0-rc.1", "1.0.0-beta.11", "1.0.0-beta.2", "1.0.0-beta",
"1.0.0-alpha.beta", "1.0.0-alpha.1", "1.0.0-alpha", "1.0.0-alpha.99999999999999999999"}
var versions []Version
for _, text := range texts {
v, err := Parse(text)
if err != nil {
fmt.Println(err)
return
}
versions = append(versions, v)
}
slices.SortFunc(versions, Compare)
for _, v := range versions {
fmt.Println(v.Major+"."+v.Minor+"."+v.Patch, v.Pre)
}
a, _ := Parse("1.4.2+build.7")
b, _ := Parse("1.4.2+build.8")
fmt.Println("precedence:", Compare(a, b), "build:", a.Build, b.Build)
_, err := strconv.Atoi("99999999999999999999")
fmt.Println("Atoi:", err)
for _, text := range []string{"v1.2.3", "1.2", "01.2.3", "1.0.0-01"} {
_, err := Parse(text)
fmt.Println(err)
}
}
1.0.0 [alpha]
1.0.0 [alpha 1]
1.0.0 [alpha 99999999999999999999]
1.0.0 [alpha beta]
1.0.0 [beta]
1.0.0 [beta 2]
1.0.0 [beta 11]
1.0.0 [rc 1]
1.0.0 []
precedence: 0 build: build.7 build.8
Atoi: strconv.Atoi: parsing "99999999999999999999": value out of range
not a semantic version: "v1.2.3"
not a semantic version: "1.2"
not a semantic version: "01.2.3"
not a semantic version: "1.0.0-01"
- Verdict: idiom. The Go standard library has no SemVer package. The package
regexpaccepts the official regex with named groups, andslices.SortFuncsorts with a comparison function. - The example keeps each number as a string and compares the length first. The specification sets no limit on the size of a number, and
strconv.Atoifails on a value larger thanint. - The module
golang.org/x/mod/semverhasCompare,IsValid,Canonical,MajorandSort. Its documentation says that it follows SemVer 2.0.0 with two exceptions: a version must start with "v", and the shorthands vMAJOR and vMAJOR.MINOR are accepted. It is not in the standard library. - Go module versions start with "v". The go command ignores build metadata when it compares versions.
use semver::{BuildMetadata, Version};
fn main() {
let mut versions: Vec<Version> = [
"1.0.0", "1.0.0-rc.1", "1.0.0-beta.11", "1.0.0-beta.2",
"1.0.0-beta", "1.0.0-alpha.beta", "1.0.0-alpha.1", "1.0.0-alpha",
]
.iter()
.map(|text| Version::parse(text).expect("valid version"))
.collect();
versions.sort();
let line: Vec<String> = versions.iter().map(Version::to_string).collect();
println!("{}", line.join(" < "));
let a = Version::parse("1.4.2+build.7").expect("valid version");
let b = Version::parse("1.4.2+build.8").expect("valid version");
println!("a == b: {}", a == b);
println!("same precedence: {}", a.cmp_precedence(&b).is_eq());
println!("build of a: {}, empty: {}", a.build, a.build == BuildMetadata::EMPTY);
for text in ["v1.2.3", "1.2", "01.2.3", "1.2.3-01", "1.2.3-alpha..1"] {
match Version::parse(text) {
Ok(version) => println!("{text}: parsed as {version}"),
Err(error) => println!("{text}: {error}"),
}
}
}
1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0
a == b: false
same precedence: true
build of a: build.7, empty: false
v1.2.3: unexpected character 'v' while parsing major version number
1.2: unexpected end of input while parsing minor version number
01.2.3: invalid leading zero in major version number
1.2.3-01: invalid leading zero in pre-release identifier
1.2.3-alpha..1: empty identifier segment in pre-release identifier
VersionReq reads a requirement with the rules of Cargo. A bare version is a caret requirement. A requirement matches a pre-release only if one of its comparators has a pre-release with the same major, minor and patch.
use semver::{Version, VersionReq};
fn main() -> Result<(), semver::Error> {
let candidates = ["0.2.9", "0.3.0", "1.2.9", "1.3.0", "1.9.0", "2.0.0-rc.1", "2.0.0"];
for text in ["1.2.3", "^0.2.3", "0.0.3", "~1.2", "~1", "1.*", ">=1.2, <1.5", ">=2.0.0-rc.1"] {
let requirement = VersionReq::parse(text)?;
let mut matches = Vec::new();
for candidate in candidates {
if requirement.matches(&Version::parse(candidate)?) {
matches.push(candidate);
}
}
let shown = requirement.to_string();
println!("{text:<14} reads as {shown:<16} matches {matches:?}");
}
let beta = VersionReq::parse("1.0.0-beta")?;
for candidate in ["1.0.0-alpha", "1.0.0-rc.1", "1.0.0", "1.4.0", "1.0.1-alpha"] {
println!("1.0.0-beta matches {candidate}: {}", beta.matches(&Version::parse(candidate)?));
}
Ok(())
}
1.2.3 reads as ^1.2.3 matches ["1.2.9", "1.3.0", "1.9.0"]
^0.2.3 reads as ^0.2.3 matches ["0.2.9"]
0.0.3 reads as ^0.0.3 matches []
~1.2 reads as ~1.2 matches ["1.2.9"]
~1 reads as ~1 matches ["1.2.9", "1.3.0", "1.9.0"]
1.* reads as 1.* matches ["1.2.9", "1.3.0", "1.9.0"]
>=1.2, <1.5 reads as >=1.2, <1.5 matches ["1.2.9", "1.3.0"]
>=2.0.0-rc.1 reads as >=2.0.0-rc.1 matches ["2.0.0-rc.1", "2.0.0"]
1.0.0-beta matches 1.0.0-alpha: false
1.0.0-beta matches 1.0.0-rc.1: true
1.0.0-beta matches 1.0.0: true
1.0.0-beta matches 1.4.0: true
1.0.0-beta matches 1.0.1-alpha: false
- Verdict: library. The Rust standard library has no SemVer type. The examples use the crate
semver1.0.28. Its documentation calls it a parser and evaluator for the Cargo flavour of Semantic Versioning. VersionimplementsOrdwith SemVer precedence, sosortgives the order of item 11. The operator==treats 1.4.2+build.7 and 1.4.2+build.8 as different versions.cmp_precedenceignores the build metadata, so it finds them equal.Version::parserejects the "v" prefix, a missing patch number and leading zeros, with an error that names the problem.VersionReq::parsereads Cargo requirements.VersionReq::matchesapplies the Cargo rule for pre-releases.
Versions
SemVer 1.0.0 and 2.0.0
| Topic | 1.0.0 | 2.0.0 |
|---|---|---|
| Leading zeros in X.Y.Z | no rule | MUST NOT |
| Pre-release | an arbitrary string after a dash | identifiers separated by dots, [0-9A-Za-z-] |
| Pre-release order | lexicographic ASCII sort | item 11.4, numeric identifiers as numbers |
| Build metadata | none | after +, ignored in precedence |
| Tags in version control | MUST be "vX.Y.Z" (SemVerTag) | no rule; the FAQ says "v1.2.3" is a tag name |
Sources: the two specifications.12
Under 1.0.0, the pre-release 1.0.0-beta10 sorts before 1.0.0-beta2, because the comparison is on characters. Under 2.0.0, a project writes 1.0.0-beta.10, and the identifier 10 compares as a number. node-semver still removes a leading "=" or "v" from a version, and says this is for compatibility with version 1.0.0 of the specification.6
Major version zero
Item 4 says that major version zero (0.y.z) is for initial development. Anything MAY change at any time, and the public API SHOULD NOT be considered stable.1 So SemVer itself gives no compatibility promise between 0.1.0 and 0.1.1. The package managers do not follow item 4 exactly. They treat the left-most non-zero number as the major number:
- npm:
^0.2.3means>=0.2.3 <0.3.0-0, and^0.0.3means>=0.0.3 <0.0.4-0.6 - Cargo: the default requirement
0.2.3means>=0.2.3, <0.3.0. The Cargo book says: "This is different from SemVer which considers all pre-1.0.0 packages to be incompatible."7 The Cargo SemVer guide says that a 0.0.z release is always a major change.8 - Composer:
^0.3means>=0.3.0 <0.4.0.11 - Go: a version is unstable if its major version is 0 or it has a pre-release suffix. Unstable versions have no compatibility requirements.9
Ranges in the package managers
SemVer defines versions and their order. It does not define ranges. Each tool has its own syntax.
| Range | npm | Cargo | Composer |
|---|---|---|---|
^1.2.3 |
>=1.2.3 <2.0.0-0 |
>=1.2.3, <2.0.0 |
>=1.2.3 <2.0.0 |
1.2.3 with no operator |
exactly 1.2.3 | same as ^1.2.3 |
exactly 1.2.3 |
~1.2.3 |
>=1.2.3 <1.3.0-0 |
>=1.2.3, <1.3.0 |
>=1.2.3 <1.3.0 |
~1.2 |
>=1.2.0 <1.3.0-0 |
>=1.2.0, <1.3.0 |
>=1.2 <2.0.0 |
Sources: node-semver,6 the Cargo book7 and Composer.11
The rows show two differences. A bare version in Cargo is a caret requirement, but in npm it is an exact match. The tilde with two numbers in Composer allows the next minor versions, while npm and Cargo allow only patch releases. The X-range 1.x of npm and the wildcard 1.* of Cargo both mean 1.0.0 or higher and lower than 2.0.0.67 The -0 in the npm upper bound is the lowest pre-release of that version, so that ^1.2.3 does not match 2.0.0-alpha.
Other systems use SemVer numbers with other rules.
- Go modules. Each version starts with the letter "v", for example v1.12.134 or v2.0.9+meta. Build metadata is ignored when versions are compared.9 From v2, the module path must end with a major version suffix such as
/v2. This implements the import compatibility rule: "If an old package and a new package have the same import path, the new package must be backwards compatible with the old package."9 A pseudo-version such asv0.0.0-20191109021931-daa7c04131f5names a commit that has no tag. The go command picks versions with minimal version selection, and it does not keep a lock file.9 - NuGet. NuGet 4.3.0 and later support SemVer 2.0.0. A plain range such as "1.0" means 1.0 or higher, not a caret range. NuGet has a fourth number, Revision. It compares pre-release labels without case, so 1.0.0-alpha and 1.0.0-Alpha are equal.13
- Python packages. PEP 440 accepts the form MAJOR.MINOR.PATCH. A semantic version with a hyphen or a plus sign is not allowed in the public version field.12 The operator
~=is the "compatible release" clause:~= 1.4.5means>= 1.4.5, == 1.4.*.12
Pitfalls
- String sort. A string sort puts 1.10.0 before 1.9.0, beta.11 before beta.2, and 1.0.0 before 1.0.0-alpha. Parse the parts and sort with the rules of item 11.
- The "v" prefix. "v1.2.3" is not a semantic version.1 Some tools remove the "v" (node-semver, semver4j). Others reject it (the Rust crate
semver). Go requires it.6910 Remove the prefix from a tag name in one place, before the parse. - Leading zeros. 01.2.3 and 1.0.0-01 are not valid. A parser that calls an integer conversion on each part accepts them with no error.
- Unicode digits. In a Python
strpattern,\dmatches any Unicode decimal digit. Other regex engines can do the same. Use[0-9], or the flagre.ASCII.17 - Build metadata and equality. Two versions that differ only in build metadata have the same precedence.1 They are still different texts. Decide if your map keys and sets use the text or the precedence. The Rust crate
semvermakes them unequal for==and equal forcmp_precedence.18 - Pre-releases in ranges. npm and Cargo exclude pre-release versions from a range unless the range asks for one. In npm, a pre-release matches only if a comparator with the same major, minor and patch has a pre-release tag. So
>1.2.3-alpha.3matches 1.2.3-alpha.7 but not 3.4.5-alpha.9.67 - Caret below 1.0.0.
^0.2.3does not allow 0.3.0, and^0.0.3allows only 0.0.3 and its pre-releases. An author who releases 0.3.0 with an additive change gets no automatic upgrade for users.67 - Breaking changes in minor releases. The version number is a promise from a person. Some changes break users with no change to a function name. The Cargo SemVer guide classes the removal of a public item, a public field added to a struct that has no private fields, and a variant added to an enum as major changes.8 The guide also says: "These are only guidelines".8 If a minor release breaks the API by accident, the FAQ says to release a minor version that restores compatibility. The released version MUST NOT change.1
- Upper bounds that are too tight. A requirement such as
>=2.0, <2.4can make the dependency graph unsolvable when another package needs 2.4. The Cargo book advises an upper bound no lower than the next incompatible version, and to use the lock file for tighter control.7 - Lock files. A range lets the resolver pick a later patch or minor version. Two builds of the same code can get different dependencies. A lock file such as Cargo.lock records the exact versions.7 Go has no lock file. Minimal version selection is deterministic, and the build list has the minimum versions that satisfy all requirements.9
- System.Version is not SemVer. In .NET,
System.Versionrepresents the version number of an assembly, an operating system or the runtime.16 It has up to four numbers and no pre-release. UseNuGet.Versioningor another SemVer type.
Tools and libraries
| Language | Verdict | SemVer support |
|---|---|---|
| Python | idiom | the official regex with re, and a tuple key for sorted17 |
| JavaScript, TypeScript | idiom | the numbered regex in the language; the npm package semver (node-semver) for ranges6 |
| Go | idiom | the official regex with regexp; the module golang.org/x/mod/semver with the "v" prefix10 |
| Rust | library | the crate semver: Version, VersionReq with Cargo rules18 |
| Java | library | semver4j: Semver.parse, satisfies with npm-style ranges19 |
| C# | library | System.Version is not SemVer; the package NuGet.Versioning has NuGetVersion.Parse and VersionComparer1316 |
| C++ | idiom | std::regex with the numbered regex and a comparator |
| PowerShell | stdlib | the type accelerator [semver] for System.Management.Automation.SemanticVersion1415 |
| Bash | library | the command semver of the npm package semver6 |
Package managers are the main users of the standard. npm and Cargo resolve ranges with the rules of node-semver and the crate semver.67 The go command uses the rules of the Go modules reference.9 NuGet uses NuGet.Versioning.13
References
- Semantic Versioning 2.0.0, Summary; Introduction; Semantic Versioning Specification (SemVer), items 1 to 11; Backus–Naur Form Grammar for Valid SemVer Versions; FAQ; About
- Semantic Versioning 1.0.0, Semantic Versioning Specification (SemVer); Tagging Specification (SemVerTag); About
- semver/semver.org, commit ca64580, "First commit", Tom Preston-Werner, 2009-12-14, the commit and the file index.md
- semver/semver, commit ec27d6a, "Extract spec from https://github.com/mojombo/semver.org.", 2011-06-08, the commit message
- semver/semver, commit 7c834b3, "Merge pull request, the commit, which the tag v2.0.0 points to
- npm, node-semver README (package version 7.8.6), Versions; Ranges; Prerelease Tags; Advanced Range Syntax (Hyphen Ranges, X-Ranges, Tilde Ranges, Caret Ranges); Coercion
- The Cargo Book, Specifying Dependencies, Default requirements; Caret requirements; Tilde requirements; Wildcard requirements; Pre-releases; Version metadata; the recommendation on upper bounds
- The Cargo Book, SemVer Compatibility, SemVer compatibility; Change categories; item-remove; struct-add-public-field-when-no-private; enum-variant-new
- Go Modules Reference, Versions; Pseudo-versions; Major version suffixes; Minimal version selection (MVS)
- Go package golang.org/x/mod/semver, the package overview and func Compare
- Composer documentation, Versions and constraints, Tilde Version Range (~); Caret Version Range (^)
- PEP 440: Version Identification and Dependency Specification, Semantic versioning; Compatible release
- NuGet documentation, Package versioning, Semantic Versioning 2.0.0; Version ranges; Normalized version numbers; Where NuGetVersion diverges from Semantic Versioning
- PowerShell SDK, SemanticVersion Class, the class description
- PowerShell documentation, about_Type_Accelerators, the table of type accelerators (semver)
- .NET API, Version Class, the class description
- The Python Standard Library, re, Python 3.14, Regular Expression Syntax, \d; Flags, re.ASCII
- semver 1.0.28 documentation, struct Version (Syntax, Total ordering, parse, cmp_precedence); struct VersionReq
- semver4j, the README
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag NY2T0V Edit this page History Report an error Markdown