Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git hooks bash -- getting the commit message

Tags:

git

bash

I am writing a git hook, to run on a commit to the main branch. I need it to parse and look for some text in the the commit message. How do I reference the commit message in my bash script?

Also I would like to know how to run the hook only on commits to the main branch. so developers can quash there local commits and commit to the main branch when they have fixed a bug or something.

Please and thank you.

like image 204
myusuf3 Avatar asked Jul 23 '10 18:07

myusuf3


2 Answers

With following command:

cat $1

will print your commit message in commit-msg

like image 111
dada Avatar answered Nov 11 '22 05:11

dada


The answer depends slightly on what you're trying to do with the commit message. There are three hooks you could be asking about:

  • prepare-commit-msg is run immediately after the default message is prepared, before the user edits it. The first argument is the name of the file with the commit message. (The second argument indicates where the message came from.)

  • commit-msg is run after the commit message is edited/finalized, but before the commit takes place. If you want to fail the commit if the user's commit message is bad, or to modify the message, you want this, and the single argument is the name of the file with the commit message.

  • post-commit is run after the commit. It has no arguments, but you can of course get the message from git log -n 1 HEAD (probably with --format=format:%s%n%b or some such). If all you want to do is look for something in the message, and notify based on it, you should use this.

All of this material is taken from the githooks manpage

As for running it only on the main branch, all you need is something like:

if [ "$(git symbolic-ref HEAD)" == "refs/head/master" ]; then
    # do your stuff
fi
like image 37
Cascabel Avatar answered Nov 11 '22 06:11

Cascabel