0

I am trying to extract the specific details like authored_date from the attribute which I am getting with help of python.

What is my end goal:

I want to extract the specific branches which are named as tobedeleted_branch1, tobedeleted_branch2 and delete them with help of my script if the authored_date is more than 7 days.

I am beginner in this and learning this currently.

So, what I want to do is,

Extract the authored date from the output and check if it is older than 7 days. If it is older than 7 days I will go ahead and perform whatever I want to perform in if condition.

import gitlab, os
#from gitlab.v4.objects import *
# authenticate
TOKEN = "MYTOKEN"
GITLAB_HOST = 'MYINSTANCE' # or your instance
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.path_with_namespace, project.id, project.name ))
    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'])
           #print(branch)
           print(branch.attributes['commit'])
           #branch.delete()

The output which I am getting from printing the print(branch.attributes['commit']) is like :

{'id': '1245829930', 'short_id': '124582', 'created_at': '2021-11-15T09:10:26.000+00:00', 'parent_ids': None, 'title': 'branch name commit' into \'master\'"', 'message': 'branch name commit', 'author_name': 'Administrator', 'author_email': 'someemail@gmail.com', 'authored_date': '2021-11-15T09:10:26.000+00:00', 'committer_name': 'Administrator', 'committer_email': 'someemail@gmail.com', 'committed_date': '2021-11-15T09:10:26.000+00:00', 'trailers': None, 'web_url': 'someweburl'}

From the above output, I want to extract the 'authored_date' and check if it is greated than 7 days I will go ahead and delete the merged branch.

Any help regarding this is highly appreciated.

torek
  • 448,244
  • 59
  • 642
  • 775
Sameer Atharkar
  • 382
  • 1
  • 3
  • 17
  • There's nothing in this question that is about Git or GitLab, it's all about the Python interface. The one thing I would note that *is* a Git/GitLab thing is that the "branch commit date" is the date on the *tip commit* of the branch. As the branch name is altered to point to different commits, you'll pick up each commit's information. – torek Nov 15 '21 at 19:31

3 Answers3

0
import datetime
created_at = '2021-11-15T09:10:26.000+00:00'
t = datetime.datetime.fromisoformat(created_at)
n = datetime.datetime.now(tz=t.tzinfo)

if n - t <= datetime.timedelta(days=7):
    ... # do someting
Vox
  • 506
  • 2
  • 13
0

using your branch.attributes about your commit inside your loop, you can do the following (make sure you import datetime). You'll want to append the branch name to be deleted to a list that you'll iterate over after, as you do not want to modify any object that you are currently iterating over (IE deleting items from the branches object that you are still iterating over).

from datetime import datetime

...
branches_to_delete = []
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'])
           #print(branch)
           print(branch.attributes['commit'])
           branch_date_object = datetime.strptime((branch.attributes['commit']['authored_date'].split('.')[0]), "%Y-%m-%dT%H:%M:%S")
           days_diff = datetime.now() - branch_date_object
           if days_diff.days > 7:
               branches_to_delete.append(branch.attributes['name'])

for branch in branches_to_delete:
    # perform your delete functionality
d_kennetz
  • 5,219
  • 5
  • 21
  • 44
  • I am getting the name error as : `branch_date_object = datetime.strptime((mydict['commit']['authored_date'].split('.')[0]), "%Y-%m-%dT%H:%M:%S") NameError: name 'mydict' is not defined` – Sameer Atharkar Nov 15 '21 at 15:59
  • sorry @SameerAtharkar, mydict should be `branch.attributes` I just was testing on my end. I have changed it. – d_kennetz Nov 15 '21 at 19:53
0
from datetime import datetime
def get_day_diff(old_date):
    old_datetime = datetime.fromisoformat(old_date)
    # Check timezone of date
    tz_info = old_datetime.tzinfo
    current_datetime = datetime.now(tz_info)
    datetime_delta = current_datetime - old_datetime
    return datetime_delta.days

# test with authored_date
authored_date = '2021-11-15T09:10:26.000+00:00'
if get_day_diff(authored_date) > 7:
  # then delete branch
  branch.delete()
aberry
  • 447
  • 3
  • 10
  • Thanks for the answer @aberry but one thing I forgot to mention is that, the authored date will be different for every other branch. So I can not hardcode that specific date – Sameer Atharkar Nov 15 '21 at 16:04
  • @SameerAtharkar I am not hard coding date here. It is just a example to test get_day_diff method. You will use above method for 'branch.attributes['commit']['authored_date']' in your code – aberry Nov 15 '21 at 18:15