Skip to content

Instantly share code, notes, and snippets.

@stoyanvi
Created July 25, 2014 13:04
Show Gist options
  • Save stoyanvi/61bd5bb57164f5203b55 to your computer and use it in GitHub Desktop.
Save stoyanvi/61bd5bb57164f5203b55 to your computer and use it in GitHub Desktop.
git hook to run a command after `git pull` if a specified file was changed. In this example it's used to run `npm install` if package.json changed and `bower install` if `bower.json` changed. Run `chmod +x post-merge` to make it executable then put it into `.git/hooks/`.

How to create a global git commit hook by Matt Venables

1 Enable git templates (This tells git to copy everything in ~/.git-templates to your per-project .git/ directory when you run git init):

git config --global init.templatedir '~/.git-templates'

2 Create a directory to hold the global hooks:

mkdir -p ~/.git-templates/hooks

3 Write your hooks in ~/.git-templates/hooks. For example, here's a post-commit hook (located in ~/.git-templates/hooks/post-commit):


#!/bin/sh

# Copy last commit hash to clipboard on commit
git log -1 --format=format:%h | pbcopy


# Add other post-commit hooks 

4 Make sure the hook is executable.

chmod a+x ~/.git-templates/hooks/post-commit

5 Re-initialize git in each existing repo you'd like to use this in:

git init

NOTE if you already have a hook defined in your local git repo, this will not overwrite it.

#!/bin/sh
#
# git hook to run a command after `git pull` if a specified file was changed
# Run `chmod a+x post-merge` to make it executable then put it into `.git/hooks/`.
changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"
check_run() {
echo "$changed_files" | grep --quiet "$1" && eval "$2"
}
# In this example it's used to run `npm install` if package.json changed, `bower install` if `bower.json` changed and `bundle install` if `Gemfile` changed.
# `npm install` and `npm prune` if the `package.json` file gets changed
# to update all the nodejs ( grunt ) dependencies deleting the unused packages (not listed into the `package.json` file)
check_run package.json "npm install && npm prune"
# `bower install` and `bower prune` if the `bower.json` file gets changed
# to install all the frontend dependencies removing the unused packages ( not listed into the `bower.json` file )
check_run bower.json "bower install && bower prune"
# `bundle install` if the `Gemfile` file gets changed
check_run Gemfile "bundle install"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment