Automating the boring stuff with Pre-Commit¶
Pre-commit runs scripts to check for simple issues before changes are committed. It is able to automatically fix small issues such as trailing whitespace and empty lines at the end of a file.
Configuring¶
Pre-commit uses a configuration file named .pre-commit-config.yaml
, which lists the hooks that pre-commit should call when it is run. A basic configuration can be obtained from pre-commit itself by running:
Result
Using what you've learnt earlier, we can redirect this output to a file named .pre-commit-config.yaml
. I'll let you try to remember the command, if you can't you can expand the box below.
For Pre-Commit to run automatically during commits, it has to be installed - this downloads the hooks and installs them under the .git
directory. To install the git hook scripts run:
Now Pre-commit should automatically run on git commit
or cz c
!
If Pre-commit is being added to an existing project or if new hooks have been added, you can run Pre-commit against all files using pre-commit run --all-files
. Since we just added it to your repository, let's go ahead and run the command:
Caution
Pre-commit will only run on changed files when called from a git hook! Therefore, it is recommended to use pre-commit run --all-files
after adding new hooks.
Hooks¶
Depending on the purpose of the repository, there are additional hooks that you will want to add to the config file. Since we just learnt about Commitizen, let's add that as the first additional hook. Open up the .pre-commit-config.yaml
file and append the following:
Commitizen hook config
Other useful hooks for pre-commit¶
Further information on the hook mappings is found here.
Next step¶
With Pre-Commit successfully added to your repository, you are ready to continue on to GitHub - Part 2!