JAVA-280 · Lesson 10 of 12 · 23 min

Releases and versioning

▶ Video coming soon A video version of this lesson is on the way.

On Thursday, March 30, Tamsin came to the back room with a question from the other side of the API. Over the summer she would build the booking website's pages against Hamza's API, and she wanted to know how she would find out when it changed. "If you rename a field on a Wednesday, my page breaks on Thursday." Leif added his own question: when an alert fires at night, how does he know which version is running and what changed in it? Both questions have the same answer, a version number that means something, and a release process that writes down what each version contains.

The booking API already had version numbers. Hamza had tagged 1.0.0 on March 1, when its endpoints were settled in Ingrid's security session, then 1.1.0 and 1.2.0 as features arrived. But the numbers had been chosen by feel, and the notes for each were a line in a chat. This lesson makes both systematic.

Semantic versioning

Semantic Versioning, SemVer 2.0.0, gives each part of a MAJOR.MINOR.PATCH version a meaning for the people who depend on the software. Increase the patch number for a backward-compatible bug fix, the minor number for backward-compatible new features, and the major number for any change that breaks existing users. Resetting the smaller numbers to zero when a larger one increases, 1.2.7 is followed by 1.3.0 or 2.0.0. A version can carry a pre-release label after a hyphen, such as 1.4.0-rc.1, which sorts before 1.4.0, and build metadata after a plus sign, which is ignored when comparing.

The version 1.4.0-rc.1+sha.91eca52 with each part labeled: major 1 for breaking changes, minor 4 for new features, patch 0 for fixes, pre-release rc.1 which sorts before 1.4.0, and build metadata after the plus sign which is ignored in comparisons.
The parts of a semantic version.

For a REST API, "breaking" has a concrete meaning, and Tamsin's renamed field is the classic case. Removing or renaming a field, an endpoint or a query parameter, making an optional field required, or changing a status code breaks clients. Adding an optional field, a new endpoint or a new optional parameter does not, provided clients ignore fields they do not know, which the website's generated TypeScript client did. The API's URL version, the v1 in /api/v1, changes only with a major version that clients must migrate to, and JAVA-260's contract check in CI was there to catch accidental breaks.

What each kind of change means for the version.
Change to the booking APIVersion bump
Fix: the last start offered was 15:30 instead of 15:00Patch
Add GET /api/v1/repair-slots/nextMinor
Add an optional notes field to bookingsMinor
Rename customerPhone to phone in the booking bodyMajor (and /api/v2)
Upgrade Spring Boot with no API changePatch
Faster availability report, same responsesPatch

Comparing versions is easy to get wrong. As text, 1.10.0 sorts before 1.9.0, and a pre-release must sort before its release, not after. The example implements SemVer's comparison rules for the cases the booking API uses.

Java Example
import java.util.*;

public class Main {
    record Version(int major, int minor, int patch, String pre) implements Comparable<Version> {
        static Version parse(String s) {
            String core = s.split("\\+")[0];
            String pre = core.contains("-") ? core.substring(core.indexOf('-') + 1) : "";
            String[] n = (pre.isEmpty() ? core : core.substring(0, core.indexOf('-'))).split("\\.");
            return new Version(Integer.parseInt(n[0]), Integer.parseInt(n[1]), Integer.parseInt(n[2]), pre);
        }

        public int compareTo(Version o) {
            int c = Comparator.comparingInt(Version::major).thenComparingInt(Version::minor)
                .thenComparingInt(Version::patch).compare(this, o);
            if (c != 0) return c;
            if (pre.isEmpty() || o.pre.isEmpty()) return Boolean.compare(pre.isEmpty(), o.pre.isEmpty());
            String[] a = pre.split("\\."), b = o.pre.split("\\.");
            for (int i = 0; i < Math.min(a.length, b.length); i++) {
                boolean na = a[i].matches("\\d+"), nb = b[i].matches("\\d+");
                int d = na && nb ? Integer.compare(Integer.parseInt(a[i]), Integer.parseInt(b[i]))
                      : na ? -1 : nb ? 1 : a[i].compareTo(b[i]);
                if (d != 0) return d;
            }
            return Integer.compare(a.length, b.length);
        }

