This page looks best with JavaScript enabled

Save time with pre-commit

 ·  ☕ 2 min read  ·  ✍️ Syed Dawood

Intro

A framework for managing and maintaining multi-language pre-commit hooks.
- pre-commit

Intro doesn’t say much. In plain english, It runs hooks(a piece of code) against files to be committed, before code is committed to a branch, sounds like an over-simplification? well it is.

How is it useful?

Well here is a small list of its uses

  • Enforce rules like not allowing code to be committed with debuggers
  • Run code through formatter
  • Run code through linter
  • Trigger test suite
  • Prevent commit to specific branch or branches
  • Sort and remove un-used imports
  • scan known Vulnerability

Prerequisites

  • Python

Getting started

Installation

pre-commit comes as a python package. use pip to install pre-commit. In case of permission issues, add --user flag.If pip is in the path, python -m can be removed. pre-commit will be installed in $HOME/.local/bin/ when user flag utilized, make sure it is in the path.

python -m pip install pre-commit

Configure

Navigate to any existing project root directory. This is usually the place where .git folder is located.Instead of starting with a blank file, let’s get the boiler-plate from pre-commit itself.

1
pre-commit sample-config > .pre-commit-config.yaml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v3.2.0
    hooks:
    -   id: trailing-whitespace
    -   id: end-of-file-fixer
    -   id: check-yaml
    -   id: check-added-large-files

sample output may be different, depending on the version. There is a huge list of hooks available , that’s not it you can roll your own. It is also language agnostic, see supported languages . Adding an existing hook is a simple copy-paste from hooks page.

After adding required hooks, its time to install these hooks. install with below command.

1
2
3
pre-commit install
# Output
# pre-commit installed at .git/hooks/pre-commit

Use auto update to keep pre-commit up to date. Auto update checks rev, compares with github repo and updates if needed.

1
pre-commit autoupdate

Conclustion

pre-commit is very powerful, and it had made code review process slightly easier for me. No more discussions on what code style to use. However, users can bypass pre-commit check by adding --no-verify flag in git commit command.

Reference

Share on

ALLSYED
WRITTEN BY
Syed Dawood
< frontend | backend | fullstack > Developer