Configure pre-commit with black, flake8, and pre-commit hooks

To run black code formatter, flake8 linter, as well as other hooks (e.g., pretty-format-json) automatically each time something is committed to a repo:

  1. Install pre-commit on the local computer (in macOS can use brew install pre-commit, in linux can install in a virtualenv using pip install pre-commit)

  2. Add a .pre-commit-config.yaml to the root of the repository:

    repos:
      - repo: https://github.com/pre-commit/pre-commit-hooks
        rev: v3.4.0
        hooks:
          - id: check-json
          - id: pretty-format-json
            args: [--no-sort-keys, --autofix, --no-ensure-ascii ]
    
      - repo: https://github.com/ambv/black
        rev: 20.8b1
        hooks:
          - id: black
            language_version: python3
      - repo: https://gitlab.com/pycqa/flake8
        rev: 3.8.4
        hooks:
          - id: flake8
    
  3. Add a pyproject.toml file for black configuration:

    [tool.black]
    line-length = 88
    include = '\.pyi?$'
    exclude = '''
    /(
        \.git
      | \.hg
      | \.mypy_cache
      | \.tox
      | \.venv
      | _build
      | buck-out
      | build
      | dist
    )/
    '''
    
  4. Add a .flake8 configuration file:

    [flake8]
    ignore = E203, E266, E501, W503, F403, F401
    max-line-length = 88
    max-complexity = 18
    select = B,C,E,F,W,T4,B9
    
  5. Install git hooks in the repository .git/ directory:

    > pre-commit install
    

References

  1. pre-commit (pre-commit.com)
  2. Automate Python workflow using pre-commits: black and flake8 (ljvmiranda921.github.io)
  3. How to setup your project with pre-commit, black, and flake8 (dev.to)
  4. Where does pre-commit install “environments”? (stackoverflow.com)
updatedupdated2021-03-232021-03-23