Git Post Commit Hook Getting Commit Number

1.2k views Asked by At

I am working on having my post-commit hook change a file to have the commit number, so that my application can use that in error handling.

I was able to build the perl script to change the file, but I was wondering how to get the commit id from the hook. Currently my hook looks like this:

#!/bin/sh
#
# An example hook script that is called after a successful
# commit is made.
#
# To enable this hook, rename this file to "post-commit".

#: Nothing
perl -pi -e 's/[A-Za-z0-9+]$/commit-number/' ../../config/commit.git

I would like the commit-number to be some sort of variable holding the commit id.

Edit: I figured out that git rev-parse HEAD will generate the HEAD commit which is what I need, but I don't know how to use that in the command.

1

There are 1 answers

5
Paŭlo Ebermann On BEST ANSWER

You can use the output of a command as a String with $(...) or backticks `...`. Thus, your script could look like this:

 perl -pi -e 's/[A-Za-z0-9+]$/'$( git rev-parse HEAD )/ ../../config/commit.git

or

 perl -pi -e 's/[A-Za-z0-9+]$/'` git rev-parse HEAD `/ ../../config/commit.git

(I prefer the first, since it better nests and is more readable. And it is better typeable on Stackexchange.)

By the way, are you sure your regex is correct? Now it replaces the last character, if it is an alphanumeric character or a +, with the last commit ID. Maybe the + should be after the ]? (And you could use s/[a-f0-9]+/ if you only want to match git-commit-IDs - there is no upper-case, and nothing after f.)