相关文章推荐
聪明伶俐的葫芦  ·  PyTorch - ...·  8 月前    · 
飘逸的企鹅  ·  WebSettings.JavaScript ...·  1 年前    · 
拉风的眼镜  ·  Excel 宏 VAB ...·  1 年前    · 
备案 控制台
学习
实践
活动
专区
工具
TVP
写文章
专栏首页 职场亮哥 git禁止在master分支push和commit
3 1

海报分享

git禁止在master分支push和commit

作为管理者,在远端将master分支设为保护分支,可以从根源上杜绝直接推送到master的问题。dev分支同理。

作为开发者,在本地的git hook中加配置可以做到在commit和push操作时做对应的检查

禁止在master分支上Commit

#!/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