#FULL STACK DEVELOPMENT MAR 28 - 2 MIN READ
Create a global GIT hook to check Flake8 before each commit
By Matías Herranz Flake8 is a Python code linter tool. More specifically, it's the wrapper

By Matías Herranz

Flake8 is a Python code linter tool. More specifically, it’s the wrapper which verifies pep8, pyflakes, and circular complexity. Flake8 tends to have a low rate of false positives.

FIRST, LET’S INSTALL FLAKE8:

$ sudo pip install flake8==2.0

Note: It is important to ensure you’ve set the right version when installing Flake8, since there are some versions that are bugged and will prevent the GIT hook from working properly (like the 2.1.0 version).

NOW, LET’S SET UP GLOBAL GIT COMMIT HOOKS:

1. Enable git templates:

$ git config –global init.templatedir ‘~/.git-templates’

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

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.

NOW, LET’S CREATE A GLOBAL GIT PRE-COMMIT HOOK:

#!/usr/bin/env python
import glob
import os
import sys
# git usurbs your bin path for hooks and will always run system python
site_packages = glob.glob(‘%s/lib/*/site-packages’ % os.environ[‘VIRTUAL_ENV’])[0]
sys.path.insert(0, site_packages)
from flake8.run import git_hook
COMPLEXITY = 10
STRICT = True
if __name__ == ‘__main__’:
sys.exit(git_hook(complexity=COMPLEXITY, strict=STRICT))

FINALLY, LET’S TAKE IT FOR A SPIN!
Go to some of your repos and re-initialize them to take the pre-commit hook:

$ git init

Now, edit some of your Python files to introduce some violation (like a >80 columns line, only one blank line between function/class definitions, etc.) and try to commit it:

$ git commit setup.py
setup.py:4:1: E302 expected 2 blank lines, found 0
setup.py:8:1: E302 expected 2 blank lines, found 0

Voilà!

Matias Herranz is as a Python Developer for Santex. He is a Computer Science and Open Source software enthusiast. His professional experience has focused on Python/Django web app development and some incursions in mobile apps for iPhone/Android. He is a team player who enjoys and finds it rewarding to share the things he learns, either through conferences and lectures, or through day-to-day communication with his coworkers.

Read our latest eBook!

Santex’s Ultimate Guide to Development Outsourcing

DOWNLOAD
×
×