Python中如何通过GitLab API修改分支的protected-branches设置?
求助下, 关于 protected-branches-api, 文档提到能够获取和创建 access levels, 但没有提到修改, 使用 python-gitlab 也没有找到相关的方法, 请问大大们是用什么解决的
现在我只能通过网页登录在 Repository Settings - Protected Branches 中手动修改
Python中如何通过GitLab API修改分支的protected-branches设置?
2 回复
import requests
import json
class GitLabBranchProtector:
def __init__(self, gitlab_url, private_token, project_id):
"""
初始化GitLab API客户端
Args:
gitlab_url: GitLab实例地址(如:https://gitlab.example.com)
private_token: 个人访问令牌(需有maintainer以上权限)
project_id: 项目ID(数字ID或带命名空间的路径,如:group/project)
"""
self.base_url = f"{gitlab_url.rstrip('/')}/api/v4"
self.headers = {
"Private-Token": private_token,
"Content-Type": "application/json"
}
self.project_id = project_id
def update_branch_protection(self, branch_name, protection_settings):
"""
更新分支保护设置
Args:
branch_name: 分支名称(如:main、develop)
protection_settings: 保护设置字典,包含以下字段:
- push_access_level: 推送权限(0=无,30=开发者,40=维护者)
- merge_access_level: 合并权限(0=无,30=开发者,40=维护者)
- allow_force_push: 是否允许强制推送(bool)
- code_owner_approval_required: 是否需要代码所有者批准(bool)
Returns:
API响应结果
"""
# API端点:PUT /projects/:id/protected_branches/:name
endpoint = f"{self.base_url}/projects/{self.project_id}/protected_branches/{branch_name}"
# 构建请求参数
params = {
"push_access_level": protection_settings.get("push_access_level", 40),
"merge_access_level": protection_settings.get("merge_access_level", 40),
"allow_force_push": protection_settings.get("allow_force_push", False),
"code_owner_approval_required": protection_settings.get("code_owner_approval_required", False)
}
# 发送PUT请求
response = requests.put(endpoint, headers=self.headers, json=params)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"API调用失败: {response.status_code} - {response.text}")
def get_branch_protection(self, branch_name):
"""
获取当前分支保护设置
"""
endpoint = f"{self.base_url}/projects/{self.project_id}/protected_branches/{branch_name}"
response = requests.get(endpoint, headers=self.headers)
return response.json() if response.status_code == 200 else None
# 使用示例
if __name__ == "__main__":
# 配置信息
GITLAB_URL = "https://gitlab.example.com"
TOKEN = "your_private_token_here" # 从GitLab设置中获取
PROJECT = "mygroup/myproject" # 或使用数字ID如123
# 创建客户端
protector = GitLabBranchProtector(GITLAB_URL, TOKEN, PROJECT)
# 设置main分支保护:仅维护者可推送和合并,禁止强制推送
settings = {
"push_access_level": 40, # 40=维护者,30=开发者
"merge_access_level": 40,
"allow_force_push": False,
"code_owner_approval_required": True
}
try:
result = protector.update_branch_protection("main", settings)
print("分支保护设置更新成功:", json.dumps(result, indent=2))
# 验证设置
current = protector.get_branch_protection("main")
print("当前保护设置:", json.dumps(current, indent=2))
except Exception as e:
print(f"操作失败: {e}")
关键点说明:
- 权限要求:需要
maintainer或以上角色权限的访问令牌 - API端点:使用
PUT /projects/:id/protected_branches/:name更新现有保护规则 - 访问级别值:
0:无访问权限30:开发者(Developer)40:维护者(Maintainer)
- 首次设置:如果分支从未设置过保护,需要先用
POST /projects/:id/protected_branches创建保护规则
一句话建议:确保你的访问令牌有足够权限,并注意首次设置和更新使用的是不同API端点。
重新 post 一个就行

