5 from datetime import timedelta, datetime, timezone
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')
21 args = parser.parse_args()
22 limit = datetime.now(timezone.utc) - timedelta(days=args.age)
24 if os.getenv('GITLAB_API_TOKEN', '') == '':
25 print("Environment variable GITLAB_API_TOKEN is required.")
28 gl = gitlab.Gitlab(args.api, private_token=os.getenv('GITLAB_API_TOKEN'))
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()))