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.

38 lines
1.3 KiB

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