要实现不允许任何人在Github上推送到分支而没有经过审核,可以利用Github的Branch Protection功能。以下是一种解决方法的代码示例:
首先,在Github仓库的设置中打开Branches选项卡。
在Branches选项卡中,选择要保护的分支(比如主分支)。
在分支保护设置中,启用以下选项:
以下是使用Github REST API进行设置的示例代码(使用Python的requests库):
import requests
import json
# Github仓库信息
repo_owner = "your_repo_owner"
repo_name = "your_repo_name"
branch_name = "your_branch_name"
# Github API地址
api_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/branches/{branch_name}/protection"
# 要发送的请求数据
data = {
"required_pull_request_reviews": {
"dismissal_restrictions": {
"users": [],
"teams": []
},
"dismiss_stale_reviews": False,
"require_code_owner_reviews": True,
"required_approving_review_count": 1
},
"enforce_admins": True,
"restrictions": None
}
# 发送PUT请求以设置分支保护
response = requests.put(api_url, headers={"Authorization": "Bearer your_github_token"}, data=json.dumps(data))
# 检查响应结果
if response.status_code == 200:
print("分支保护设置成功!")
else:
print("分支保护设置失败!")
print(response.content)
请将上述代码中的以下变量替换为您的实际值:
repo_owner
:Github仓库所有者的用户名或组织名。repo_name
:Github仓库的名称。branch_name
:要保护的分支的名称。your_github_token
:您的Github个人访问令牌(具有适当的权限)。运行上述代码后,它将使用Github API在指定的仓库和分支上设置分支保护。从此时起,只有通过Pull Request审核的推送才会被接受,除非是管理员进行的推送。