Git Tag: Sort tags by semantic version / natural order
git tag command lists all tags you have created in your repository. When creating a new version of a project that you are working on, using a command like
npm version major|minor|patch is easier as it takes care of everything. For the rest of the projects, we still run
git tag to quickly lookup the existing tags in the repository, so we can figure out the what the next version number should be.
By default, the
git tag output is sorted alphabetically, and you can end up with lists like this:
v0.0.8 v0.1.0 v0.10.0 v0.10.1 v0.2.0 v0.20.0 <=- The latest release v0.3.0 <=- Not the latest release
It can be a bit daunting to go through the list and find the latest version from the list. I was pleasantly surprised to discover the Git provides a feature to sort tags by version numbers.
You can run the following for the nicely sorted list of tags:
git tag --sort version:refname
This will output a properly sorted list, and the semantically latest version will be at the bottom of the list:
v0.0.8 v0.1.0 v0.2.0 v0.3.0 v0.10.0 v0.10.1 v0.20.0 <=- The latest release
You can get the list in reverse order as well, by prefixing a dash to the command:
git tag --sort -version:refname
Because it's cumbersome to type the sort option every time, you can set this as a global Git configuration. It turns out
tag.sort configuration precisely does that.
git config --global tag.sort -version:refname
From now on, when you type
git tag, you will get a nicely sorted list of all your tags, sorted by their version numbers, and the latest version will be o the top of the list!