SemVer 2.0.0 Versioning Calculator
Parse Semantic Versioning strings, calculate next major/minor/patch releases, and resolve npm caret (^) and tilde (~) ranges.
Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.
What is Semantic Versioning (SemVer 2.0.0)?
Semantic Versioning (SemVer 2.0.0) is an authoritative software engineering specification created by GitHub co-founder Tom Preston-Werner designed to solve "Dependency Hell"—the catastrophic state where complex software dependency graphs become impossible to upgrade without breaking runtime compatibility.
Standardized across modern package management ecosystems—including npm (JavaScript/TypeScript), Cargo (Rust), Go Modules, Composer (PHP), NuGet (.NET), and Maven (Java)—SemVer communicates the exact architectural impact of code modifications through a deterministic three-part version sequence:
$$\texttt{MAJOR}.\texttt{MINOR}.\texttt{PATCH}[-\texttt{PRERELEASE}][+\texttt{BUILDMETADATA}]$$
Example: 2.4.1-rc.2+sha.d9f8e7a
By encoding breaking API changes, backward-compatible feature expansions, and bug patches directly into version numbers, automated package managers can safely execute automatic dependency upgrades (such as patch security updates) while preventing breaking modifications from destabilizing enterprise production applications.
The SemVer 2.0.0 Three-Part Core Architecture
flowchart TD
Release["New Software Code Commit / Tag"] --> ImpactCheck{Nature of API Modification}
ImpactCheck -- "Breaking Change (Backwards Incompatible)" --> BumpMajor["Bump MAJOR: 1.4.2 -> 2.0.0 (Reset Minor & Patch to 0)"]
ImpactCheck -- "New Feature (Backwards Compatible)" --> BumpMinor["Bump MINOR: 1.4.2 -> 1.5.0 (Reset Patch to 0)"]
ImpactCheck -- "Bug Fix (Backwards Compatible)" --> BumpPatch["Bump PATCH: 1.4.2 -> 1.4.3"]
BumpMajor & BumpMinor & BumpPatch --> PreReleaseCheck{"Is Release Ready for Production?"}
PreReleaseCheck -- "Internal Testing / Staging" --> AddPre["Append Pre-Release Tag: -alpha.1, -beta.2, -rc.1"]
PreReleaseCheck -- "Production Golden Release" --> CleanVersion["Emit Final Canonical Version"]
AddPre & CleanVersion --> BuildMeta{"Attach CI/CD Commit Hash?"}
BuildMeta -- Yes --> AddMeta["Append Build Metadata: +sha.a1b2c3d"]
BuildMeta -- No --> FinalTag["Publish to Package Registry"]
1. MAJOR Version (Breaking API Contracts)
Incremented when software introduces backward-incompatible API changes.
- Any function signature modification, removed endpoint, altered parameter type, or deprecated protocol forces a MAJOR increment (e.g.
1.8.4$\to$2.0.0). - Incrementing MAJOR strictly requires resetting MINOR and PATCH to
0.
2. MINOR Version (Backward-Compatible Features)
Incremented when new functionality or public API methods are introduced in a strictly backward-compatible manner (e.g. 2.4.1 $\to$ 2.5.0).
- Existing consumer code can upgrade with zero modifications and zero broken behavior.
- Incrementing MINOR strictly requires resetting PATCH to
0.
3. PATCH Version (Backward-Compatible Bug Fixes)
Incremented for internal bug fixes, security hotfixes, or performance optimizations that do not alter the public API contract (e.g. 2.5.0 $\to$ 2.5.1).
4. The 0.y.z Initial Development Phase Rule
Under SemVer 2.0.0 §4:
Major version zero (
0.y.z) is for initial development. Anything MAY change at any time. The public API should NOT be considered stable.
In the 0.x.x regime, package managers treat MINOR version increments (0.1.0 to 0.2.0) as breaking changes.
Package Manager Range Operators Matrix (npm & Cargo)
Package dependency files (package.json, Cargo.toml) use specialized range symbols to govern automated build resolution:
| Range Operator | Syntax Example | Resolved Version Boundary Range | Resolution Rationale |
|---|---|---|---|
Caret (^) | ^1.2.3 | $\ge 1.2.3 \text{ and } < 2.0.0$ | Default npm standard: Permits backward-compatible features and bug fixes; locks breaking MAJOR. |
Caret on Zero (^0.x) | ^0.2.3 | $\ge 0.2.3 \text{ and } < 0.3.0$ | Zero-protection rule: In 0.x, minor changes are breaking; caret locks minor version! |
Tilde (~) | ~1.2.3 | $\ge 1.2.3 \text{ and } < 1.3.0$ | Strict patch locking: Permits bug fixes only; forbids MINOR feature upgrades. |
| Exact Version | 1.2.3 | $= 1.2.3$ | Locks exact release; zero updates permitted without manual lockfile edits. |
Wildcard (* / x) | 1.2.x | $\ge 1.2.0 \text{ and } < 1.3.0$ | Accepts any patch in the 1.2 branch. |
| Hyphen Range | 1.2.0 - 2.1.0 | $\ge 1.2.0 \text{ and } \le 2.1.0$ | Inclusive boundary range across releases. |
| Greater Than Equal | >= 2.0.0 | $\ge 2.0.0$ | Open-ended upper bound (dangerous in production builds). |
Precedence Rules: Sorting Pre-Releases & Build Metadata
SemVer 2.0.0 §11 defines strict mathematical precedence order:
- Normal Version Precedence: Compared numerically:
1.0.0 < 2.0.0 < 2.1.0 < 2.1.1. - Pre-Release Precedence: A pre-release version has lower precedence than the associated normal version: $$1.0.0\text{-alpha} < 1.0.0\text{-alpha.1} < 1.0.0\text{-beta} < 1.0.0\text{-rc.1} < \mathbf{1.0.0}$$
- Build Metadata Ignored in Precedence: Build metadata (appended after
+) provides CI/CD telemetry (git commit hashes, compilation timestamps), but is completely ignored when determining version priority: $$1.0.0\text{+build.1} == 1.0.0\text{+build.2} == 1.0.0$$
Practical Implementation Examples
Python: Full-Spectrum SemVer 2.0.0 Parser & Comparator
The following standalone script parses semantic version strings, enforces SemVer 2.0.0 precedence, and calculates target version bumps:
import re
from typing import Tuple, Optional, List
class SemanticVersion:
SEMVER_REGEX = 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-]+)*))?$'
)
def __init__(self, version_str: str):
match = self.SEMVER_REGEX.match(version_str.strip())
if not match:
raise ValueError(f"Invalid SemVer 2.0.0 string: '{version_str}'")
self.major = int(match.group('major'))
self.minor = int(match.group('minor'))
self.patch = int(match.group('patch'))
self.prerelease = match.group('prerelease')
self.buildmetadata = match.group('buildmetadata')
def bump(self, part: str) -> 'SemanticVersion':
part = part.lower()
if part == 'major':
return SemanticVersion(f"{self.major + 1}.0.0")
elif part == 'minor':
return SemanticVersion(f"{self.major}.{self.minor + 1}.0")
elif part == 'patch':
return SemanticVersion(f"{self.major}.{self.minor}.{self.patch + 1}")
else:
raise ValueError("Part must be 'major', 'minor', or 'patch'")
def _precedence_key(self) -> Tuple:
# Pre-release comparison: None (final release) is higher than any pre-release
if self.prerelease is None:
pre_tuple = (1, ())
else:
# Identifiers separated by dots
identifiers = []
for part in self.prerelease.split('.'):
if part.isdigit():
identifiers.append((0, int(part)))
else:
identifiers.append((1, part))
pre_tuple = (0, tuple(identifiers))
return (self.major, self.minor, self.patch, pre_tuple)
def __lt__(self, other: 'SemanticVersion') -> bool:
return self._precedence_key() < other._precedence_key()
def __eq__(self, other: 'SemanticVersion') -> bool:
# Build metadata is intentionally ignored in equality under SemVer spec §11
return self._precedence_key() == other._precedence_key()
def __repr__(self) -> str:
s = f"{self.major}.{self.minor}.{self.patch}"
if self.prerelease:
s += f"-{self.prerelease}"
if self.buildmetadata:
s += f"+{self.buildmetadata}"
return s
# Verification & Precedence Sorting Demo
versions = [
SemanticVersion("1.0.0"),
SemanticVersion("1.0.0-rc.1"),
SemanticVersion("1.0.0-alpha"),
SemanticVersion("2.0.0"),
SemanticVersion("1.0.0-alpha.1"),
SemanticVersion("1.0.0+build.105")
]
print("Sorted Precedence Order:")
for v in sorted(versions):
print(" ->", v)
TypeScript / JavaScript Implementation
export interface SemVerParts {
major: number;
minor: number;
patch: number;
prerelease?: string;
build?: string;
}
export function bumpVersion(current: string, bumpType: 'major' | 'minor' | 'patch'): string {
const parts = current.split('-')[0].split('.').map(Number);
let [major, minor, patch] = parts;
if (bumpType === 'major') {
major += 1;
minor = 0;
patch = 0;
} else if (bumpType === 'minor') {
minor += 1;
patch = 0;
} else if (bumpType === 'patch') {
patch += 1;
}
return `${major}.${minor}.${patch}`;
}
Critical Edge Cases & Common Versioning Traps
1. The Caret Zero-Major Trap (^0.1.4)
In npm, developers commonly assume that the caret (^) always allows minor upgrades.
However, for pre-1.0 releases, ^0.1.4 resolves only up to < 0.2.0. Under SemVer rules, 0.2.0 is treated as a breaking change. If a library author releases breaking changes in 0.1.5 instead of 0.2.0, consumer applications automatically pull in broken builds.
2. Lexicographical Sorting Bugs in Pre-Releases (alpha.2 vs alpha.10)
Under SemVer 2.0.0 §11.4:
- Identifiers consisting of only digits are compared numerically:
alpha.2 < alpha.10. - Naive string sorting (
alpha.10 < alpha.2alphabetically) treatsalpha.10as older thanalpha.2, causing automated deployment pipelines to downgrade software releases!
3. Mixing SemVer with Calendar Versioning (CalVer)
Projects like Ubuntu (24.04), JetBrains IDEs (2024.1), and Pip (24.0) use Calendar Versioning (CalVer) based on release year and month. Attempting to parse CalVer numbers using strict SemVer libraries causes errors because CalVer releases omit patch numbers or use leading zeros (2024.04), which violate SemVer §2 prohibitions against leading zeros.