How can I automatically be warned if a specific file changes?

greg0ire picture greg0ire · May 30, 2013 · Viewed 8.1k times · Source

I have a php project, and when I pull from another repository and the composer.lock file gets changed, I'm supposed to run composer.phar install --dev. How can git automatically warn me / ask me if I want to run this command? I suppose some sort of hook would do the trick, but how can I get information regarding only what has changed before and after the pull in it?

Answer

mvp picture mvp · May 31, 2013

It depends on what option you use when pulling:

No option : git fetch and git merge are run

You can write your own post-merge git hook:

This hook is invoked by git merge, which happens when a git pull is done on a local repository. The hook takes a single parameter, a status flag specifying whether or not the merge being done was a squash merge. This hook cannot affect the outcome of git merge and is not executed, if the merge failed due to conflicts.

This hook should work for you (save this as executable file .git/hooks/post-merge):

#!/bin/sh

CHANGED=`git diff HEAD@{1} --stat -- $GIT_DIR/../composer.lock | wc -l`
if [ $CHANGED -gt 0 ];
then
    echo "composer.lock has changed!"
    composer.phar install --dev
fi

--rebase : git fetch and git rebase are run

You can write your own post-checkout git hook:

This hook is invoked when a git checkout is run after having updated the worktree. The hook is given three parameters: the ref of the previous HEAD, the ref of the new HEAD and a flag indicating whether the checkout was a branch checkout or a file checkout

This hook should work for you (save this as executable file .git/hooks/post-checkout):

#!/bin/sh

CHANGED=`git diff $1 $2 --stat -- $GIT_DIR/../composer.lock | wc -l`
if [ $CHANGED -gt 0 ];
then
    echo "composer.lock has changed!"
    composer.phar install --dev
fi

UPDATE

Here is my personal set of git hooks.