1

Save time with pre-commit

 2 years ago
source link: https://allsyed.com/posts/save-time-with-pre-commit/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
📅 Dec 24, 2020  ·  ☕ 2 min read  ·  ✍️ Syed Dawood
Featured Image

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.

pre-commit sample-config > .pre-commit-config.yaml
# 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.

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.

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK