Introducing pre-commit hooks
I recently became aware of the open-source project: pre-commit, which is "A framework for managing and maintaining multi-language pre-commit hooks."
The key feature of pre-commit is that it creates an execution environment for itself in order to enable running hooks without messing with (or creating conflicts with) your development or operating environment.
pre-commit uses a configuration file (
.pre-commit-config.yaml) to determine which
hooks to run and how to handle them. These hooks can come from public or private
repositories and there's a pretty solid mechanism for dealing with dependencies.
I'd discovered the pre-commit project when looking at another open-source project that used it to maintain a level of code consistency. To carry this out, pre-commit can be used to update files during the commit phase to bring those files into alignment with the standards (and verify correctness, run lint programs, etc.)
Pre-commit can be installed on macOS using homebrew with
# brew install pre-commit
Once installed, you can add a pre-commit configuration by creating a
file and putting appropriate contents in it. Here's an example config that cleans up yaml,
end of file, and trailing whitespace:
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
Install the git hook scripts with the install command:
# pre-commit install
And now give it a shot by running the command against all of your files:
# pre-commit run -a
It's not necessary to use
pre-commit run, since the whole point of the pre-commit hooks
is that they run before code is committed. However, if you make a change to your pre-commit
configuration and want to bring the older content into line, you can use
pre-commit run to
clean up existing code to the new standards.