Conceptcore
Version constraints
Also called version constraint, version requirement, version range, version specifier, caret range, tilde range, compatible release, semver range.
A version constraint names the versions of a dependency that a project accepts. Each ecosystem has its own range syntax, such as the caret and tilde of npm and Cargo, or intervals in Maven.
- Applies to
- core-languages
Idea
A dependency in a manifest file has a name and a version constraint: the set of versions that the project accepts. An exact version is the narrowest constraint. A range lets the package manager choose a newer version that has bug fixes, while it keeps out versions that can break the project.
Most ranges rely on Semantic Versioning. Under it, a version is MAJOR.MINOR.PATCH, and you increment MAJOR "when you make incompatible API changes", MINOR "when you add functionality in a backward compatible manner" and PATCH "when you make backward compatible bug fixes".1 So a range from 1.2.3 up to, but not including, 2.0.0 accepts the fixes and the new features of version 1, and it keeps out the next incompatible version.
Each ecosystem writes ranges in its own way, and the same text can mean different things. In npm, 1.2.3 is one exact version.2 In Cargo, 1.2.3 is the range from 1.2.3 up to, but not including, 2.0.0.3
How it works
A constraint is a set of comparisons that a version must all satisfy. In npm, a comparator set such as >=1.2.7 <1.3.0 matches 1.2.7, 1.2.8 and 1.2.99, but not 1.2.6, 1.3.0 or 1.1.0.2 In Python the comparisons are joined with commas, as in ~= 0.9, >= 1.0, != 1.3.4.*, < 2.0, and "The comma (“,”) is equivalent to a logical and operator".4
Short forms expand to such ranges:
| Constraint | npm | Cargo |
|---|---|---|
^1.2.3 |
>=1.2.3 <2.0.0-0 |
>=1.2.3, <2.0.0 |
^0.2.3 |
>=0.2.3 <0.3.0-0 |
>=0.2.3, <0.3.0 |
^0.0.3 |
>=0.0.3 <0.0.4-0 |
>=0.0.3, <0.0.4 |
~1.2.3 |
>=1.2.3 <1.3.0-0 |
>=1.2.3, <1.3.0 |
1.2.3 |
exactly 1.2.3 | the same as ^1.2.3 |
The caret allows the changes that "do not modify the left-most non-zero element" of the version, in the words of the npm documentation.2 So for a version 0.x, a change of the minor number counts as a break. Cargo calls the caret requirement "the default version requirement strategy", and it treats versions as compatible "if their left-most non-zero major/minor/patch component is the same". Cargo notes that "This is different from SemVer which considers all pre-1.0.0 packages to be incompatible".3 SemVer itself says that "Anything MAY change at any time" in major version zero.1
The tilde is narrower. With a major, minor and patch version, only patch-level changes are allowed.32 The -0 at the end of the npm upper bounds excludes the prereleases of the next version, such as 2.0.0-beta.
The examples below expand caret, tilde and exact constraints into a range from a lowest version up to a first version that is not allowed, and test eleven versions against each range.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | A std::array<int, 3> for a version; arrays compare element by element with the operator <=>. Alternative: The Go example. |
| Java | Idiom | |
| C | Idiom | An array of three ints for a version and a compare function that returns a negative, zero or positive number. Alternative: The Go example. |
| C# | Idiom | |
| JavaScript | Idiom | The npm package semver gives satisfies and validRange, and the same parse and compare code is short in plain JavaScript. Alternative: The Python example. |
| TypeScript | Idiom | As in JavaScript, with a tuple type [number, number, number] for a version. Alternative: The Go example. |
| Go | Idiom | |
| Rust | Idiom | The semver crate gives VersionReq and Version, with the same caret and tilde rules as Cargo. Alternative: The Go example. |
| Kotlin | Idiom | A data class that implements Comparable, as in the Java example. Alternative: The Java example. |
| SQL | Idiom | A query can store the major, minor and patch numbers in columns and compare them as a row value. Alternative: The Python example. |
| Bash | Idiom | Sort -V sorts version strings, and a script can split a version on dots with read. Alternative: The Python example. |
| PowerShell | Idiom | The [version] type accelerator parses and compares versions, as System.Version does in the C# example. Alternative: The C# example. |
| HTML | Does not apply | Markup does not compare versions. |
| CSS | Does not apply | Style rules do not compare versions. |
| Regular expressions | Does not apply | A pattern can check the syntax of a version, but it does not compare versions. |
Each example parses a version into three numbers, so that 1.10.0 sorts after 1.9.0. The Python and Go examples compare tuples and arrays of numbers. The Java example uses a record that implements Comparable, and the C# example uses the built-in type System.Version, which has the comparison operators. None of the examples handles prerelease tags.
# Turn caret, tilde and exact constraints into a range [low, high), then test versions against it.
def parse(version):
return tuple(int(part) for part in version.split("."))
def show(version):
return ".".join(str(part) for part in version)
def to_range(constraint):
op = constraint[0] if constraint[0] in "^~" else ""
low = parse(constraint[len(op):])
major, minor, patch = low
if op == "^": # keep the left-most part that is not zero
if major > 0:
high = (major + 1, 0, 0)
elif minor > 0:
high = (0, minor + 1, 0)
else:
high = (0, 0, patch + 1)
elif op == "~": # allow patch changes only
high = (major, minor + 1, 0)
else: # an exact version
high = (major, minor, patch + 1)
return low, high
CANDIDATES = ["0.0.4", "0.0.5", "0.2.3", "0.2.4", "0.2.9", "0.3.0",
"1.2.2", "1.2.3", "1.2.9", "1.4.0", "2.0.0"]
print("versions:", " ".join(CANDIDATES))
for constraint in ["^1.2.3", "^0.2.4", "^0.0.4", "~1.2.3", "~0.2.4", "1.2.3"]:
low, high = to_range(constraint)
matches = [v for v in CANDIDATES if low <= parse(v) < high]
print(f"{constraint} means >={show(low)} <{show(high)}, matches {' '.join(matches)}")
versions: 0.0.4 0.0.5 0.2.3 0.2.4 0.2.9 0.3.0 1.2.2 1.2.3 1.2.9 1.4.0 2.0.0
^1.2.3 means >=1.2.3 <2.0.0, matches 1.2.3 1.2.9 1.4.0
^0.2.4 means >=0.2.4 <0.3.0, matches 0.2.4 0.2.9
^0.0.4 means >=0.0.4 <0.0.5, matches 0.0.4
~1.2.3 means >=1.2.3 <1.3.0, matches 1.2.3 1.2.9
~0.2.4 means >=0.2.4 <0.3.0, matches 0.2.4 0.2.9
1.2.3 means >=1.2.3 <1.2.4, matches 1.2.3
- Verdict: idiom. A version is a tuple of three ints, and Python compares tuples element by element, so
low <= parse(v) < highis the whole range test. - The constraint
1.2.3here has the npm meaning, one exact version. In Cargo it would mean^1.2.3. - For real projects, the
packaginglibrary parses and compares Python versions and specifiers.
// Turn caret, tilde and exact constraints into a range [low, high), then test versions against it.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
record Version(int major, int minor, int patch) implements Comparable<Version> {
static Version parse(String s) {
int[] p = Arrays.stream(s.split("\\.")).mapToInt(Integer::parseInt).toArray();
return new Version(p[0], p[1], p[2]);
}
public int compareTo(Version o) {
if (major != o.major) {
return Integer.compare(major, o.major);
}
if (minor != o.minor) {
return Integer.compare(minor, o.minor);
}
return Integer.compare(patch, o.patch);
}
@Override
public String toString() {
return major + "." + minor + "." + patch;
}
}
record Range(Version low, Version high) {
boolean contains(Version v) {
return low.compareTo(v) <= 0 && v.compareTo(high) < 0;
}
}
static Range toRange(String constraint) {
char first = constraint.charAt(0);
String op = first == '^' || first == '~' ? String.valueOf(first) : "";
Version low = Version.parse(constraint.substring(op.length()));
Version high = switch (op) {
case "^" -> low.major() > 0 ? new Version(low.major() + 1, 0, 0) // keep the left-most part that is not zero
: low.minor() > 0 ? new Version(0, low.minor() + 1, 0)
: new Version(0, 0, low.patch() + 1);
case "~" -> new Version(low.major(), low.minor() + 1, 0); // allow patch changes only
default -> new Version(low.major(), low.minor(), low.patch() + 1); // an exact version
};
return new Range(low, high);
}
public static void main(String[] args) {
List<String> candidates = List.of("0.0.4", "0.0.5", "0.2.3", "0.2.4", "0.2.9", "0.3.0",
"1.2.2", "1.2.3", "1.2.9", "1.4.0", "2.0.0");
System.out.println("versions: " + String.join(" ", candidates));
for (String constraint : List.of("^1.2.3", "^0.2.4", "^0.0.4", "~1.2.3", "~0.2.4", "1.2.3")) {
Range r = toRange(constraint);
String matches = candidates.stream()
.filter(c -> r.contains(Version.parse(c)))
.collect(Collectors.joining(" "));
System.out.println(constraint + " means >=" + r.low() + " <" + r.high() + ", matches " + matches);
}
}
}
versions: 0.0.4 0.0.5 0.2.3 0.2.4 0.2.9 0.3.0 1.2.2 1.2.3 1.2.9 1.4.0 2.0.0
^1.2.3 means >=1.2.3 <2.0.0, matches 1.2.3 1.2.9 1.4.0
^0.2.4 means >=0.2.4 <0.3.0, matches 0.2.4 0.2.9
^0.0.4 means >=0.0.4 <0.0.5, matches 0.0.4
~1.2.3 means >=1.2.3 <1.3.0, matches 1.2.3 1.2.9
~0.2.4 means >=0.2.4 <0.3.0, matches 0.2.4 0.2.9
1.2.3 means >=1.2.3 <1.2.4, matches 1.2.3
- Verdict: idiom. A record implements
Comparable, so versions compare by major, then minor, then patch. - A switch expression picks the upper bound, and a nested conditional handles the three cases of the caret.
- The record
Rangeholds the bounds and the testcontains.
// Turn caret, tilde and exact constraints into a range [low, high), then test versions against it.
static (Version Low, Version High) ToRange(string constraint)
{
var op = constraint[0] is '^' or '~' ? constraint[..1] : "";
var low = Version.Parse(constraint[op.Length..]);
var high = op switch
{
"^" when low.Major > 0 => new Version(low.Major + 1, 0, 0), // keep the left-most part that is not zero
"^" when low.Minor > 0 => new Version(0, low.Minor + 1, 0),
"^" => new Version(0, 0, low.Build + 1),
"~" => new Version(low.Major, low.Minor + 1, 0), // allow patch changes only
_ => new Version(low.Major, low.Minor, low.Build + 1), // an exact version
};
return (low, high);
}
string[] candidates = ["0.0.4", "0.0.5", "0.2.3", "0.2.4", "0.2.9", "0.3.0",
"1.2.2", "1.2.3", "1.2.9", "1.4.0", "2.0.0"];
Console.WriteLine("versions: " + string.Join(" ", candidates));
foreach (var constraint in new[] { "^1.2.3", "^0.2.4", "^0.0.4", "~1.2.3", "~0.2.4", "1.2.3" })
{
var (low, high) = ToRange(constraint);
var matches = candidates.Where(c => Version.Parse(c) >= low && Version.Parse(c) < high);
Console.WriteLine($"{constraint} means >={low} <{high}, matches {string.Join(" ", matches)}");
}
versions: 0.0.4 0.0.5 0.2.3 0.2.4 0.2.9 0.3.0 1.2.2 1.2.3 1.2.9 1.4.0 2.0.0
^1.2.3 means >=1.2.3 <2.0.0, matches 1.2.3 1.2.9 1.4.0
^0.2.4 means >=0.2.4 <0.3.0, matches 0.2.4 0.2.9
^0.0.4 means >=0.0.4 <0.0.5, matches 0.0.4
~1.2.3 means >=1.2.3 <1.3.0, matches 1.2.3 1.2.9
~0.2.4 means >=0.2.4 <0.3.0, matches 0.2.4 0.2.9
1.2.3 means >=1.2.3 <1.2.4, matches 1.2.3
- Verdict: idiom. The built-in class
System.Versionparses1.2.3and has the operators<and>=. System.Versioncalls the third partBuild, not patch, and it has no prerelease tags. A SemVer library is needed for versions such as 1.2.3-beta.- A switch expression with
whenclauses picks the upper bound.
// Turn caret, tilde and exact constraints into a range [low, high), then test versions against it.
package main
import (
"fmt"
"slices"
"strconv"
"strings"
)
type version [3]int
func parse(s string) version {
var v version
for i, part := range strings.Split(s, ".") {
v[i], _ = strconv.Atoi(part)
}
return v
}
func (v version) String() string { return fmt.Sprintf("%d.%d.%d", v[0], v[1], v[2]) }
func less(a, b version) bool { return slices.Compare(a[:], b[:]) < 0 }
func toRange(constraint string) (low, high version) {
op := ""
if strings.HasPrefix(constraint, "^") || strings.HasPrefix(constraint, "~") {
op = constraint[:1]
}
low = parse(constraint[len(op):])
major, minor, patch := low[0], low[1], low[2]
switch {
case op == "^" && major > 0: // keep the left-most part that is not zero
high = version{major + 1, 0, 0}
case op == "^" && minor > 0:
high = version{0, minor + 1, 0}
case op == "^":
high = version{0, 0, patch + 1}
case op == "~": // allow patch changes only
high = version{major, minor + 1, 0}
default: // an exact version
high = version{major, minor, patch + 1}
}
return low, high
}
func main() {
candidates := []string{"0.0.4", "0.0.5", "0.2.3", "0.2.4", "0.2.9", "0.3.0",
"1.2.2", "1.2.3", "1.2.9", "1.4.0", "2.0.0"}
fmt.Println("versions:", strings.Join(candidates, " "))
for _, constraint := range []string{"^1.2.3", "^0.2.4", "^0.0.4", "~1.2.3", "~0.2.4", "1.2.3"} {
low, high := toRange(constraint)
var matches []string
for _, c := range candidates {
if v := parse(c); !less(v, low) && less(v, high) {
matches = append(matches, c)
}
}
fmt.Printf("%s means >=%v <%v, matches %s\n", constraint, low, high, strings.Join(matches, " "))
}
}
versions: 0.0.4 0.0.5 0.2.3 0.2.4 0.2.9 0.3.0 1.2.2 1.2.3 1.2.9 1.4.0 2.0.0
^1.2.3 means >=1.2.3 <2.0.0, matches 1.2.3 1.2.9 1.4.0
^0.2.4 means >=0.2.4 <0.3.0, matches 0.2.4 0.2.9
^0.0.4 means >=0.0.4 <0.0.5, matches 0.0.4
~1.2.3 means >=1.2.3 <1.3.0, matches 1.2.3 1.2.9
~0.2.4 means >=0.2.4 <0.3.0, matches 0.2.4 0.2.9
1.2.3 means >=1.2.3 <1.2.4, matches 1.2.3
- Verdict: idiom. A version is an array of three ints, and
slices.Comparecompares two arrays element by element. - The method
Stringlets%vprint a version as 1.2.3. - For module versions, the package golang.org/x/mod/semver compares versions that start with a v.
Variations and related ideas
- Python. A version specifier is a list of clauses with the operators
~=,==,!=,<=,>=,<,>and===. The compatible release clause~= 2.2is the same as>= 2.2, == 2.*, and~= 1.4.5is the same as>= 1.4.5, == 1.4.*.4 - NuGet. NuGet uses interval notation:
[1.0,2.0)means 1.0 ≤ x < 2.0, and[1.0]means exactly 1.0. A plain1.0is a minimum version, inclusive.5 - Maven. Maven has the same interval notation, and it splits requirements into two kinds. A plain
1.0is a soft requirement: "Use 1.0 if no other version appears earlier in the dependency tree". A range such as[1.0,2.0)is a hard requirement. Maven "picks the highest version of each project that satisfies all the hard requirements", and the build fails if no version satisfies them.6 - Go. A
requiredirective "declares a minimum required version", with no upper limit.7 A new major version gets a new module path, such asexample.com/mod/v2. This follows 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".7 So two major versions are two different modules. - Prereleases. In npm, a version with a prerelease tag, such as
1.2.3-alpha.3, satisfies a range only if a comparator with the same major, minor and patch numbers also has a prerelease tag.2 Python has its own rules for the handling of pre-releases.4
Pitfalls
- The same text, another meaning.
1.2.3is exact in npm, the same as^1.2.3in Cargo, a minimum in NuGet and a soft requirement in Maven.2356 Check the syntax of the ecosystem before you copy a constraint. - Versions below 1.0. Under the caret,
^0.2.3does not accept 0.3.0, and^0.0.3accepts no other version.23 A library at 0.x that adds a feature in 0.3.0 does not reach users with^0.2.3. - Ranges that are too wide.
*or>=1.0accepts the next major version, with its incompatible changes. SemVer gives the meaning of the numbers, but only the authors of a package can follow it.1 - Ranges that are too narrow. If every library pins an exact version, two libraries that need different patch versions of the same package can make the resolution fail. See Dependency resolution.
- String order. Compare versions as numbers, not as strings: in a comparison of strings, 1.10.0 sorts before 1.9.0. SemVer requires that each element "MUST increase numerically", as in 1.9.0, 1.10.0, 1.11.0.1
Cost
A range check is cheap: parse the version and compare a few numbers. The cost of a constraint is in what it lets through. A wide range lets new, untested versions into the build; a narrow range makes upgrades and resolution harder. Most projects use a range in the manifest and record the exact versions in a lock file; see Lock files.
History
Tom Preston-Werner first wrote the Semantic Versioning specification.1 Its version 2.0.0, which comes after 1.0.0 and two release candidates, was marked as final in a commit of 18 June 2013.18 node-semver describes a version by the 2.0.0 specification, Cargo builds its default requirements on SemVer compatibility, and NuGet supports SemVer 2.0.0 from NuGet 4.3.0.235 Maven follows the precedence rules of SemVer 1.0.0 in most cases, but its version order is not compatible with SemVer 2.0.0.6 Python has its own version scheme and specifiers, defined in the Python packaging specifications.4 Go chose minimum versions and major version suffixes for its modules.7
References
- Semantic Versioning 2.0.0, Summary; Semantic Versioning Specification, items 4 and 8
- npm, node-semver (README), Ranges; Advanced Range Syntax, Tilde Ranges, Caret Ranges; Prerelease Tags
- The Cargo Book, Specifying Dependencies, Version requirement syntax; Default requirements; Caret requirements; Tilde requirements
- Python Packaging User Guide, Version specifiers, Version specifiers; Compatible release
- NuGet documentation, Package versioning, Version basics; Version ranges
- Maven, POM Reference, Dependency Version Requirement Specification; Version Order Specification
- Go Modules Reference, Major version suffixes; require directive
- semver/semver, commit 7c834b3, Mark 2.0.0 as RTM, the commit of the tag v2.0.0, the commit date, 2013-06-18
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 PBRTQC Edit this page History Report an error Markdown