Created
October 23, 2020 08:10
-
-
Save suncle1993/a29c407f21b6b1b4ad882272e4f99c2f to your computer and use it in GitHub Desktop.
一键配置在master上禁止commit和push操作
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment