add kubespray to the XTesting as it provides newer version of kubenetes and can be...
[it/test.git] / XTesting / kubespray / scripts / gitlab-branch-cleanup / main.py
1 import gitlab
2 import argparse
3 import os
4 import sys
5 from datetime import timedelta, datetime, timezone
6
7
8 parser = argparse.ArgumentParser(
9     description='Cleanup old branches in a GitLab project')
10 parser.add_argument('--api', default='https://gitlab.com/',
11     help='URL of GitLab API, defaults to gitlab.com')
12 parser.add_argument('--age', type=int, default=30,
13     help='Delete branches older than this many days')
14 parser.add_argument('--prefix', default='pr-',
15     help='Cleanup only branches with names matching this prefix')
16 parser.add_argument('--dry-run', action='store_true',
17     help='Do not delete anything')
18 parser.add_argument('project',
19     help='Path of the GitLab project')
20
21 args = parser.parse_args()
22 limit = datetime.now(timezone.utc) - timedelta(days=args.age)
23
24 if os.getenv('GITLAB_API_TOKEN', '') == '':
25     print("Environment variable GITLAB_API_TOKEN is required.")
26     sys.exit(2)
27
28 gl = gitlab.Gitlab(args.api, private_token=os.getenv('GITLAB_API_TOKEN'))
29 gl.auth()
30
31 p = gl.projects.get(args.project)
32 for b in p.branches.list(all=True):
33     date = datetime.fromisoformat(b.commit['created_at'])
34     if date < limit and not b.protected and not b.default and b.name.startswith(args.prefix):
35         print("Deleting branch %s from %s ..." %
36             (b.name, date.date().isoformat()))
37         if not args.dry_run:
38             b.delete()