|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +""" |
| 4 | +
|
| 5 | +The script applies a label in the form "Target: {branchName}. If necessary, it |
| 6 | +removes labels in the same form, but NOT for the target branch. For instance, if |
| 7 | +someone edited the target branch from v4.0.x to v5.0.x |
| 8 | +
|
| 9 | +""" |
| 10 | + |
| 11 | +import os |
| 12 | +import re |
| 13 | +import sys |
| 14 | + |
| 15 | +from github import Github |
| 16 | + |
| 17 | +# ============================================================================== |
| 18 | + |
| 19 | +GITHUB_BASE_REF = os.environ.get('GITHUB_BASE_REF') |
| 20 | +GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN') |
| 21 | +GITHUB_REPOSITORY = os.environ.get('GITHUB_REPOSITORY') |
| 22 | +PR_NUM = os.environ.get('PR_NUM') |
| 23 | + |
| 24 | +# Sanity check |
| 25 | +if (GITHUB_BASE_REF is None or |
| 26 | + GITHUB_TOKEN is None or |
| 27 | + GITHUB_REPOSITORY is None or |
| 28 | + PR_NUM is None): |
| 29 | + print("Error: this script is designed to run as a Github Action") |
| 30 | + exit(1) |
| 31 | + |
| 32 | +# ============================================================================== |
| 33 | + |
| 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): |
| 38 | + needsLabel = True |
| 39 | + targetPrefix = "Target: " |
| 40 | + targetLabel = f"{targetPrefix}{GITHUB_BASE_REF}" |
| 41 | + for label in pullRequest.get_labels(): |
| 42 | + if label.name.startswith(targetPrefix): |
| 43 | + if label.name == targetLabel: |
| 44 | + needsLabel = False |
| 45 | + else: |
| 46 | + print(f"Removing label '{label.name}") |
| 47 | + pullRequest.remove_from_labels(label) |
| 48 | + if needsLabel: |
| 49 | + print(f"Adding label '{targetLabel}") |
| 50 | + pullRequest.add_to_labels(targetLabel) |
| 51 | + return None |
| 52 | + |
| 53 | +# ============================================================================== |
| 54 | + |
| 55 | +g = Github(GITHUB_TOKEN) |
| 56 | +repo = g.get_repo(GITHUB_REPOSITORY) |
| 57 | +prNum = int(PR_NUM) |
| 58 | +pr = repo.get_pull(prNum) |
| 59 | +ensureLabels(pr) |
0 commit comments