(In one of the projects that I'm working on) I suggested starting using git hook to run some validations before committing the changes to GitHub, and the boss said: "Great idea, all yours!"
I wasn't sure if I should be happy or sad because I had to implement the hooks...
I used to work with git hooks, but this was the first time I have to do it from scratch, so I read about the git hooks ( https://git-scm.com/docs/githooks ), and I focused on just one, the pre-commit.
Alright, so the hooks are scripts that run before or after some git action, but this can be a mess if your teammates use a different OS (Windows, Linux, or Mac) because some scripts won't work on Windows (like bash/sh script) or vice versa (like PowerShell scripts).
I had to find another solution, and I remembered that all my teammates have Python installed, and I thought: "Instead of creating our hooks, maybe I could find a python module to manage the hooks" and I found it!.
pre-commit is a framework for managing and maintaining multi-language pre-commit hooks, is easy to install/configure, and has several pre-created hooks.
Installation:
You can use brew or conda, but the best way is with pip:
pip install pre-commit
Configuration:
Create a .pre-commit-config.yaml
in the root folder of your project and read the docs to know how to organize it.
This is an example:
fail_fast: false
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: check-merge-conflict
- id: end-of-file-fixer
- id: trailing-whitespace
When your .pre-commit-config.yaml
is ready then you can set up the git hooks with:
pre-commit install
And that's all, the next time you create a new commit, it will run the pre-commit hooks!!!
PS C:\Users\myProject> git commit -m "testing hooks"
Check for merge conflicts................................................Passed
Fix End of Files.........................................................Failed
- hook id: end-of-file-fixer
- exit code: 1
- files were modified by this hook
Fixing .pre-commit-config.yaml
Trim Trailing Whitespace.................................................Passed
Here is the link to the website: https://pre-commit.com/
And they already have some pre-created hooks, not only for Python, there are also for dockerfile, Javascript, go, JSON, XML, Perl, shell, etc: https://pre-commit.com/hooks.html