Tuesday, July 8, 2014

Git - post commit hook

Git Hooks is powerful tool for customizing Git. In this post we created custom post-commit hook, that send email after every new commit.


Client side hooks

  • pre-commit is called before a commit occurs.
  • prepare-commit-msg lets you edit the default message before the editor is fired up; it's useful in automated commits to add some context.
  • commit-msg is the last step where you can interrupt a commit.
  • post-commit is executed after a commit is completed, for notification purposes.
  • post-checkout you can use it to set up your working directory properly for your project environment.
  • post-merge you can use it to restore data in the working tree that Git can’t track, such as permissions data.


Server side hooks

  • pre-receive can be used to check and interrupt the receival of the new commits, if it is the case.
  • post-receive notifies that commits have been published on this repository.
  • update is a version of pre-receive that is run once per each different branch.
  • post-update is a notification activated after all references have been updated; the default hook updates some metadata to let the repository be published via HTTP.


For detailed description and other not mentioned hooks go to git documentation.


There are already published some post-receive hook for sending email after push new data to server (1, 2, 3).  


Send emails after commit on the client side is not typical use case. On Linux servers we let store the /etc in a Git. After changing the configuration we commit changes to ( for the server local ) git repository. After every configuration changing we want to notify the other administrators. We use the following post-commit hook:

#!/bin/bash
###
# This hook sends email after git commit.
# It does not send email to the author of the commit.
### SETTING
RECIPIENTS=("admin1@example.com" "admin2@example.com" "admin3@example.com" "admin4@example.com")
SUBJECT="git: SUBJECT"
MESSAGE=$(git log -1 -p)
AUTHOR=$(git log -1 --format="%aE")
### FUNCTIONS
# Get index of value in array or return -1
function indexOf() {
index=0
while [ "$index" -lt "${#RECIPIENTS[@]}" ]; do
if [ "${RECIPIENTS[$index]}" = "$1" ]; then
echo $index
return
fi
let "index++"
done
echo -1
}
# join values in array
function join {
(
IFS=",";
echo "${RECIPIENTS[@]}";
)
}
### MAIN
idx=$(indexOf $AUTHOR)
if [ "$idx" != -1 ];
then
# remove author´s email
unset RECIPIENTS["idx"]
fi
if [ ${#RECIPIENTS[@]} != 0 ];
then
echo "post-commit: send email to $(join)";
mail -s "$SUBJECT" "$(join)" <<< "$MESSAGE"
fi
view raw gistfile1.txt hosted with ❤ by GitHub


After copy a new post-commit file to .git/hooks don’t remember reinit git:
#git init

No comments:

Post a Comment