Using Pre-commit to automate tasks

2020-05-14
Tools



pre_commit

Table of Contents

1. What is pre-commit

With pre-commit you can automate some repetitive tasks before doing a commit on a git repository. It is useful for identifying simple issues before submission to code review.

For example with pre-commit you can point out issues in code such as missing semicolons, trailing whitespace, and debug statements.

Pre-commit can work with any development language even though is a python package.

2. Installation

To install you can simply run:

pip install pre-commit

3. Configuration

Once you have the package installed you need the file .pre-commit-config.yaml with the hooks you need.

As an example you can use:

.pre-commit-config.yaml
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v2.3.0
    hooks:
    -   id: check-yaml
    -   id: end-of-file-fixer
    -   id: trailing-whitespace
-   repo: https://github.com/psf/black
    rev: 19.3b0
    hooks:
    -   id: black

Once you are in a repository that has the .pre-commit-config.yaml file you can install the hooks with:

pre-commit install

4. Usage

By default pre-commit will run only on the stagged files. You can check all the files the first time you install it with:

pre-commit run --all-files

After that each time you try to do a commit pre-commit will run all hooks and will prevent you from commiting simple issues.

5. Updating hooks

You can update all pre-commit hooks with:

pre-commit autoupdate

6. Continuous integration (CI)

It is a good idea to run pre-commit on your CI to check that nobody is pushing code with errors.

You can do it with:

pre-commit run --all-files

If you want to only run it on the files that have changed just do:

pre-commit run --from-ref origin.HEAD --to-ref HEAD

7. Useful hooks

There are some default hooks defined here.

Some that I find really useful are:

You can add them with the following code:

.pre-commit-config.yaml
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v2.3.0
    hooks:
    -   id: check-merge-conflict
    -   id: check-json
    -   id: check-toml
    -   id: check-yaml
    -   id: no-commit-to-branch