        public String toString() { return major + "." + minor + "." + patch + (pre.isEmpty() ? "" : "-" + pre); }
    }

    public static void main(String[] args) {
        List<String> tags = List.of("1.10.0", "1.2.0", "1.4.0", "1.4.0-rc.2", "1.9.0", "1.4.0-rc.10", "1.4.0-beta", "1.3.0+sha.91eca52");
        System.out.println("as text:    " + new TreeSet<>(tags));
        List<Version> vs = new ArrayList<>(tags.stream().map(Version::parse).toList());
        Collections.sort(vs);
        System.out.println("as SemVer:  " + vs);
    }
}
Output
as text:    [1.10.0, 1.2.0, 1.3.0+sha.91eca52, 1.4.0, 1.4.0-beta, 1.4.0-rc.10, 1.4.0-rc.2, 1.9.0]
as SemVer:  [1.2.0, 1.3.0, 1.4.0-beta, 1.4.0-rc.2, 1.4.0-rc.10, 1.4.0, 1.9.0, 1.10.0]

What this code does

parse drops any build metadata after the plus sign and splits off the pre-release label after the first hyphen. compareTo compares the three numbers as numbers, then puts a version with a pre-release before the same version without one, and compares pre-release parts one by one, numerically when both are digits. Sorted as text, 1.10.0 lands before 1.2.0 and rc.10 before rc.2, which is exactly the kind of bug that deploys the wrong version.

Commit messages that carry the change type

If each commit says what kind of change it is, the next version number can be worked out instead of chosen. Conventional Commits 1.0.0 is a small convention for that: a commit message starts with a type, an optional scope in parentheses, a colon and a description. fix means a bug fix and feat a new feature; other types such as docs, chore, test and refactor do not affect the version. A breaking change is marked with an exclamation mark after the type, or with a footer starting BREAKING CHANGE:. Kofi liked it for a different reason: the history became readable.

Java Example
import java.util.*;

public class Main {
    enum Bump { NONE, PATCH, MINOR, MAJOR }

    static Bump bumpFor(String message) {
        String header = message.lines().findFirst().orElse("");
        if (header.matches("^\\w+(\\([^)]*\\))?!:.*") || message.contains("\nBREAKING CHANGE:")) return Bump.MAJOR;
        if (header.startsWith("feat")) return Bump.MINOR;
        if (header.startsWith("fix")) return Bump.PATCH;
        return Bump.NONE;
    }

    static String next(String current, List<String> commits) {
        Bump b = commits.stream().map(Main::bumpFor).max(Comparator.naturalOrder()).orElse(Bump.NONE);
        int[] v = Arrays.stream(current.split("\\.")).mapToInt(Integer::parseInt).toArray();
        return switch (b) {
            case MAJOR -> (v[0] + 1) + ".0.0";
            case MINOR -> v[0] + "." + (v[1] + 1) + ".0";
            case PATCH -> v[0] + "." + v[1] + "." + (v[2] + 1);
            case NONE -> current + " (no release needed)";
        };
    }

    public static void main(String[] args) {
        System.out.println(next("1.2.0", List.of("docs: describe the release checklist", "chore(ci): cache Gradle dependencies")));
        System.out.println(next("1.2.0", List.of("fix: last start is 15:00, not 15:30", "docs: fix a typo")));
        System.out.println(next("1.2.0", List.of("fix(sms): retry once on 503", "feat(api): add /api/v1/repair-slots/next")));
        System.out.println(next("1.2.0", List.of("feat(api)!: rename customerPhone to phone")));
        System.out.println(next("1.2.0", List.of("refactor: split SlotCalendar\n\nBREAKING CHANGE: slot times are now in UTC")));
    }
}
Output
1.2.0 (no release needed)
1.2.1
1.3.0
2.0.0
2.0.0

