How To Create A Git Hook To Enforce Usage Of Feature Branches

Posted By Weston Ganger

Heres an example git hook to enforce usage of feature branches

!/usr/bin/env ruby

if ENV["SKIP_GLOBAL_GIT_HOOKS"].to_s == "true"
  exit 0

if ENV['SKIP_BRANCH_CHECK'].to_s != "true"
  git_branch = `git rev-parse --abbrev-ref HEAD`.strip
  restricted_branches = ["master", "main", "release", "production", "prod"]

  if restricted_branches.include?(git_branch)
    git_repo = `basename -s .git $(git config --get remote.origin.url)`.strip
    allowed_repos = ["repo_a", "repo_b"]

    if !allowed_repos.include?(git_repo)
      puts "NOT ALLOWED TO PUSH TO RESTRICTED BRANCHES (#{git_branch}), please use a feature branch instead."
      puts "To skip this check use `SKIP_BRANCH_CHECK=true`"
      exit 1

Also since git hooks are not committed to your repository you can either use one of the following techniques to save this git hook:

  • If you want to share the hook with all team members working on the project, then use the <a href="">.githooks technique</a>
  • If you want to have this hook available to every project you personally work on, then use the global git hooks technique as described below
    • Create a folder within your dotfiles repo for your git hooks and add your git hooks here
    • Add the following line to your .bashrc/.zshrc (recommended) or run manually, [[ -d "$HOME/path/to/your/global_git_hooks_folder" ]] && git config --global core.hooksPath "$HOME/path/to/your/global_git_hooks_folder"
    • Now every project you work on will also include the global hooks from the specified folder

Article Topic:Software Development - Linux

Date:August 24, 2022