githashtagssha1

What is the format of a git tag object and how to calculate its SHA?


I am familiar with how Git creates SHA1 hashes for files (blobs), but not how they are created for tag objects. I assume they are, if I create an annotated tag, but what is the recipe? And how might I replicate it outside of Git (e.g., in Perl or Python)?


Solution

  • The pattern is basically:

    sha1("tag " + datasize + "\0" + data)
    

    Where data is the output of git cat-file. One can produce this by piping that output to git-hash-object like so:

    git cat-file tag v0.30 | git hash-object -t tag --stdin
    

    And the equivalent a perl one-liner is:

    git cat-file tag v0.30 | perl -MDigest::SHA1 -E '$/=undef;$_=<>;say Digest::SHA1->new->add("tag ".length()."\0".$_)->hex digest'
    

    It seems that one can do this same thing with any of the types objects simply by replacing "tag " with the proper object name: "blob ", "tree ", or "commit ".