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': '[email protected]', 'authored_date': '2021-11-15T09:10:26.000+00:00', 'committer_name': 'Administrator', 'committer_email': '[email protected]', '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.

1
  • 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. Commented Nov 15, 2021 at 19:31

3 Answers 3

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()
Sign up to request clarification or add additional context in comments.

2 Comments

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
@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
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

5 Comments

Why not timedelta(days=7) ?
we should pass timezone to datetime.datetime.now() to get correct current datetime and hence day difference
@aberry you are right
Thanks for the answer @Vassago 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.
@SameerAtharkar It's an example, you may replace created_at and days to with what you want
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

2 Comments

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
sorry @SameerAtharkar, mydict should be branch.attributes I just was testing on my end. I have changed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.