Sub topic 2
What a Tag Is and Why You Use One
This chapter assumes you can commit, branch, push and pull, and that you have a GitHub repository you can push to. You should also know that every commit has a unique hash.
A tag is a fixed name for a commit
A tag is a name that points to one commit. Git stores it as a reference, a small entry that maps a name to a commit hash. Branches are references too. The difference is in how they behave.
- A branch moves. When you commit on
main, the namemainadvances to the new commit. - A tag stays.
v1.0.0points to the same commit until someone deliberately changes it.
A tag does not hold a copy of your files. It only labels a commit that already exists.
Why you use one
Commit hashes such as 4f2a9c1 are hard to remember and hard to say aloud. A tag replaces the hash with a name people can use.
- Marking releases.
v1.0.0identifies exactly what you shipped. - Reproducing a state. You can rebuild or debug the code as it was at a release.
- Communicating. Bug reports, changelogs and deployment scripts can refer to a version instead of a hash.
- Driving automation. GitHub Releases and many CI pipelines start from a tag. Later chapters cover both.
Creating a tag
Run these commands in a repository that has at least one commit.
# Tag the commit you are on
git tag v1.0.0
# Confirm which commit the tag points to
git rev-parse v1.0.0
git rev-parse HEAD
# Commit more work, then compare again
git commit --allow-empty -m "Work after the release"
git rev-parse v1.0.0
git rev-parse HEADBefore the new commit, both rev-parse commands print the same hash. After it, HEAD has moved and v1.0.0 has not. That is the difference between a tag and a branch.
Common mistakes
- Treating a tag like a branch. You cannot commit onto a tag. If you check one out, you land on a detached HEAD, which a later chapter covers.
- Expecting tags to travel automatically. A plain
git pushdoes not send tags to the remote. You will push them explicitly in the chapter on sharing tags. - Tagging before the work is final. If you tag a commit and then find a bug, the tag is on the wrong commit. Moving a tag that others have already fetched causes real problems, so check the commit first.
Exercise
You tag the current commit as v2.0.0 and then make three more commits on main. Which commit does v2.0.0 point to now, and which commit does main point to?
Show answer
v2.0.0 still points to the commit you tagged. main points to the newest of the three later commits, because branches move forward with each commit and tags do not.