How to fix wrong Git Tag date

Erdal TAŞKESENErdal TAŞKESEN
2 min read

You can add a tag to a previous commit in Git using the command git tag TAG_NAME COMMIT_HASH. However, this will update the tag's date, which can cause your repository to become out of chronological order.

To fix this, you can use the following code:

git tag -l | while read -r tag ; do COMMIT_HASH=$(git rev-list -1 $tag) && GIT_COMMITTER_DATE="$(git show $COMMIT_HASH --format=%aD | head -1)" git tag -a -f $tag -m"$(git show $COMMIT_HASH --format=%s | head -1)" $COMMIT_HASH ; done && git push --tags --force

WARNING: This code will delete all your remote tags and recreate them using the commit date and subject line of the tag's associated commit. Note that any messages you have added to the tag will be overwritten by the commit subject line.

# Loop over tags
git tag -l | while read -r tag
do
    # get the commit hash of the current tag
    COMMIT_HASH=$(git rev-list -1 $tag)

    # Get commit date of the tag and override the default tag date by specifying
    # the environment variable `GIT_COMMITTER_DATE`.
    # Note that if you specify the variable on a different line, it will apply
    # to the current environment. This isn't desired as probably don't want your
    # future tags to also have that past date. Of course, when you close shell,
    # the variable will no longer persist.
    # GIT_COMMITTER_DATE="$(git show $COMMIT_HASH --format=%aD | head -1)"

    # Create a new tag using the tag's name and the commit's subject line.
    # git tag -a -f $tag -m"$(git show 4ca668c --format=%s | head -1)" $COMMIT_HASH

    GIT_COMMITTER_DATE="$(git show $COMMIT_HASH --format=%aD | head -1)" git tag -a -f $tag -m"$(git show 4ca668c --format=%s | head -1)" $COMMIT_HASH
done
# Force push tags and overwrite ones on the server with the same name
git push --tags --force

Here is an explanation of what each part of the code does:

  1. The git tag -l command lists all local tags.

  2. The while loop iterates over each tag.

  3. The COMMIT_HASH variable stores the commit hash of the current tag.

  4. The GIT_COMMITTER_DATE environment variable is set to the commit date of the tag, which overrides the default tag date.

  5. The git tag command is used to recreate the tag using the tag name, commit subject line, and commit hash.

  6. The git push command is used to force push the tags to the server, overwriting any tags with the same name.

References

  1. https://stackoverflow.com/a/25939259
0
Subscribe to my newsletter

Read articles from Erdal TAŞKESEN directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Erdal TAŞKESEN
Erdal TAŞKESEN

Hey, y’all 🖖🏽 I am a passionate self-taught developer, open-source advocate, and tech enthusiast with a hands-on approach to problem-solving and an unending thirst for knowledge. Anything and everything classified as technology fascinate me.