git,

Git 101: tags

Oct 30, 2022 · 3 mins read · Post a comment

Git tags is a Git feature that allows us to tag certain commits. Basically, it’s a Git ref that points to and labels commits wherefrom we want to release our software. You can think of it as a commit checkpoint as well. The tag versioning is usually done using the popular Semantic Versioning (v.X.Y.Z) with X being the major version, Y minor and Z patch version, for instance v1.0.0. Let’s explore it further.

Prerequisites

  • Git

Solution

Create tag:

git tag v1.0.1

This will create a tag from whatever commit current HEAD points to.

annotated and lightweight tags

There are two types of tags: annotated and lightweight, with the latter one being the default one. Both are kept under the .git/refs/tags/ directory.

Annotated tags are storing additional metadata such as: email, date and author name, release notes. They represent as a full object in Git and can be signed and verified with GPG too. To create an annotated tag, run:

git tag -a v1.0.2 -m "Version release v.1.0.2"

Where lightweight tags are being more as bookmarks including name and pointer to the commit they are referencing to. Lightweight tags don’t include -a (annotate), -m (message) or -s (sign) flags.

listing and sorting tags

To list tags, simply run:

git tag -l

If you want to include the tag messages, run:

git tag -ln

List tags starting with version v2:

git tag -l "v2.*"

To list remote tags, run:

git ls-remote --tags origin

Sort tags by latest created:

git tag -l --sort=committerdate

Sort tags by name:

git tag -l --sort=refname

tagging commits

To tag a specific commit, run:

git tag -a v1.0.3 <commit-ID>

With commit ID being the short 8 character SHA-1 hash, for example: 288t815.

retagging

If you try to create a tag with same version as an already created one, you will get the following error:

fatal: tag 'v1.0.4' already exists

So, just add the -f flag.

git tag -f v1.0.4

fetching tags

To fetch tags, run:

git fetch --prune --all --tags

pushing tags

Push a single tag:

git push v1.0.5

Push all tags:

git push --tags

removing local and remote tags

Delete tag locally:

git tag -d v1.0.6

Delete tag from a remote repository:

git push --delete v1.0.7

A much safer alternative preventing accidental branch with the same name as the tag removal, would be to specify the full ref path. For instance:

git push origin :refs/tags/tagname

checking out tags

Checkout a tag resulting in a detached HEAD state, run:

git checkout v1.0.8

latest tag associated with the current checked out branch

git describe

show tag’s data

If you want to show more tag details including commit message, diff and what not, run:

git show v1.0.9

Conclusion

To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.

git