Skip to content

Commit ab22e59

Browse files
committed
github-labeler: check if the label exists before adding it
The GitHub API automatically creates a label when applying it (if it doesn't exist already), so we need to check if the label exists in the repo before we go to apply (and create) it. This way, the humans have control over which labels are created and assigned, which is how the bot should work.
1 parent 186f0fb commit ab22e59

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

github-labeler.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,22 +31,32 @@
3131

3232
# ==============================================================================
3333

34-
# Given a pullRequest object, the function checks what labels are currently on
35-
# the pull request, removes any matching the form "Target: {branch}" (if
36-
# {branch} is not the current target branch), and adds the correct label.
37-
def ensureLabels(pullRequest):
34+
# Given a pullRequest object and list of existing labels, the function checks
35+
# what labels are currently on the pull request, removes any matching the form
36+
# "Target: {branch}" (if {branch} is not the current target branch), and adds
37+
# the correct label.
38+
#
39+
# Because the GH API automatically creates a label when applying it (if it
40+
# doesn't exist), we try to get a label object to check if the label has been
41+
# created before we add (and create) it ourselves.
42+
def ensureLabels(pullRequest, repo):
3843
needsLabel = True
3944
targetPrefix = "Target: "
4045
targetLabel = f"{targetPrefix}{GITHUB_BASE_REF}"
46+
try:
47+
repo.get_label(targetLabel)
48+
except:
49+
print(f"Label '{targetLabel}' not found")
50+
return None
4151
for label in pullRequest.get_labels():
4252
if label.name.startswith(targetPrefix):
4353
if label.name == targetLabel:
4454
needsLabel = False
4555
else:
46-
print(f"Removing label '{label.name}")
56+
print(f"Removing label '{label.name}'")
4757
pullRequest.remove_from_labels(label)
4858
if needsLabel:
49-
print(f"Adding label '{targetLabel}")
59+
print(f"Adding label '{targetLabel}'")
5060
pullRequest.add_to_labels(targetLabel)
5161
return None
5262

@@ -56,4 +66,4 @@ def ensureLabels(pullRequest):
5666
repo = g.get_repo(GITHUB_REPOSITORY)
5767
prNum = int(PR_NUM)
5868
pr = repo.get_pull(prNum)
59-
ensureLabels(pr)
69+
ensureLabels(pr, repo)

0 commit comments

Comments
 (0)