How to update a protected branch in python-gitlab?

2.1k Views Asked by At

I am using python-gitlab to help configure projects. I'm trying to automate going into GitLab Settings > Repository > Protected branches, then for the existing master branch, changing "Allowed to merge" from "Maintainers" to "Developers + Maintainers". Here's a code snippet:

import gitlab
gl = gitlab.Gitlab.from_config()
project = project = gl.projects.get("my-team/my_project")
master_branch = project.protectedbranches.get("master")
print(master_branch.merge_access_levels)

The data type is just is a list of dicts; there doesn't appear to be a way to update the setting like other settings in this API. Even is you just update it:

master_branch.merge_access_levels[0]['access_level'] = 30
project.save()

nothing happens. Is there a way to do this with python-gitlab?

2

There are 2 best solutions below

0
On

For what I've done in my project, I didn't find any way to update. So I just remove the wanted branch from protected branch list and then create the protected branch again by referring to the official docs.

project.protectedbranches.delete('master')
project.protectedbranches.create({
    'name': 'master',
    'merge_access_level': gitlab.const.AccessLevel.NO_ACCESS,
    'push_access_level': gitlab.const.AccessLevel.NO_ACCESS,
    'allow_force_push': False
})

And this works really well.

Attention: the delete/create actions just remove/put the wanted branch from/into protected branches list, there is no risk with the branch itself.

0
On

You are looking for branch.protect():

branch = project.branches.get('master')
branch.protect(developers_can_push=True, developers_can_merge=True)