code-branchGit hook

Run commands automatically when using Git commands

When I work on a Flutter project with a team, I want clean code before every push. So I use Git hook to run checks automatically when we run Git commands.

Main idea:

  • Stop errors early before code goes to remote.

  • Reduce errors from forgetting analyze or tests.

  • Help new teammates follow the same flow.

Step 1: Create .githooks folder

mkdir -p .githooks

Step 2: Create pre-push file

Goal in this example: always run fvm flutter analyze before push.

Create file:

.githooks/pre-push

Content:

#!/usr/bin/env bash

# Flutter Analyzer
printf "\e[33;1m%s\e[0m\n" '=== Running Flutter analyzer ==='

# Undo the stash of the files
pop_stash_files () {
    if [ -n "$hasChanges" ]; then
        printf "\e[33;1m%s\e[0m\n" '=== Applying git stash changes ==='
        git stash pop
    fi
}

fvm flutter analyze
if [ $? -ne 0 ]; then
  printf "\e[31;1m%s\e[0m\n" '=== Flutter analyzer error ==='
  pop_stash_files
  exit 1
fi

printf "\e[33;1m%s\e[0m\n" 'Finished running Flutter analyzer'

Step 3: Activate Git hook

Run:

Combine with Make to group setup commands

You can group Git hook setup commands in one Makefile target so your team can run it quickly.

Example:

If you want full Make details, check this article:

terminalMakechevron-right

How it works

Git hook works by hook file name. If the file name is correct, Git will detect it and run it at the right time.

Common hook file names:

Example:

  • pre-commit runs before git commit

  • pre-push runs before git push

How to disable

If you want to skip hook one time:

If you want to disable project hook path:

Update Git hook in project

When you update scripts in .githooks, just commit it. Then the team can pull and run setup-project (or activation commands) to use the new hooks.

Buy Me a Coffeearrow-up-right | Support Me on Ko-fiarrow-up-right

Last updated