TExcelTAD
Home › Build Fundamentals: From Source to Binary › Versions & Semver Ranges

Versions & Semver Ranges

So far every input of the build was a file in your project. Real projects also depend on other people's code: libraries that are released in versions, downloaded by a package manager, and updated on their own schedule. Two ideas make that manageable: a version scheme that says what kind of change a new release contains, and version ranges that say which releases your project accepts.

Semantic Versioning

Semantic Versioning (semver) is the most common scheme. A version is MAJOR.MINOR.PATCH, optionally followed by a pre-release tag (-beta.2) and build metadata (+git.5f3a):

Bump When Example
MAJOR incompatible API change (something removed or changed) 1.9.3 → 2.0.0
MINOR new functionality, backwards compatible 1.9.3 → 1.10.0
PATCH backwards-compatible bug fix 1.9.3 → 1.9.4

Rules that trip people up:

  • Versions compare numerically, part by part: 1.10.0 is newer than 1.9.0.
  • A pre-release is lower than its release: 2.0.0-rc.1 < 2.0.0.
  • 0.x is special: before 1.0 anything may change at any time. Most tools treat 0.MINOR as if it were the major version (0.3 → 0.4 may break you).
  • Build metadata (+…) is ignored when comparing.

Semver is a promise made by humans. A "patch" release can still break you, which is why lockfiles (next lesson) exist.

Version ranges

A manifest rarely pins an exact version. It states a range, and the package manager picks a version inside it. The syntax differs per ecosystem, but the common operators mean the same thing:

Range Means npm Cargo Others
^1.4.2 compatible with 1.4.2: >=1.4.2 <2.0.0 yes default for "1.4.2" Poetry, Composer
^0.4.2 >=0.4.2 <0.5.0 (0.x: minor is "major") yes yes
~1.4.2 patch updates only: >=1.4.2 <1.5.0 yes yes Poetry; pip's ~=1.4.2 is similar
1.4.x / 1.4.* any 1.4 patch yes yes pip ==1.4.*
>=1.2, <2 explicit comparators >=1.2 <2 >=1.2, <2 pip, Conan [>=1.2 <2]
1.4.2 exactly 1.4.2 yes no: it means ^1.4.2 pip needs ==

Note the row for a bare 1.4.2: npm reads it as exact, Cargo as ^1.4.2. Reading another ecosystem's manifest with your own ecosystem's rules is a classic mistake.

Model: a range matcher

This model implements the npm-style operators above, including the 0.x rule and the rule that a pre-release only matches a range that mentions a pre-release of the same version:

js · try it yourself
const parse = (v) => {
  const [core, pre] = v.split("+")[0].split("-");
  const [major, minor = 0, patch = 0] = core.split(".").map(Number);
  return { major, minor, patch, pre: pre ?? null };
};
function compare(a, b) {
  for (const k of ["major", "minor", "patch"]) if (a[k] !== b[k]) return a[k] - b[k];
  if (a.pre === b.pre) return 0;
  if (a.pre === null) return 1;                     // release > pre-release
  if (b.pre === null) return -1;
  return a.pre < b.pre ? -1 : 1;                    // (real semver compares dot-separated parts)
}
// Turn one range into [lower bound, upper bound) comparators.
function toComparators(range) {
  const out = [];
  for (const part of range.split(/\s+/)) {
    const m = part.match(/^(\^|~|>=|<=|>|<|=)?(.*)$/);
    const op = m[1] ?? "=", raw = m[2];
    if (raw.includes("x")) {                        // 1.4.x
      const [maj, min] = raw.split(".").map(Number);
      out.push([">=", parse(`${maj}.${min}.0`)], ["<", parse(`${maj}.${min + 1}.0-0`)]);
      continue;
    }
    const v = parse(raw);
    if (op === "^") {
      const upper = v.major > 0 ? `${v.major + 1}.0.0` : v.minor > 0 ? `0.${v.minor + 1}.0` : `0.0.${v.patch + 1}`;
      out.push([">=", v], ["<", parse(upper + "-0")]);
    } else if (op === "~") out.push([">=", v], ["<", parse(`${v.major}.${v.minor + 1}.0-0`)]);
    else out.push([op, v]);
  }
  return out;
}
function satisfies(version, range) {
  const v = parse(version), comps = toComparators(range);
  if (v.pre && !comps.some(([, c]) => c.pre && c.pre !== "0" && compare({ ...c, pre: null }, { ...v, pre: null }) === 0)) return false;
  return comps.every(([op, c]) => {
    const r = compare(v, c);
    return { "=": r === 0, ">=": r >= 0, ">": r > 0, "<=": r <= 0, "<": r < 0 }[op];
  });
}

