python-3.xgitlabgitlab-apipython-gitlab

How to update a Branch using python-gitlab for Gitlab API?


Im working on a small project which uses python-gitlab on its version 3.13.0

The project has a mixture of 2.x.x and 3.x.x features that i've been fixing, but there are a few methods for branches that i can't reproduce.

I saw a similar question for what im looking here stackoverflow-question, but the given answer suggests to use branch.unprotect(), and that method along with branch.protect() is no longer working on 3.x.x versions on.

I've been digging into the docs https://python-gitlab.readthedocs.io/en/stable/gl_objects/branches.html and https://python-gitlab.readthedocs.io/en/stable/gl_objects/protected_branches.html but haven't found a direct way to reproduce those methods, any ideas about that?

Thanks in advance!

Im running these methods inside a few tests on a ci/cd in Gitlab, already got tests to create repositories, branches, retrieve them and delete, but havent been able to reproduce the protect and unprotect branches.


Solution

  • 3.13.0 seems to be an odd version to use - and it is two years old. Why not update at least to a more recent 3.15. or even 4.X.X? But I guess that might not even be the issue you are encountering here.

    Have you taken a look at the GitLab API docs for protected branches? From what I see in python-gitlab this is the endpoint used in both 2.X.X and 3.X.X versions. Only the method was moved as noted here in the post you already mentioned.

    The calls seem to be pretty much straight forward and could worst case be called directly using the requests library:

    import requests
    
    projectid=5
    branch="*-stable"
    headers = {'PRIVATE-TOKEN': 'YOUR-TOKEN-HERE'}
    
    requests.delete(f'https://gitlab.example.com/api/v4/projects/{projectid}/protected_branches/{branch}', headers=headers)
    

    The more challenging part is to find the right protection rule to delete if a wildcard is used for the protection rule! I assume that already was an issue in python-gitlab 2.X.X and maybe a reason to move the method (and reflect the structure of the API after all).