首页 > 解决方案 > 有没有办法只允许分支创建者在 Github 中推送它?

问题描述

我尝试手动添加规则,但是由于加入团队的人很多,这很耗时。

更新:

标签: github

解决方案


我不会评论这是否是一个好主意。可以说,一旦导致我创建以下更新挂钩以应用于规范回购,我就很生气(但请注意,Github 不允许自定义更新挂钩,所以你在那里不走运):

#!/usr/bin/env python
import os
import re
import sys
from pathlib import Path
from subprocess import check_output


branch = sys.argv[1]
old_commit = sys.argv[2]
new_commit = sys.argv[3]
zero = "0000000000000000000000000000000000000000"
branch_pattern = 'feature/.+'


def get_author(commit):
    return str(check_output(['git', '--no-pager', 'show', '-s', "--format='%an'", commit]).strip(), 'utf-8')


def allow(message=None):
    if message:
        print(message)
    exit(0)


def deny(message=None):
    if message:
        print(message)
    exit(1)


# if this isn't a feature branch bail
if not re.match(branch_pattern, branch):
    allow()

# if the update is a delete bail
if new_commit == zero:
    allow("update: deleting branch '%s': OK" % branch)

# if this is the first commit on the branch bail
if old_commit == zero:
    allow("update: creating branch '%s': OK" % branch)

branch_log = Path('.git', 'logs', 'refs', 'heads').joinpath(*branch.split(os.path.sep))
with open(branch_log, 'r') as log:
    first_commit = log.readline(81).split(sep=' ', maxsplit=1)[1]

branch_author = get_author(first_commit)
new_commit_author = get_author(new_commit)

print("update: branch = '%s'; branch author = %s; commit author = %s" % (branch, branch_author, new_commit_author))

if new_commit_author == branch_author:
    allow("update: commit author == branch author: OK")
else:
    deny(
        "update: branch author != commit author: REJECTED\n"
        "update: create a branch for your changes from the tip of %s and request a pull instead"
        % branch
    )

推荐阅读