const available = ["1.3.9", "1.4.0", "1.4.2", "1.4.7", "1.10.0", "2.0.0-rc.1", "2.0.0", "0.4.1", "0.4.9", "0.5.0"];
for (const range of ["^1.4.2", "~1.4.2", "1.4.x", ">=1.4.0 <1.10.0", "^0.4.1", ">=2.0.0-rc.1"]) {
  const ok = available.filter((v) => satisfies(v, range));
  console.log(`${range.padEnd(16)} -> ${ok.join(", ")}`);
}
^1.4.2           -> 1.4.2, 1.4.7, 1.10.0
~1.4.2           -> 1.4.2, 1.4.7
1.4.x            -> 1.4.0, 1.4.2, 1.4.7
>=1.4.0 <1.10.0  -> 1.4.0, 1.4.2, 1.4.7
^0.4.1           -> 0.4.1, 0.4.9
>=2.0.0-rc.1     -> 2.0.0-rc.1, 2.0.0
  • ^1.4.2 accepts 1.10.0 (numeric comparison: 10 > 4) but not 2.0.0-rc.1, because a pre-release is not picked unless the range asks for one.
  • ^0.4.1 stops before 0.5.0: the 0.x rule.
  • >=2.0.0-rc.1 mentions a 2.0.0 pre-release, so 2.0.0-rc.1 is allowed, and 2.0.0 too.

A package manager then usually picks the highest version in the range (npm, Cargo, pip, Conan). Go is the notable exception: it picks the minimum version that satisfies everyone (Go Modules in Depth explains why).

Version checks in C: pkg-config

C and C++ have no single package manager, but they have a long-standing convention for finding installed libraries and checking their versions: pkg-config. Each library installs a .pc file with its version, compiler flags and linker flags. Build systems (Meson, CMake's pkg_check_modules, Autotools) call it:

bash · try it yourself
mkdir -p pc
cat > pc/tadmath.pc <<'PC'
prefix=/opt/tadmath
libdir=${prefix}/lib
includedir=${prefix}/include

Name: tadmath
Description: Small maths helpers
Version: 1.4.2
Cflags: -I${includedir}
Libs: -L${libdir} -ltadmath
PC
export PKG_CONFIG_PATH=$PWD/pc
pkg-config --modversion tadmath
pkg-config --cflags --libs tadmath
pkg-config --atleast-version=1.2 tadmath && echo "1.2 or newer: yes"
pkg-config --print-errors 'tadmath >= 2.0' || echo "exit status: $?"
1.4.2
-I/opt/tadmath/include -L/opt/tadmath/lib -ltadmath
1.2 or newer: yes
Package dependency requirement 'tadmath >= 2.0' could not be satisfied.
Package 'tadmath' has version '1.4.2', required version is '>= 2.0'
exit status: 1

pkg-config understands comparisons (>=, <, =), not caret or tilde ranges, and only checks what is already installed: it never downloads anything. Package managers for C/C++ (Conan, vcpkg) are the subject of C/C++ Packages.

Test yourself

Which versions does ^1.4.2 accept?

  1. Only 1.4.2
  2. >=1.4.2 <1.5.0
  3. >=1.4.2 <2.0.0
  4. Any version

Why does ^0.4.1 not accept 0.5.0?

  1. 0.5.0 is a pre-release
  2. Before 1.0, the minor number acts as the major: ^0.4.1 means >=0.4.1 <0.5.0
  3. Carets only allow patches
  4. It's a bug

A Cargo.toml says serde = "1.0.200". What does Cargo accept?

  1. Exactly 1.0.200
  2. ^1.0.200, i.e. >=1.0.200 <2.0.0
  3. Any 1.0.x
  4. The latest version