#!/bin/sh
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
在master分支上Commit时提示
#!/bin/sh
protected_branch='master'
current_branch=$(git rev-parse --symbolic --abbrev-ref HEAD)
if [ "$protected_branch" == "$current_branch" ]; then
read -p "You're about to commit to master, is that what you intended? [y|n] " -n 1 -r </dev/tty
if echo "$REPLY" | grep -E '^[Yy]$' >/dev/null; then
exit 0 # commit will execute
exit 1 # commit will not execute
fi
禁止推送到master分支
#!/bin/sh
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
if [ "$protected_remote_branch" == "$remote_ref" ]; then
echo ".git/hooks: Do not commit to $protected_branch branch"
exit 1
exit 0
推送到master分支时提示
#!/bin/sh
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
if [ "$protected_remote_branch" == "$remote_ref" ]; then
read -p "You're about to push master, is that what you intended? [y|n] " -n 1 -r < /dev/tty
if echo $REPLY | grep -E '^[Yy]$' > /dev/null
exit 0 # push will execute
exit 1 # push will not execute
exit 0
为什么需要循环读取?因为git一次可以push多个分支
推送时如果commit消息包含WIP则禁止推送
#!/bin/sh
z40=0000000000000000000000000000000000000000
while read local_ref local_sha remote_ref remote_sha; do
if [ "$local_sha" = $z40 ]; then
# Handle delete
if [ "$remote_sha" = $z40 ]; then
# New branch, examine all commits
range="$local_sha"
# Update to existing branch, examine new commits
range="$remote_sha..$local_sha"
# Check for WIP commit
commit=$(git rev-list -n 1 --grep '^feat: WIP' "$range")
if [ -n "$commit" ]; then
echo >&2 "Found WIP commit in $local_ref, not pushing"
exit 1