You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.4 KiB

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