From 1ae794e5e4f85844ef8f060675837ad627a8878b Mon Sep 17 00:00:00 2001
From: Maxime Guyot <Miouge1@users.noreply.github.com>
Date: Fri, 20 Mar 2020 21:16:06 +0100
Subject: [PATCH] Add script to cleanup old gitlab branches (#5795)

---
 scripts/gitlab-branch-cleanup/.gitignore      |  2 +
 scripts/gitlab-branch-cleanup/README.md       | 24 +++++++++++
 scripts/gitlab-branch-cleanup/main.py         | 40 +++++++++++++++++++
 .../gitlab-branch-cleanup/requirements.txt    |  1 +
 4 files changed, 67 insertions(+)
 create mode 100644 scripts/gitlab-branch-cleanup/.gitignore
 create mode 100644 scripts/gitlab-branch-cleanup/README.md
 create mode 100644 scripts/gitlab-branch-cleanup/main.py
 create mode 100644 scripts/gitlab-branch-cleanup/requirements.txt

diff --git a/scripts/gitlab-branch-cleanup/.gitignore b/scripts/gitlab-branch-cleanup/.gitignore
new file mode 100644
index 000000000..03e7ca8de
--- /dev/null
+++ b/scripts/gitlab-branch-cleanup/.gitignore
@@ -0,0 +1,2 @@
+openrc
+venv
diff --git a/scripts/gitlab-branch-cleanup/README.md b/scripts/gitlab-branch-cleanup/README.md
new file mode 100644
index 000000000..6a2b5ffbe
--- /dev/null
+++ b/scripts/gitlab-branch-cleanup/README.md
@@ -0,0 +1,24 @@
+# gitlab-branch-cleanup
+
+Cleanup old branches in a GitLab project
+
+## Installation
+
+```shell
+pip install -r requirements.txt
+python main.py --help
+```
+
+## Usage
+
+```console
+$ export GITLAB_API_TOKEN=foobar
+$ python main.py kargo-ci/kubernetes-sigs-kubespray
+Deleting branch pr-5220-containerd-systemd from 2020-02-17 ...
+Deleting branch pr-5561-feature/cinder_csi_fixes from 2020-02-17 ...
+Deleting branch pr-5607-add-flatcar from 2020-02-17 ...
+Deleting branch pr-5616-fix-typo from 2020-02-17 ...
+Deleting branch pr-5634-helm_310 from 2020-02-18 ...
+Deleting branch pr-5644-patch-1 from 2020-02-15 ...
+Deleting branch pr-5647-master from 2020-02-17 ...
+```
diff --git a/scripts/gitlab-branch-cleanup/main.py b/scripts/gitlab-branch-cleanup/main.py
new file mode 100644
index 000000000..ec1875935
--- /dev/null
+++ b/scripts/gitlab-branch-cleanup/main.py
@@ -0,0 +1,40 @@
+import gitlab
+import argparse
+import os
+import sys
+from datetime import timedelta, datetime, timezone
+
+
+from pprint import pprint
+
+parser = argparse.ArgumentParser(
+    description='Cleanup old branches in a GitLab project')
+parser.add_argument('--api', default='https://gitlab.com/',
+    help='URL of GitLab API, defaults to gitlab.com')
+parser.add_argument('--age', type=int, default=30,
+    help='Delete branches older than this many days')
+parser.add_argument('--prefix', default='pr-',
+    help='Cleanup only branches with names matching this prefix')
+parser.add_argument('--dry-run', action='store_true',
+    help='Do not delete anything')
+parser.add_argument('project',
+    help='Path of the GitLab project')
+
+args = parser.parse_args()
+limit = datetime.now(timezone.utc) - timedelta(days=args.age)
+
+if os.getenv('GITLAB_API_TOKEN', '') == '':
+    print("Environment variable GITLAB_API_TOKEN is required.")
+    sys.exit(2)
+
+gl = gitlab.Gitlab(args.api, private_token=os.getenv('GITLAB_API_TOKEN'))
+gl.auth()
+
+p = gl.projects.get(args.project)
+for b in p.branches.list(all=True):
+    date = datetime.fromisoformat(b.commit['created_at'])
+    if date < limit and not b.protected and not b.default and b.name.startswith(args.prefix):
+        print("Deleting branch %s from %s ..." %
+            (b.name, date.date().isoformat()))
+        if not args.dry_run:
+            b.delete()
diff --git a/scripts/gitlab-branch-cleanup/requirements.txt b/scripts/gitlab-branch-cleanup/requirements.txt
new file mode 100644
index 000000000..4a169edeb
--- /dev/null
+++ b/scripts/gitlab-branch-cleanup/requirements.txt
@@ -0,0 +1 @@
+python-gitlab
-- 
GitLab