- Install pre-commit: pip install pre-commit
- Add pre-commit to requirements.txt (or requirements-dev.txt)
- Define .pre-commit-config.yaml with the hooks you want to include
- Execute pre-commit install to install git hooks in your .git/ directory
The YAML file configures the sources where the hooks will be taken from. In our case, flake8’s already been included in this framework so we just need to specify its id. On the other hand, we need to define where to source black using few lines of code. Below is a sample .pre-commit-config.yaml file that I use in my project:
repos:
- repo: https://github.com/psf/black
rev: stable
hooks:
- id: black
language_version: python3.6
- repo: https://gitlab.com/pycqa/flake8
rev: 3.7.9
hooks:
- id: flake8
These are my opinions on how to format my Python code:
- Unlike in PEP8, code length is 120 characters, not 80. Because we use 1080p monitors.
- Use of double-quotes than single-quotes in strings.
- If there are many function args, each arg will be wrapped per line.
[tool.black]
line-length = 120
include = '\.pyi?$'
exclude = '''
/(
\.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
)/
'''
Alternative to black is autopep8.
In order for black to work nicely with flake8 (or prevent it from spewing out various errors and warnings), we need to list down some error codes to ignore. Feel free to change the ignore list.
You can check my .flake8 configuration below:
[flake8]
ignore = E203, E266, E501, W503, F403, F401
max-line-length = 79
max-complexity = 18
select = B,C,E,F,W,T4,B9
@todo
Needs PHP8.1 and Composer
composer require --dev phpstan/phpstan
composer require --dev squizlabs/php_codesniffer
or via compose.json
{
"require-dev":{
"phpstan/phpstan": "^1.3",
"squizlabs/php_codesniffer": "^3.6"
}
}
Open .git/hooks/pre-commit
file:
#!/usr/bin/env bash
function __run() #(step, name, cmd)
{
local color output exitcode
printf "[%s] %-20s" "$1" "$2"
output=$(eval "$3" 2>&1)
exitcode=$?
if [[ 0 == $exitcode || 130 == $exitcode ]]; then
echo -e "OK!"
else
echo -e "Not OK!\n\n$output"
exit 1
fi
}
modified="git diff --diff-filter=M --name-only --cached | grep \".php$\""
ignore="resources/lang,resources/views,bootstrap/helpers,database/migrations,bin"
phpcs="vendor/bin/phpcs --report=code --colors --report-width=80 --standard=PSR2 --ignore=${ignore}"
__run "1/3" "php lint" "${modified} | xargs -r php -l"
__run "2/3" "code sniffer" "${modified} | xargs -r ${phpcs}"
__run "3/3" "phpstan" "${modified} | xargs -r vendor/bin/phpstan analyse"