TestEngineering/Web/Automation/Flake8 Pre Commit Hook
Contents
Introduction
The style guide specifies that all Python code adheres to PEP8. To prevent committing code that does not pass PEP8, follow these steps to installing a pre-commit to run staged files using the flake8 checker. For further assistance on this pre-commit hook please refer the the official documentation.
Installation
Install flake8 into your global site packages:
sudo pip install pep8
Change directory to your git repository:
cd ~/workspace/mygitrepo
Remove any existing pre-commit hooks:
rm .git/hooks/pre-commit
Install the pre-commit hook:
flake8 --install-hook
Git Template
You can add this hook to the git template, which means it will be active for all freshly initialised git repositories (unless they already contain a pre-commit hook):
cd ~/workspace/mygitrepo git config --global init.templatedir ~/.git_template mkdir ~/.git_template/hooks cp .git/hooks/pre-commit ~/.git_template/hooks/
Usage
Once installed, the pre-commit hook will be run whenever you attempt to commit changes to your local repository. Here's an example of it in action:
git checkout -b TestFlake8 echo "import os; # comment" > flake8-warnings.py git add flake8-warnings.py git commit -m 'my commit' .../flake8-warnings.py:1:1: F401 'os' imported but unused .../flake8-warnings.py:1:10: E703 statement ends with a semicolon .../flake8-warnings.py:1:11: E261 at least two spaces before inline comment [TestFlake8 ...] my commit 1 file changed, 1 insertion(+) create mode 100644 flake8-warnings.py
Note that by default the warnings are displayed but the commit is still allowed.
Running the Hook
To run the hook directly instead of attempting a commit:
./.git/hooks/pre-commit
Preventing Commits
To abort a commit if errors are found:
export FLAKE8_STRICT=true
You may want to add this to your default profile.
Ignoring Warnings
To ignore certain warnings:
export FLAKE8_IGNORE=E501
You may want to add this to your default profile.