What this code does

bumpFor reads the type from the first line of each message and looks for the exclamation mark or the BREAKING CHANGE footer. The release takes the largest bump among its commits, because a release containing one feature and three fixes is a feature release. Commits that only change documentation or the build need no release at all.

Tools such as semantic-release and release-please do exactly this, along with the release notes. For a shop with one developer, Leif suggested keeping the rule but letting Hamza confirm the number by hand, with the computed one as a check.

Tags and the build version

A tag in Git marks one commit with a name. A release is tagged with v and its version, as an annotated tag, which records who made it and when and can carry a message. The build should take its version from the tag, so that the version is written in one place only: Git. git describe gives a name for any commit relative to the latest tag: the tag itself for a tagged commit, or the tag, the number of commits since and the short hash, such as v1.2.0-4-g91eca52, for one in between.

Java Example
import java.util.regex.*;

public class Main {
    static String buildVersion(String describe) {
        Matcher m = Pattern.compile("v(\\d+)\\.(\\d+)\\.(\\d+)(?:-(\\d+)-g([0-9a-f]+))?(-dirty)?").matcher(describe);
        if (!m.matches()) return "0.0.0-SNAPSHOT";
        if (m.group(4) == null && m.group(6) == null) return m.group(1) + "." + m.group(2) + "." + m.group(3);
        int nextPatch = Integer.parseInt(m.group(3)) + 1;
        String base = m.group(1) + "." + m.group(2) + "." + nextPatch + "-SNAPSHOT";
        String meta = m.group(5) != null ? "+" + m.group(4) + ".g" + m.group(5) : "";
        return base + meta + (m.group(6) != null ? (meta.isEmpty() ? "+" : ".") + "dirty" : "");
    }

    public static void main(String[] args) {
        for (String d : new String[] {"v1.2.0", "v1.2.0-4-g91eca52", "v1.2.0-4-g91eca52-dirty", "v1.2.0-dirty", "91eca52"})
            System.out.printf("%-24s -> %s%n", d, buildVersion(d));
    }
}
Output
v1.2.0                   -> 1.2.0
v1.2.0-4-g91eca52        -> 1.2.1-SNAPSHOT+4.g91eca52
v1.2.0-4-g91eca52-dirty  -> 1.2.1-SNAPSHOT+4.g91eca52.dirty
v1.2.0-dirty             -> 1.2.1-SNAPSHOT+dirty
91eca52                  -> 0.0.0-SNAPSHOT

What this code does

A tagged, clean commit gets exactly the tag's version, so a release build is 1.2.0 and nothing else. A commit after the tag becomes a snapshot of the next patch, with the commit count and hash as build metadata, and uncommitted changes add dirty, so such a JAR can never be mistaken for a release. A repository with no tags at all falls back to 0.0.0-SNAPSHOT.

build.gradle.kts (version from Git)
val gitVersion: String = providers.exec {
    commandLine("git", "describe", "--tags", "--dirty", "--match", "v*")
}.standardOutput.asText.get().trim()

version = gitVersion.removePrefix("v").let {
    if (Regex("\\d+\\.\\d+\\.\\d+").matches(it)) it else "${it.substringBefore('-')}-SNAPSHOT"
}

What this code does

providers.exec runs git describe in a way that Gradle's configuration cache understands, and --match v* ignores tags that are not releases. A clean tagged commit gives its version; anything else becomes a snapshot of the tag's version, a simpler rule than the example's. In CI, actions/checkout must fetch tags for this to work, which fetch-depth: 0 does.

Release notes

Tamsin's question needed one more piece: a human-readable list of what changed. A changelog is a file, usually CHANGELOG.md, with a section per version, newest first, grouping changes as added, changed, fixed or removed, the format suggested by Keep a Changelog. The booking API's changelog is also its notice to Tamsin: anything under Changed or Removed is something her pages may need to handle. With conventional commits, a first draft writes itself.

