Skip to content

precommit

Patrick Schratz edited this page Dec 25, 2021 · 4 revisions

Introduction

pre-commit is a system library which can be used in R via the R package precommit by Lorenz Walthert (who also created styler).

As the name indicates, it executes a specific set of hook before committing, ensuring clean commits. These hooks can do anything in principle. The R package precommit adds many R-specific hooks, such as using styler to style files before committing or running roxygenize to ensure the man/ files are up-to-date. See the repo-specific .pre-commit-config.yml files for a full list.

These hooks can be executed both locally (i.e. before committing) or during a CI run using the pre-commit-ci service (installed as a GitHub app). The following explains how to use these hooks locally and how to activate them for your repo.

Local execution

To use the precommit hooks defined in a repo's YAML file locally

  1. Install the R package precommit
  2. Install the precommit system library - instructions
  3. Run precommit::use_precommit() to activate the repo to use the hooks
  4. Continue committing as usual

You will notice that before each commit, specific hooks will run and eventually modify files (e.g. when files are not styled according to the mlr styler style.). If this happens, you can review the changes in the git index and stage the changed files again. Redo the commit. Now all hooks should succeed and you've done a clean commit.

CI configuration

To use pre-commit during the CI runs of your package, the GitHub App must be enabled for your repository. Currently this is done selectively per repo and an admin of the mlr-org must do so. Simply ask Patrick if you're interested.

There is a hard timeout of 120s defined for this service, so the installation of all dependencies (which precommit is doing behind the scenes using renv) and the hook execution must finish within this time.

Setting up a new mlr-org repo to use precommit

The easiest way is to copy an already existing config, e.g. from mlr3spatiotempcv. Next, the roxygen hook needs to be changed as it is repo specific. To do so, run precommit::snippet_generate("additional-deps-roxygenize") from the package root and c/p the output into the YAML file, replacing the existing content of the roxygenize hook.

  • If you want to use the hooks locally, run precommit::use_precommit().
  • If you want to only use them during CI, see section CI configuration from above.

Note: If your package depends on local system libraries, precommit-ci will fail for the roxygenize hook as it cannot installs those deps. In this case, you are forced to local execution for this hook. To do so, add the following to the precommit YAML file:

ci:
    skip: [roxygenize]

Troubleshooting

In case a local hook fails and prevents you from committing but you have no time and/or motivation to fix it, you can skip a specific hook for this current commit via SKIP=<hook-id> git commit [..].