1

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.

Dave Long
  • 9,569
  • 14
  • 59
  • 89

1 Answers1

3

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.)

user1686
  • 13,155
  • 2
  • 35
  • 54
Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
  • I meant, they are not typeable inside the code-quoting environment, since they themselves delimit these environments, thus `` ... `` does not work as wished. Sorry, should have been more explicit. – Paŭlo Ebermann Feb 22 '11 at 20:15
  • That is exactly what I needed, and I had tested the $() approach, but I didn't realize that the final slash could be outside of quotation marks. Thank you. – Dave Long Feb 22 '11 at 20:22
  • You can also add more quotation marks at the end: '/' works, too. – Paŭlo Ebermann Feb 22 '11 at 20:28
  • Now is it possible to access the commit's id in a pre-commit? That way the file stays under version control with the proper commit id? If not I will just add the commit.git file to my ignore list. – Dave Long Feb 22 '11 at 21:13
  • 2
    The commit-ID is a hash of the state of the tree at the time of the commit, not some random value. So if you in a pre-commit-hook change something of the commited files, the commit-ID would change almost certainly. You would need to break the SHA-1 algorithm to be able to put the SHA-1 code of the commit into the commit itself (or some really long brute-forcing). – Paŭlo Ebermann Feb 22 '11 at 21:16