繁体   English   中英

如何防止使用 python 推送到主分支?

[英]How to prevent push to master branch using python?

我在 python 中编写了一个预推送钩子,它可以防止部分推送到主分支。 即在功能分支中并给出此命令git push origin master时,文件被推送。

在下图中,当头部位于主分支时,会阻止推送。 当用户在 master 分支时,推送被阻止

但是当 head 在 feature1 分支中时,不会阻止向 master 推送。 在此处输入图像描述

到目前为止我的代码:

#!/usr/bin/env python

import sys
import re
from subprocess import check_output

branch = check_output(['git', 'symbolic-ref','--short','HEAD']).strip()
print('branch-name:',branch.decode('utf-8')) #this prints the current branch: feature (if in feature) 


if ((branch.decode('utf-8')) != 'master'):
    print('into if clause')
    print('push to remote successful')
    sys.exit(0)

else :
    print('into else clause')
    print('you are not allowed to push to the master branch')
    sys.exit(1)

我想以不允许以下命令的方式修改代码(无论它位于哪个分支): git push --force origin master git push --delete origin master ; git push origin master git co master git push --force origin 提前致谢。

如果您在 Github 的私人仓库上使用免费计划,您可能无法使用受保护的分支功能。 所以你需要阻止来自本地的任何推送/提交。
请记住,可以使用--no-verify命令轻松绕过它。

我建议你使用哈士奇而不是 python 来做,因为我认为这更容易..

这就是我为使其在本地工作并分发给所有 repo 成员所做的工作。

首先,你需要安装 husky 来控制 pre-commit 和 pre-push hook。 然后,我制作了一个预推送 bash 脚本并将其提交到存储库中。 然后使用 husky 参数从 husky pre-push hook 调用这个脚本。

这是我在package.json中的沙哑配置(如果需要,您可以设置单独的配置)

"husky": {
    "hooks": {
        "pre-commit": "./commands/pre-commit",
        "pre-push": "./commands/pre-push $HUSKY_GIT_STDIN"
    }
},

如您所见,我有 2 个脚本,一个用于预推送,一个用于预提交。

这是我的commands/pre-push bash 脚本

#!/bin/bash

echo -e "===\n>> Talenavi Pre-push Hook: Checking branch name / Mengecek nama branch..."

BRANCH=`git rev-parse --abbrev-ref HEAD`
PROTECTED_BRANCHES="^(master|develop)"

if [[ $1 != *"$BRANCH"* ]]
then
  echo -e "\n🚫 You must use (git push origin $BRANCH) / Anda harus menggunakan (git push origin $BRANCH).\n" && exit 1
fi

if [[ "$BRANCH" =~ $PROTECTED_BRANCHES ]]
then
  echo -e "\n🚫 Cannot push to remote $BRANCH branch, please create your own branch and use PR."
  echo -e "🚫 Tidak bisa push ke remote branch $BRANCH, silahkan buat branch kamu sendiri dan gunakan pull request.\n" && exit 1
fi

echo -e ">> Finish checking branch name / Selesai mengecek nama branch.\n==="

exit 0

该脚本基本上会做两件事:

  • 该脚本将阻止任何试图推送到某个分支的人(在我的情况下,我不希望任何人——包括我自己——直接推送到masterdevelop分支)。 他们需要在自己的分支中工作,然后创建拉取请求。
  • 此脚本将阻止任何尝试推送到与其当前活动分支不同的分支的人。 例如,您在分支fix/someissue中,但随后您错误地输入git push origin master

有关更详细的说明,您可以从本文中进行操作:
https://github.com/talenavi/husky-precommit-prepush-githooks

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM