Skip to content

Instantly share code, notes, and snippets.

@withakay
Created January 29, 2024 12:06

Revisions

  1. withakay created this gist Jan 29, 2024.
    43 changes: 43 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    #!/bin/bash

    # Setup:
    # Assuming you don't alread have a global githooks dir
    #
    # mkdir -p ~/.githooks/
    #
    # Save this script to the above path.
    # Make a shell script called `pre-commit` in the above path (touch ~/.githooks/pre-commit).
    # Edit pre-commit script sp it calls this script from it e.g.
    #
    # ``` pre-commit
    # #!/bin/bash
    # bash ~/.githooks/pre-commit_commit-to-main-guard.sh
    # ```
    #
    # Configure git
    #
    # git config --global core.hooksPath ~/.githooks

    protected_branches=("master" "main")
    current_branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null)"

    # Check if git command is available and if we are in a git repository
    if [ $? -ne 0 ]; then
    echo "Error: git command failed or not in a git repository."
    exit 1
    fi

    # Check if the current branch is a protected branch
    if echo "${protected_branches[@]}" | grep -wq "$current_branch"; then
    echo "You are about to commit to $current_branch. Are you sure? [y/n]"
    read -p "" -n 1 -r yn
    echo
    if [[ ! $yn =~ ^[Yy]$ ]]; then
    echo "Commit aborted."
    exit 1
    fi
    else
    # Not a protected branch, proceed normally
    exit 0
    fi