Java Example
import java.util.*;

public class Main {
    public static void main(String[] args) {
        String version = "1.4.0", date = "2028-04-27";
        List<String> commits = List.of(
            "fix: reject bookings on public holidays",
            "feat(api): add /api/v1/repair-slots/next",
            "docs: describe the release checklist",
            "chore(ci): cache Gradle dependencies",
            "feat: limit active bookings to two per phone number");
        Map<String, String> sections = new LinkedHashMap<>();
        sections.put("feat", "Added");
        sections.put("fix", "Fixed");
        Map<String, List<String>> groups = new LinkedHashMap<>();
        for (String c : commits) {
            String type = c.substring(0, c.indexOf(':')).replaceAll("\\(.*\\)|!", "");
            String text = c.substring(c.indexOf(':') + 2);
            if (sections.containsKey(type))
                groups.computeIfAbsent(sections.get(type), k -> new ArrayList<>()).add(text);
        }
        System.out.println("## [" + version + "] - " + date);
        for (String s : sections.values()) {
            if (!groups.containsKey(s)) continue;
            System.out.println("### " + s);
            groups.get(s).forEach(t -> System.out.println("- " + Character.toUpperCase(t.charAt(0)) + t.substring(1)));
        }
    }
}
Output
## [1.4.0] - 2028-04-27
### Added
- Add /api/v1/repair-slots/next
- Limit active bookings to two per phone number
### Fixed
- Reject bookings on public holidays

What this code does

The type is everything before the colon, with any scope and exclamation mark removed, and only features and fixes appear in the notes because documentation and build changes do not concern users. Groups keep the order of the sections map, Added before Fixed, and each line starts with a capital letter. The commits are the ones the booking API's next release was expected to contain after the review in April, and lesson 12 shows how close the guess was.

A release workflow

Leif's release process has one manual step, creating the tag, and everything after it is automatic. Pushing a tag that matches v* starts a workflow that builds and tests that exact commit, pushes the image with the version tag as well as the commit tag, and creates a GitHub release with the notes and the JAR attached. A release cannot be made from a branch, and the same version cannot be released twice, because the tag already exists.

.github/workflows/booking-api-release.yml (draft)
name: booking-api release

on:
  push:
    tags: ["v*"]

permissions:
  contents: write
  packages: write

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0
      - uses: actions/setup-java@v5
        with: { distribution: temurin, java-version: "25" }
      - uses: gradle/actions/setup-gradle@v6
      - run: ./gradlew build
        working-directory: booking-api
      - name: Check the version matches the tag
        run: test "v$(./gradlew -q printVersion)" = "${GITHUB_REF_NAME}"
        working-directory: booking-api
      - id: version
        run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
      - uses: docker/login-action@v4
        with: { registry: ghcr.io, username: "${{ github.actor }}", password: "${{ secrets.GITHUB_TOKEN }}" }
      - uses: docker/build-push-action@v7
        with:
          context: booking-api
          push: true
          tags: |
            ghcr.io/second-gear/booking-api:${{ steps.version.outputs.version }}
            ghcr.io/second-gear/booking-api:sha-${{ github.sha }}
      - run: gh release create "${GITHUB_REF_NAME}" booking-api/build/libs/booking-api-*.jar --notes-file booking-api/release-notes.md
        env: { GH_TOKEN: "${{ secrets.GITHUB_TOKEN }}" }

What this code does

The workflow runs only for tags starting with v, and it needs write permission on contents to create the release and on packages to push the image. The version check fails the release if the build's version and the tag disagree, for instance when a tag was pushed for a commit with uncommitted changes. The gh command-line tool, preinstalled on GitHub's runners, creates the release with the notes file and the JAR.

The step with the id version strips the leading v from the tag name, so the Git tag v1.4.0 produces the image tag 1.4.0, the same form as in lessons 3 and 6. The image, the JAR, the health endpoint and the Compose file then all show the same version number, and only the Git tag carries the v.

