Git能否像Mercurial一样将标签作为提交记录创建?
Great question! The difference in how Git and Mercurial handle tags is a common point of confusion when switching between the two. Let’s break down why they behave differently, then walk through ways to make Git act more like Mercurial for tag creation.
Why the Difference?
Mercurial stores tags in a .hgtags file in your repository. Every time you add a tag, Mercurial automatically updates this file and creates a new commit to track the change—this is why you see a commit for each tag.
Git, by contrast, has two types of tags:
- Lightweight tags: Simple pointers to a commit (no extra metadata, no associated commit record).
- Annotated tags: Create a separate tag object with metadata (author, message), but this object isn’t a regular commit in your branch history.
Neither of these default behaviors creates a visible commit in your main branch history like Mercurial does—but we can fix that.
Solution 1: Simulate Mercurial’s .hgtags Approach
You can replicate Mercurial’s behavior by maintaining a tag-tracking file in your Git repo, then committing changes to it whenever you add a tag.
- Create a file (e.g.,
.gittags) in your repo root to track tags. This will work just like Mercurial’s.hgtags. - Use a simple script or manual steps to update this file, commit the change, then create your tag:
# Replace these with your tag name and message TAG_NAME="v1.0.0" TAG_MESSAGE="Release version 1.0.0" # Add the current commit hash and tag to the tracking file echo "$(git rev-parse HEAD) $TAG_NAME" >> .gittags # Commit the updated tag file git add .gittags git commit -m "Add tag $TAG_NAME" # Create an annotated tag (optional but recommended for metadata) git tag -a "$TAG_NAME" -m "$TAG_MESSAGE"
This will create a new commit in your branch history (for the .gittags update) just like Mercurial does.
Solution 2: Create an Empty Commit for the Tag
If you don’t want a separate tag file, you can create an empty commit specifically to associate with your tag. This creates a visible commit in your history for the tag action:
# Replace with your tag details TAG_NAME="v1.0.0" TAG_MESSAGE="Release version 1.0.0" # Create an empty commit with your tag message git commit --allow-empty -m "Tag: $TAG_NAME - $TAG_MESSAGE" # Tag the new empty commit git tag "$TAG_NAME"
This commit will show up in your branch history, making it clear when the tag was added—just like Mercurial’s tag commits.
Pushing Tags Automatically
You mentioned needing to check a checkbox in IntelliJ IDEA to push tags. To make this easier:
- Use
git push --tagson the command line to push all local tags to the remote. - Or, configure Git to automatically push tags when you push your branch:
git config --global push.followTags true
This setting tells Git to push any annotated tags that are associated with commits you’re pushing.
内容的提问来源于stack exchange,提问作者Radek Anuszewski

