Skip to content

Instantly share code, notes, and snippets.

@suncle1993
Created October 23, 2020 08:10
Show Gist options
  • Select an option

  • Save suncle1993/a29c407f21b6b1b4ad882272e4f99c2f to your computer and use it in GitHub Desktop.

Select an option

Save suncle1993/a29c407f21b6b1b4ad882272e4f99c2f to your computer and use it in GitHub Desktop.

Revisions

  1. suncle1993 created this gist Oct 23, 2020.
    88 changes: 88 additions & 0 deletions forbid-master.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,88 @@
    #!/usr/bin/env bash
    set -e

    MIN_GIT_VERSION="2.9"
    HOOKS_DIR="$HOME/.git-hooks"

    function checkGitVersion() {
    # check if git is installed
    if ! command -v git &>/dev/null; then
    echo "git could not be found"
    exit 1
    else
    echo "git has been installed"
    fi

    # check if the git version is greater than v2.9
    # git core.hooksPath supported from v2.9
    if (
    echo a version ${MIN_GIT_VERSION}
    git version
    ) | sort -Vk3 | tail -1 | grep -q git; then
    echo "git version qualify"
    else
    echo "git version must be greater than v2.9. please upgrade now!"
    exit 1
    fi
    }

    function createHooksDir() {
    if [ ! -d "$HOOKS_DIR" ]; then
    mkdir -p "$HOOKS_DIR"
    echo "hooks dir has been created"
    else
    echo "hooks dir exists"
    fi
    }

    function generatePreCommit() {
    cat <<'EOF' >"$HOOKS_DIR/pre-commit"
    #!/bin/bash
    protected_branch='master'
    current_branch=$(git rev-parse --symbolic --abbrev-ref HEAD)
    if [ "$protected_branch" == "$current_branch" ]; then
    echo "git hooks: Do not commit to $current_branch branch"
    exit 1
    fi
    exit 0
    EOF

    chmod +x "$HOOKS_DIR/pre-commit"
    }

    function generatePrePush() {
    cat <<'EOF' >"$HOOKS_DIR/pre-push"
    #!/bin/bash
    protected_branch='master'
    remote_branch_prefix="refs/heads/"
    protected_remote_branch=$remote_branch_prefix$protected_branch
    while read local_ref local_sha remote_ref remote_sha
    do
    if [ "$protected_remote_branch" == "$remote_ref" ]; then
    echo " git hooks: Do not commit to $protected_branch branch"
    exit 1
    fi
    done
    exit 0
    EOF

    chmod +x "$HOOKS_DIR/pre-push"
    }

    function configGitHooksPath() {
    git config --global core.hookspath "$HOOKS_DIR"
    }

    checkGitVersion
    createHooksDir
    generatePreCommit
    generatePrePush
    configGitHooksPath

    echo "forbid master commit and push done"