-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgithub-labeler.py
executable file
·69 lines (57 loc) · 2.19 KB
/
github-labeler.py
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
#!/usr/bin/env python3
"""
The script applies a label in the form "Target: {branchName}. If necessary, it
removes labels in the same form, but NOT for the target branch. For instance, if
someone edited the target branch from v4.0.x to v5.0.x
"""
import os
import re
import sys
from github import Github
# ==============================================================================
GITHUB_BASE_REF = os.environ.get('GITHUB_BASE_REF')
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
GITHUB_REPOSITORY = os.environ.get('GITHUB_REPOSITORY')
PR_NUM = os.environ.get('PR_NUM')
# Sanity check
if (GITHUB_BASE_REF is None or
GITHUB_TOKEN is None or
GITHUB_REPOSITORY is None or
PR_NUM is None):
print("Error: this script is designed to run as a Github Action")
exit(1)
# ==============================================================================
# Given a pullRequest object and list of existing labels, the function checks
# what labels are currently on the pull request, removes any matching the form
# "Target: {branch}" (if {branch} is not the current target branch), and adds
# the correct label.
#
# Because the GH API automatically creates a label when applying it (if it
# doesn't exist), we try to get a label object to check if the label has been
# created before we add (and create) it ourselves.
def ensureLabels(pullRequest, repo):
needsLabel = True
targetPrefix = "Target: "
targetLabel = f"{targetPrefix}{GITHUB_BASE_REF}"
try:
repo.get_label(targetLabel)
except:
print(f"Label '{targetLabel}' not found")
return None
for label in pullRequest.get_labels():
if label.name.startswith(targetPrefix):
if label.name == targetLabel:
needsLabel = False
else:
print(f"Removing label '{label.name}'")
pullRequest.remove_from_labels(label)
if needsLabel:
print(f"Adding label '{targetLabel}'")
pullRequest.add_to_labels(targetLabel)
return None
# ==============================================================================
g = Github(GITHUB_TOKEN)
repo = g.get_repo(GITHUB_REPOSITORY)
prNum = int(PR_NUM)
pr = repo.get_pull(prNum)
ensureLabels(pr, repo)