0

I am extreme beginner in writing python scripts as I am learning it currently.

I am writing a code where I am going to extract the branches which I have which are named something like tobedeleted_branch1 , tobedeleted_branch2 etc with the help of python-gitlab module.

With so much of research and everything, I was able to extract the names of the branch with the script I have given bellow, but now what I want is, I need to delete the branches which are getting printed.

So I had a plan that, I will go ahead and store the print output in a variable and will delete them in a go, but I am still not able to store them in a variable.

Once I store the 'n' number of branches in that variable, I want to delete them.

I went through the documentation but I couldn't figure out how can I make use of it in python script.

Module: https://python-gitlab.readthedocs.io/en/stable/index.html

Delete branch with help of module REF: https://python-gitlab.readthedocs.io/en/stable/gl_objects/branches.html#branches

Any help regarding this is highly appreciated.

import gitlab, os
TOKEN = "MYTOKEN"
GITLAB_HOST = 'MYINSTANCE' 
gl = gitlab.Gitlab(GITLAB_HOST, private_token=TOKEN)

# set gitlab group id
group_id = 6
group = gl.groups.get(group_id, lazy=True)

#get all projects
projects = group.projects.list(include_subgroups=True, all=True)

#get all project ids
project_ids = []
for project in projects:
    project_ids.append((project.id))
print(project_ids)

for project in project_ids:
    project = gl.projects.get(project)
    branches = project.branches.list()
    for branch in branches:
       if "tobedeleted" in branch.attributes['name']:
           print(branch.attributes['name'])

Also, I am very sure this is not the clean way to write the script. Can you please drop your suggestions on how to make it better ?

Thanks

torek
  • 448,244
  • 59
  • 642
  • 775
Sameer Atharkar
  • 382
  • 1
  • 3
  • 17

1 Answers1

1

Branch objects have a delete method.

for branch in project.branches.list(as_list=False):
    if 'tobedeleted' in branch.name:
        branch.delete()

You can also delete a branch by name if you know its exact name already:

project.branches.delete('exact-branch-name')

As a side note:

The other thing you'll notice I've done is add the as_list=False argument to .list(). This will make sure that you paginate through all branches. Otherwise, you'll only get the first page (default 20 per page) of branches. The same is true for most list methods.

sytech
  • 29,298
  • 3
  • 45
  • 86