Over a million developers have joined DZone.

Why You Need a Git Pre-Commit Hook and Why Most Are Wrong

DZone's Guide to

Why You Need a Git Pre-Commit Hook and Why Most Are Wrong

· Web Dev Zone
Free Resource

Never build auth again! Okta makes it simple to implement authentication, authorization, MFA and more in minutes. Try the free developer API today! 

A pre-commit hook is a piece of code that runs before every commit and determines whether or not the commit should be accepted. Think of it as the gatekeeper to your codebase.

Want to ensure you didn’t accidentally leave any PDBs in your code? Pre-commit hook. Want to make sure your javascript is JSHint approved? Pre-commit hook. Want to guarantee clean, readable PEP8-compliant code? Pre-commit hook. Want to pipe all of the comments in your codebase through Strunk & White? Please don’t.

The pre-commit hook is just an executable file that runs before every commit. If it exits with zero status, the commit is accepted. If it exits with a non-zero status, the commit is rejected. (Note: A pre-commit hook can be bypassed by passing the --no-verify argument.)

Along with the pre-commit hook there are numerous other git hooks that are available: post-commit, post-merge, pre-receive, and others that can be found here.

Why Most Pre-Commit Hooks are Wrong


Be wary of the above’s example as the majority of pre-commit hooks you’ll see on the web are wrong. Most test against whatever files are currently on disk, not what is in the staging area (the files actually being committed).

We avoid this in our hook by stashing all changes that are not part of the staging area before running our checks and then popping the changes afterwards. This is very important because a file could be fine on disk while the changes that are being committed are wrong.

The code below is the pre-commit hook we use at Yipit. Our hook is simply a set of checks to be run against any files that have been modified in this commit. Each check can be configured to include/exclude particular types of files. It is designed for a Django environment, but should be adaptable to other environments with minor changes. Note that you need git 1.7.7+

#!/usr/bin/env python

import os
import re
import subprocess
import sys

modified = re.compile('^(?:M|A)(\s+)(?P<name>.*)')

        'output': 'Checking for pdbs...',
        'command': 'grep -n "import pdb" %s',
        'ignore_files': ['.*pre-commit'],
        'print_filename': True,
        'output': 'Checking for ipdbs...',
        'command': 'grep -n "import ipdb" %s',
        'ignore_files': ['.*pre-commit'],
        'print_filename': True,
        'output': 'Checking for print statements...',
        'command': 'grep -n print %s',
        'match_files': ['.*\.py$'],
        'ignore_files': ['.*migrations.*', '.*management/commands.*', '.*manage.py', '.*/scripts/.*'],
        'print_filename': True,
        'output': 'Checking for console.log()...',
        'command': 'grep -n console.log %s',
        'match_files': ['.*yipit/.*\.js$'],
        'print_filename': True,
        'output': 'Checking for debugger...',
        'command': 'grep -n debugger %s',
        'match_files': ['.*\.js$'],
        'print_filename': True,
       'output': 'Running Jshint...',
       # By default, jshint prints 'Lint Free!' upon success. We want to filter this out.
       'command': 'jshint %s | grep -v "Lint Free!"',
       'match_files': ['.*yipit/.*\.js$'],
       'print_filename': False,
        'output': 'Running Pyflakes...',
        'command': 'pyflakes %s',
        'match_files': ['.*\.py$'],
        'ignore_files': ['.*settings/.*', '.*manage.py', '.*migrations.*', '.*/terrain/.*'],
        'print_filename': False,
        'output': 'Running pep8...',
        'command': 'pep8 -r --ignore=E501,W293 %s',
        'match_files': ['.*\.py$'],
        'ignore_files': ['.*migrations.*'],
        'print_filename': False,
        'output': 'Checking for Sass changes...',
        'command': 'sass --quiet --update %s',
        'match_files': ['.*\.scss$'],
        'print_filename': True,

def matches_file(file_name, match_files):
    return any(re.compile(match_file).match(file_name) for match_file in match_files)

def check_files(files, check):
    result = 0
    print check['output']
    for file_name in files:
        if not 'match_files' in check or matches_file(file_name, check['match_files']):
            if not 'ignore_files' in check or not matches_file(file_name, check['ignore_files']):
                process = subprocess.Popen(check['command'] % file_name, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
                out, err = process.communicate()
                if out or err:
                    if check['print_filename']:
                        prefix = '\t%s:' % file_name
                        prefix = '\t'
                    output_lines = ['%s%s' % (prefix, line) for line in out.splitlines()]
                    print '\n'.join(output_lines)
                    if err:
                        print err
                    result = 1
    return result

def main(all_files):
    # Stash any changes to the working tree that are not going to be committed
    subprocess.call(['git', 'stash', '-u', '--keep-index'], stdout=subprocess.PIPE)
    files = []
    if all_files:
        for root, dirs, file_names in os.walk('.'):
            for file_name in file_names:
                files.append(os.path.join(root, file_name))
        p = subprocess.Popen(['git', 'status', '--porcelain'], stdout=subprocess.PIPE)
        out, err = p.communicate()
        for line in out.splitlines():
            match = modified.match(line)
            if match:
    result = 0
    print 'Running Django Code Validator...'
    return_code = subprocess.call('$VIRTUAL_ENV/bin/python manage.py validate', shell=True)
    result = return_code or result
    for check in CHECKS:
        result = check_files(files, check) or result
    # Unstash changes to the working tree that we had stashed
    subprocess.call(['git', 'reset', '--hard'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    subprocess.call(['git', 'stash', 'pop', '-q'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

if __name__ == '__main__':
    all_files = False
    if len(sys.argv) > 1 and sys.argv[1] == '--all-files':
        all_files = True

To use this hook or a hook that you create yourself, simply copy the file to .git/hooks/pre-commit inside of your project and make sure that it is executable or add in to your git repo and setup a symlink.

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!


Published at DZone with permission of Steve Pulec. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}