Exercises

Try it yourself

Bump a version

Complete bump so that it returns the next version for a bump of major, minor or patch, resetting the smaller numbers to zero. Any pre-release label on the current version is dropped.

public class Main {
    static String bump(String version, String kind) {
        return version;
    }

    public static void main(String[] args) {
        System.out.println(bump("1.2.7", "patch"));
        System.out.println(bump("1.2.7", "minor"));
        System.out.println(bump("1.2.7", "major"));
        System.out.println(bump("1.4.0-rc.2", "patch"));
    }
}

Try it yourself

Newest release

Complete newest so that it returns the highest version among the tags that are releases (no pre-release label), comparing the three numbers numerically. Tags start with v, which is not part of the version. Return none if there is no release.

import java.util.*;

public class Main {
    static String newest(List<String> tags) {
        return tags.get(tags.size() - 1);
    }

    public static void main(String[] args) {
        System.out.println(newest(List.of("v1.2.0", "v1.10.0", "v1.9.3", "v1.11.0-rc.1")));
        System.out.println(newest(List.of("v1.3.0", "v1.4.0-rc.1", "v1.3.1")));
        System.out.println(newest(List.of("v2.0.0-beta")));
    }
}

Tamsin left with a promise she liked: anything she needed to change on her side would appear under Changed or Removed in the changelog, with a major version, before it reached production. Leif left with a rule for the night: the version on the health endpoint, the Git tag and the image tag would always be the same string.

Common mistakes

  • MistakeChoosing version numbers by feel.

    InsteadUse SemVer: patch for fixes, minor for compatible features, major for breaking changes.

  • MistakeSorting versions as text.

    InsteadCompare the numbers numerically and put pre-releases before their release.

  • MistakeWriting the version in the build file and in Git separately.

    InsteadDerive the build's version from the Git tag.

  • MistakeRenaming an API field in a minor release.

    InsteadTreat it as breaking: a major version, a new URL version, and a note under Changed.

  • MistakeBuilding releases from a laptop.

    InsteadPush a tag and let a workflow build, publish and create the release.

Summary and key terms

  • Semantic Versioning 2.0.0 gives MAJOR.MINOR.PATCH a meaning: breaking changes, compatible features and fixes, with pre-release labels sorting before their release and build metadata ignored.
  • For an API, removing or renaming fields or endpoints is breaking, while adding optional ones is not.
  • Conventional Commits 1.0.0 put the change type in each message so that the next version and the release notes can be derived.
  • Releases are annotated Git tags such as v1.4.0, the build takes its version from git describe, and untagged builds become snapshots.
  • A changelog groups changes as added, changed, fixed or removed, and a workflow triggered by a v tag builds, checks, publishes the image and creates the GitHub release.
Semantic Versioning
A versioning scheme where MAJOR.MINOR.PATCH signals breaking changes, features and fixes.
Breaking change
A change that makes existing users or clients stop working.
Pre-release
A version label after a hyphen, such as rc.1, that sorts before the release.
Build metadata
Information after a plus sign in a version, ignored when comparing.
Conventional Commits
A convention for commit messages that start with a type such as feat or fix.
Annotated tag
A Git tag that records its author, date and a message.
git describe
A command naming a commit relative to the latest tag.
Snapshot
A development build that is not a release.
Changelog
A file listing the notable changes in each version.
GitHub release
A page tied to a tag with notes and attached files.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Which part of the version changes for a bug fix?

    Show answer

    The patch number.

  2. Is adding an optional field to a response a breaking change?

    Show answer

    No, provided clients ignore unknown fields.

  3. Which sorts first, 1.4.0-rc.2 or 1.4.0?

    Show answer

    1.4.0-rc.2.

  4. What does a commit message starting feat(api)!: mean?

    Show answer

    A new feature that is a breaking change, so a major version.

  5. What starts the release workflow?

    Show answer

    Pushing a tag that starts with v.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz