Git Hooks Tutorial

My public talk about this project at Sberloga:
Git Hooks Is All You Need

1. Git Hooks 101

  1. Init git repo:
mkdir git_repo
cd git_repo

git init
  1. Git hooks are located in .git/hooks folder:
ls -lah .git/hooks
  1. Create executable (chmod +x) pre-commit hooks (path: .git/hooks/pre-commit):
  • bash hook with exit code 0
  • bash hook with exit code 1
  • python hook with exit code 0

Make commit after each step. You'll see different results.

2. Python pre-commit library

  1. Create and activate virtual environment:
python3 -m venv venv
source venv/bin/activate
  1. Install and activate pre-commit library:
pip install pre-commit
pre-commit install
  1. Create pre-commit configuration file .pre-commit-config.yaml.
    Alternatively, you can use local configuration.

  2. Create main.py file.
    Make commit. Pre-commit library will reformat file according to PEP8.
    Remove unused import sys string to get ready-to-commit main.py file.

3. Remote repo

  1. Init empty "remote" repo:
git init --bare ../remote_repo.git
  1. Link local and "remote" repo:
git remote add origin ../remote_repo.git
  1. Create executable (chmod +x) pre-receive hook on "remote" (path: ../remote_repo.git/hooks/pre-receive).
    Make push and see the result.

Reference

Useful links:

  • git hooks intro: link
  • git hooks usage: link
  • pre-commit page: link

Thanks

Thanks to Anastasiya for help with jupyter notebook hooks!