Skip to content

Setting Up pre‐commit

Thiago Franco de Moraes edited this page Jun 1, 2024 · 2 revisions

pre-commit is a framework for managing and maintaining pre-commit hooks which are scripts that run when you use git commit. Below are the steps to install pre-commit using both pip and conda, and enable it.

Installation

Using pip

  1. make sure you are using the correct virtual environment and run:

    pip install pre-commit

Using conda

  1. Install pre-commit:

    conda install -c conda-forge pre-commit

    Or you can create a new virutal environment from the environment.yml as it pre-commit is included there:

    conda env create -f environment.yaml

Setting Up pre-commit hooks after installation

  1. Install the hooks:

    Run the following command to install the hooks defined in your configuration file:

    pre-commit install

    This will set up the pre-commit hooks to run automatically on git commit.

  2. Making a Commit:

    After installing pre-commit, the hooks will run automatically every time you make a commit. If any hook fails, the commit will be aborted (as if you didn't commit at all). You need to fix the issues reported by the hooks and try committing again. Fortunately, All hooks currently in the repository are just formatters and linting fixers so you should just check which files where changed using git status, make sure they are ok, add them using git add, and finally git commit again using git commit.

Testing pre-commit

The pre-commit hooks we used uses ruff for formatting and linting. If pre-commit doesn't work make sure that ruff is properly installed in your virtual environment.

  1. you can test if pre-commit has been correctly installed by making an empty commit:
git commit --allow-empty -m "testing"

and you should see the following in your terminal:

image

and then for removing the empty commit you can run git reset --soft HEAD~.

  1. Manually Running Hooks:

    If you want to run the hooks on all files (not just the modified ones), use:

    pre-commit run --all-files

    Or run hooks on just the staged files with:

    pre-commit run

Additional Resources

Now you have pre-commit installed and configured in your project, helping to ensure code quality and consistency by running checks automatically before each commit.