Git Hooks

Hooks currently covered: pre-commit

What are Git Hooks?

Hooks are programs you can place in a hooks directory to trigger actions at certain points in git’s execution. That's it.

  • Hooks that don’t have the executable bit set are ignored.
  • By default the hooks directory is $GIT_DIR/hooks, but that can be changed via the core.hooksPath configuration variable.
  • Before Git invokes a hook, it changes its working directory to either $GIT_DIR in a bare repository or the root of the working tree in a non-bare repository. An exception are hooks triggered during a push which are always executed in $GIT_DIR.

A complete list of Git hooks can be found here .

Pre-Commit Hooks

pre-commit is a framework that allows you to identify simple issues in your code before committing it. You can add different plugins to your pre-commit pipeline. Once your files are committed, they will be checked by these plugins. Unless all checks pass, no code will be committed.

Step 1:

To install pre-commit and some associated plugins, type:

pip3 install pre-commit # the pre-commit framework
pip3 install black # formats code automatically for PEP8
pip3 install flake8 # checks various PEP8 issues not covered by black
pip3 install isort # sorts imported libraries alphabetically into sections
pip3 install interrogate  # checks codebase for missing docstrings

Any of these plugins can be run manually by

<plugin-name> <file-name>

Step 2:

Add pre-commit configs to the repo in the .pre-commit-config.yaml file:

repos:
-   repo: https://github.com/ambv/black
    rev: 20.8b1
    hooks:
    - id: black
-   repo: https://gitlab.com/pycqa/flake8
    rev: 3.8.4
    hooks:
    - id: flake8
-   repo: https://github.com/timothycrosley/isort
    rev: 5.7.0
    hooks:
    -   id: isort
-   repo: https://github.com/econchick/interrogate
    rev: 1.4.0  
    hooks:
    - id: interrogate
      args: [-vv, -i, --fail-under=80]

Step 3:

Add pre-commit to git hooks:

pre-commit install

This gives:

pre-commit installed at .git/hooks/pre-commit

Now these plugins will run whenever code is committed. To skip a commit, use the --no-verify flag with the commit command.

References: