Automatically commit pre-processed files with git pre-commit hooks

A quick tip for anyone who uses pre-processing tools in their asset or production pipeline and needs to commit those.

If you find yourself typing gulp --production or any sort of commands every time before committing, it might be worth your while to make it part of the committing process itself, through the use of git hooks. Git hooks are scripts that are run when certain actions occur, such as pre-commit (before commit), commit-msg (commit message), etc.

In this case we’re using it to run our asset pipeline before every commit. To do that, add a pre-commit script to the .git/hooks folder. This is what I’m using.

#!/bin/sh

# Minify production JS and CSS 
gulp --gulpfile site/gulpfile.js --production

# Add production files 
git add ./public_html/js ./public_html/css

Remember to make this executable with chmod +x git-commit.

When you next run git commit, you may notice the files do not appear in the commit message. Don’t panic - your git hook is working fine. It only appears this way because the message was generated before the pre-commit hook is ran. The files added in the hook will be committed. I have tested this with git 2.7.4, and if you are paranoid, you can test it out yourself using the same method I have -

  1. Create a new folder and initialize an empty git repo

    $ mkdir test 
    $ cd test 
    $ git init 
    
  2. Create a file and add it to the repo

    $ touch test-add 
    $ git add test-add 
    
  3. Add a pre-commit hook. Remember to chmod +x it.

    #!/bin/sh
    echo 'Running pre-commit hook' 
    touch test-hook
    git add test-hook
    
  4. Commit and note the files the commit message says will be committed. Enter something, exit and note that both files have in fact been committed

    $ git commit 
    Running pre-commit hook
    [master (root-commit) ec3948e] Hello world
     2 files changed, 0 insertions(+), 0 deletions(-)
     create mode 100644 test-add
     create mode 100644 test-hook