-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync_labels.py
More file actions
255 lines (214 loc) · 8.17 KB
/
Copy pathsync_labels.py
File metadata and controls
255 lines (214 loc) · 8.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#!/usr/bin/env python3
"""Sync GitHub labels from a JSON definition file to one or more repositories.
Usage:
python sync_labels.py --token ghp_xxx
python sync_labels.py --token ghp_xxx --repos 3dcitydb/3dcitydb
python sync_labels.py --token ghp_xxx --dry-run
python sync_labels.py --token ghp_xxx --remove-all --dry-run
python sync_labels.py --token ghp_xxx --remove-only
python sync_labels.py --token ghp_xxx --file my-labels.json
"""
import argparse
import json
import os
import sys
from urllib.parse import quote
import requests
API_BASE = "https://api.github.com"
DEFAULT_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "labels.json")
def load_labels(path):
with open(path, encoding="utf-8") as f:
return json.load(f)
def normalize_color(color):
return color.lstrip("#").lower()
def get_existing_labels(session, repo):
"""Fetch all existing labels for a repo, handling pagination."""
labels = []
url = f"{API_BASE}/repos/{repo}/labels"
params = {"per_page": 100}
while url:
resp = session.get(url, params=params)
resp.raise_for_status()
labels.extend(resp.json())
# Follow pagination links
url = resp.links.get("next", {}).get("url")
params = None # params already encoded in the next URL
return labels
def check_rate_limit(session):
resp = session.get(f"{API_BASE}/rate_limit")
if resp.ok:
data = resp.json()
remaining = data["resources"]["core"]["remaining"]
limit = data["resources"]["core"]["limit"]
if remaining < 50:
print(f" WARNING: GitHub API rate limit low: {remaining}/{limit} remaining")
return remaining
return None
def remove_all_labels(session, repo, dry_run=False):
"""Remove all existing labels from a repository."""
existing = get_existing_labels(session, repo)
if not existing:
print(" No existing labels to remove.")
return 0
removed = 0
for label in existing:
name = label["name"]
if dry_run:
print(f" DELETE {name}")
else:
url = f"{API_BASE}/repos/{repo}/labels/{quote(name, safe='')}"
resp = session.delete(url)
resp.raise_for_status()
print(f" DELETED {name}")
removed += 1
print(f"\n Removed: {removed} label(s)")
return removed
def sync_repo(session, repo, target_labels, dry_run=False):
"""Sync labels for a single repository. Returns counts of actions taken."""
print(f"\n{'=' * 60}")
print(f"Repository: {repo}")
print(f"{'=' * 60}")
existing = get_existing_labels(session, repo)
existing_map = {label["name"].lower(): label for label in existing}
created = 0
updated = 0
unchanged = 0
for target in target_labels:
name = target["name"]
color = normalize_color(target["color"])
description = target.get("description", "")
name_lower = name.lower()
if name_lower in existing_map:
existing_label = existing_map[name_lower]
existing_color = normalize_color(existing_label["color"])
existing_desc = existing_label.get("description") or ""
if existing_color != color or existing_desc != description:
if dry_run:
changes = []
if existing_color != color:
changes.append(f"color: {existing_color} -> {color}")
if existing_desc != description:
changes.append("description changed")
print(f" UPDATE {name} ({', '.join(changes)})")
else:
url = f"{API_BASE}/repos/{repo}/labels/{quote(existing_label['name'], safe='')}"
resp = session.patch(url, json={
"new_name": name,
"color": color,
"description": description,
})
resp.raise_for_status()
print(f" UPDATED {name}")
updated += 1
else:
unchanged += 1
else:
if dry_run:
print(f" CREATE {name} (#{color})")
else:
url = f"{API_BASE}/repos/{repo}/labels"
resp = session.post(url, json={
"name": name,
"color": color,
"description": description,
})
resp.raise_for_status()
print(f" CREATED {name}")
created += 1
print(f"\n Summary: {created} created, {updated} updated, {unchanged} unchanged")
return created, updated, unchanged
def build_target_labels(data, repo):
"""Build the full list of target labels for a repo (shared + repo-specific)."""
labels = list(data["shared_labels"])
repo_specific = data.get("repo_labels", {}).get(repo, [])
labels.extend(repo_specific)
return labels
def main():
parser = argparse.ArgumentParser(
description="Sync GitHub labels from a JSON definition file."
)
parser.add_argument(
"--token",
default=os.environ.get("GITHUB_TOKEN"),
help="GitHub personal access token (or set GITHUB_TOKEN env var)",
)
parser.add_argument(
"--file",
default=DEFAULT_FILE,
help=f"Path to labels JSON file (default: {DEFAULT_FILE})",
)
parser.add_argument(
"--repos",
nargs="+",
help="Specific repos to sync (default: all repos in JSON file)",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would change without applying",
)
parser.add_argument(
"--remove-all",
action="store_true",
help="Remove all existing labels from target repos before syncing",
)
parser.add_argument(
"--remove-only",
action="store_true",
help="Remove all existing labels from target repos without syncing",
)
args = parser.parse_args()
if args.remove_all and args.remove_only:
print("Error: --remove-all and --remove-only are mutually exclusive.",
file=sys.stderr)
sys.exit(1)
if not args.token:
print("Error: GitHub token required. Use --token or set GITHUB_TOKEN env var.",
file=sys.stderr)
sys.exit(1)
data = load_labels(args.file)
repos = args.repos or data["repositories"]
# Validate requested repos are in the JSON file
known_repos = set(data["repositories"])
for repo in repos:
if repo not in known_repos:
print(f"Warning: '{repo}' is not listed in {args.file}, "
f"only shared labels will be applied.", file=sys.stderr)
session = requests.Session()
session.headers.update({
"Authorization": f"token {args.token}",
"Accept": "application/vnd.github.v3+json",
"X-GitHub-Api-Version": "2022-11-28",
})
if args.dry_run:
print("DRY RUN - no changes will be made\n")
check_rate_limit(session)
total_created = 0
total_updated = 0
total_unchanged = 0
for repo in repos:
try:
if args.remove_all or args.remove_only:
print(f"\n{'=' * 60}")
print(f"Repository: {repo}")
print(f"{'=' * 60}")
remove_all_labels(session, repo, dry_run=args.dry_run)
if args.remove_only:
continue
target_labels = build_target_labels(data, repo)
c, u, uc = sync_repo(session, repo, target_labels, dry_run=args.dry_run)
total_created += c
total_updated += u
total_unchanged += uc
except requests.HTTPError as e:
print(f"\n ERROR syncing {repo}: {e}", file=sys.stderr)
if e.response is not None:
print(f" Response: {e.response.text}", file=sys.stderr)
check_rate_limit(session)
print(f"\n{'=' * 60}")
print(f"Total: {total_created} created, {total_updated} updated, "
f"{total_unchanged} unchanged across {len(repos)} repo(s)")
if args.dry_run:
print("(DRY RUN - no changes were made)")
if __name__ == "__main__":
main()