|
| 1 | +#!/usr/bin/env -S uv --quiet run --script |
| 2 | +# /// script |
| 3 | +# requires-python = ">=3.12" |
| 4 | +# dependencies = [ |
| 5 | +# "requests", |
| 6 | +# ] |
| 7 | +# /// |
| 8 | +"""Clean up GitLab projects older than a given number of days in a group. |
| 9 | +
|
| 10 | +Uses TEST_GITLAB_API_URL, TEST_GITLAB_TOKEN, and TEST_GITLAB_GROUP environment |
| 11 | +variables by default (same as the E2E test suite), but all values can be |
| 12 | +overridden via CLI flags. |
| 13 | +
|
| 14 | +Examples: |
| 15 | + # Dry-run (default) — show what would be deleted: |
| 16 | + ./hack/cleanup-gitlab-projects.py |
| 17 | +
|
| 18 | + # Actually delete: |
| 19 | + ./hack/cleanup-gitlab-projects.py --force |
| 20 | +
|
| 21 | + # Custom age threshold: |
| 22 | + ./hack/cleanup-gitlab-projects.py --days 3 --force |
| 23 | +""" |
| 24 | + |
| 25 | +import argparse |
| 26 | +import os |
| 27 | +import sys |
| 28 | +from datetime import datetime, timezone |
| 29 | + |
| 30 | +import requests |
| 31 | + |
| 32 | + |
| 33 | +def get_projects(base_url: str, token: str, group: str) -> list[dict]: |
| 34 | + """Return all projects in the given group, handling pagination.""" |
| 35 | + headers = {"PRIVATE-TOKEN": token} |
| 36 | + url = f"{base_url}/api/v4/groups/{requests.utils.quote(group, safe='')}/projects" |
| 37 | + params: dict = {"per_page": 100, "page": 1, "include_subgroups": False} |
| 38 | + projects: list[dict] = [] |
| 39 | + while True: |
| 40 | + resp = requests.get(url, headers=headers, params=params, timeout=30) |
| 41 | + resp.raise_for_status() |
| 42 | + batch = resp.json() |
| 43 | + if not batch: |
| 44 | + break |
| 45 | + projects.extend(batch) |
| 46 | + params["page"] += 1 |
| 47 | + return projects |
| 48 | + |
| 49 | + |
| 50 | +def delete_project(base_url: str, token: str, project_id: int) -> None: |
| 51 | + headers = {"PRIVATE-TOKEN": token} |
| 52 | + url = f"{base_url}/api/v4/projects/{project_id}" |
| 53 | + resp = requests.delete(url, headers=headers, timeout=30) |
| 54 | + resp.raise_for_status() |
| 55 | + |
| 56 | + |
| 57 | +def main() -> None: |
| 58 | + parser = argparse.ArgumentParser( |
| 59 | + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter |
| 60 | + ) |
| 61 | + parser.add_argument( |
| 62 | + "--api-url", |
| 63 | + default=os.getenv("TEST_GITLAB_API_URL", "https://gitlab.pipelinesascode.com"), |
| 64 | + help="GitLab API base URL (default: $TEST_GITLAB_API_URL)", |
| 65 | + ) |
| 66 | + parser.add_argument( |
| 67 | + "--token", |
| 68 | + default=os.getenv("TEST_GITLAB_TOKEN", ""), |
| 69 | + help="GitLab private token (default: $TEST_GITLAB_TOKEN)", |
| 70 | + ) |
| 71 | + parser.add_argument( |
| 72 | + "--group", |
| 73 | + default=os.getenv("TEST_GITLAB_GROUP", "pac-e2e-tests"), |
| 74 | + help="GitLab group path (default: $TEST_GITLAB_GROUP)", |
| 75 | + ) |
| 76 | + parser.add_argument( |
| 77 | + "--days", |
| 78 | + type=int, |
| 79 | + default=7, |
| 80 | + help="Delete projects older than this many days (default: 7)", |
| 81 | + ) |
| 82 | + parser.add_argument( |
| 83 | + "--force", |
| 84 | + action="store_true", |
| 85 | + help="Actually delete projects (default is dry-run)", |
| 86 | + ) |
| 87 | + args = parser.parse_args() |
| 88 | + |
| 89 | + if not args.token: |
| 90 | + print( |
| 91 | + "ERROR: GitLab token is required. Set TEST_GITLAB_TOKEN or pass --token.", |
| 92 | + file=sys.stderr, |
| 93 | + ) |
| 94 | + sys.exit(1) |
| 95 | + |
| 96 | + base_url = args.api_url.rstrip("/") |
| 97 | + now = datetime.now(tz=timezone.utc) |
| 98 | + |
| 99 | + print(f"Listing projects in group '{args.group}' on {base_url} ...") |
| 100 | + projects = get_projects(base_url, args.token, args.group) |
| 101 | + print(f"Found {len(projects)} project(s).") |
| 102 | + |
| 103 | + to_delete = [] |
| 104 | + for proj in projects: |
| 105 | + created = datetime.fromisoformat(proj["created_at"]) |
| 106 | + age = now - created |
| 107 | + if age.days >= args.days: |
| 108 | + to_delete.append((proj, age)) |
| 109 | + |
| 110 | + if not to_delete: |
| 111 | + print(f"No projects older than {args.days} day(s). Nothing to do.") |
| 112 | + return |
| 113 | + |
| 114 | + print(f"\n{len(to_delete)} project(s) older than {args.days} day(s):\n") |
| 115 | + for proj, age in to_delete: |
| 116 | + print( |
| 117 | + f" {proj['path_with_namespace']} (ID {proj['id']}, created {proj['created_at']}, {age.days}d old)" |
| 118 | + ) |
| 119 | + |
| 120 | + if not args.force: |
| 121 | + print("\nDry-run mode. Pass --force to delete these projects.") |
| 122 | + return |
| 123 | + |
| 124 | + print() |
| 125 | + errors = 0 |
| 126 | + for proj, age in to_delete: |
| 127 | + name = proj["path_with_namespace"] |
| 128 | + try: |
| 129 | + delete_project(base_url, args.token, proj["id"]) |
| 130 | + print(f" Deleted {name} (ID {proj['id']})") |
| 131 | + except requests.HTTPError as exc: |
| 132 | + print(f" ERROR deleting {name}: {exc}", file=sys.stderr) |
| 133 | + errors += 1 |
| 134 | + |
| 135 | + deleted = len(to_delete) - errors |
| 136 | + print(f"\nDone. Deleted {deleted} project(s).", end="") |
| 137 | + if errors: |
| 138 | + print(f" {errors} error(s).", end="") |
| 139 | + print() |
| 140 | + |
| 141 | + |
| 142 | +if __name__ == "__main__": |
| 143 | + main() |
0 commit comments