Git pre-commit hook

When I got repeated reviews about code not passing flake8 checking bob mentioned about using hooks. It was then a new term to me. After checking a couple of webpages I found it very interesting. I wrote a git pre-commit-hook using shell scripting.My script checks two case

1: Check if the current branch is a master branch.
2: Check for python file for checking python syntax errors

What are git hooks?
git can trigger some import actions before you perform an important function like commit, rebase etc. A pre-commit hook is triggered before a commit occurs. Git hooks are stored in hooks directory of .git

Step 1

cd .git/hooks
vi pre- commit

Step 2: Copy the code


(git diff --cached --name-only

git diff–cached is used to find the difference between latest commit and files added for staging.
–name-only list only names of the that have changed.

(git diff --cached --name-only --diff-filter=ACM | grep -e '\.py$'

This list all the python files.

flake8 $file --ignore=E501

This ignores E501(line too long).

Step3: Make the file executable

chmod +x pre-commit-hook

And that’s it. Now every time when you commit your code, git will run flake8 for you. Also you may not fear about accidentally committing your master branch.

Advertisements