This repository has been archived by the owner on Jul 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
142 lines (117 loc) · 5.35 KB
/
main.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
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
import os
import re
import requests
import json
from github import Github
class MissingEnvironmentVariable(Exception):
pass
def main():
""" Main function """
""" Get environment variables """
print("Fetching environment variables...")
token = os.environ['INPUT_TOKEN']
if not token:
raise MissingEnvironmentVariable("`token` environment variable not found")
try:
repository = os.environ['INPUT_REPOSITORY']
except KeyError:
raise MissingEnvironmentVariable("`repository` environment variable not found")
try:
pull_request_number = os.environ['INPUT_PULL-REQUEST-NUMBER']
except KeyError:
raise MissingEnvironmentVariable("`pull-request-number` environment variable not found")
try:
pull_request_body = os.environ['INPUT_PULL-REQUEST-BODY']
except KeyError:
raise MissingEnvironmentVariable("`pull-request-body` environment variable not found")
try:
copy_issues_labels = os.environ['INPUT_COPY-ISSUES-LABELS']
except KeyError:
copy_issues_labels = False
try:
include_closed_issues = os.environ['INPUT_INCLUDE-CLOSED-ISSUES']
except KeyError:
include_closed_issues = False
if include_closed_issues:
is_open = ""
else:
is_open = "is:open"
print("Environment variables fetched successfully")
""" Get pull request """
print("Finding issue numbers in pull requests body..")
print(f"Pull request body: {pull_request_body}")
pattern = re.compile(r"(((.lose|.ix|.esolve)(\S*|\s*))(.|)\#\d+)", re.VERBOSE)
matches = re.findall(pattern, pull_request_body)
print(f"Matches: {matches}")
if not matches:
raise RuntimeError("No regex matches found in the body!")
issue_numbers = []
for match in matches:
for entry in match:
print(f"entry: {entry}")
if "#" not in entry:
print(f"Skipping {entry}")
else:
print(f"Found {entry}")
index = entry.index("#")
issue_number = entry[index + 1:]
issue_numbers.append(issue_number)
print(f"Found issue number: {issue_number}")
if not issue_numbers:
raise RuntimeError("No issue found in the regex matches!")
print(f"Issue numbers: {issue_numbers}")
""" Find issues with GitHub API """
print("Fetching issues...")
url = "https://api.github.com/search/issues?q=" \
+ f"repo:{repository} is:issue {is_open} linked:pr pr:{pull_request_number} " \
+ " ".join(str(i) for i in issue_numbers)
print(f"Request url: {url}")
headers = {
"Accept": "application/vnd.github+json"
}
response = requests.get(url, headers=headers)
if response.status_code != 200:
with open(os.environ['GITHUB_OUTPUT'], 'a') as fh:
print(f"is-pull-request-linked-to-issues={False}", file=fh)
raise RuntimeError(f"Error fetching issues: {json.dumps(response.json(), indent=2)}")
response_json = response.json()
print(json.dumps(response_json, indent=2))
if response_json["total_count"] == 0:
with open(os.environ['GITHUB_OUTPUT'], 'a') as fh:
print(f"is-pull-request-linked-to-issues={False}", file=fh)
raise RuntimeError("Error fetching issues, 'total_response' = 0")
github = Github(token)
pull_request_labels = [label.name for label in github.get_repo(repository).get_pull(
int(pull_request_number)).get_labels()]
print(f"Pull request labels: {pull_request_labels}")
response_json_issue_numbers = []
for item in response_json["items"]:
print(f"item: {json.dumps(item, indent=2)}")
print(f"item['number']: {item['number']}")
if str(item["number"]) in issue_numbers:
response_json_issue_numbers.append(item["number"])
print(f"Found issue number: {item['number']}")
""" Copy labels from issues to pull request """
if copy_issues_labels:
print("Copying labels from issues to pull request...")
for label in item["labels"]:
if label["name"] and label["name"] not in pull_request_labels:
print(f"Adding label: {label['name']}")
github.get_repo(repository).get_pull(int(pull_request_number)).add_to_labels(str(label["name"]))
print(f"Found and added issue label: {label['name']}")
print("Labels copied successfully")
if not response_json_issue_numbers:
with open(os.environ['GITHUB_OUTPUT'], 'a') as fh:
print(f"is-pull-request-linked-to-issues={False}", file=fh)
raise RuntimeError(f"Error fetching issues, didn't find issue number in response: {response_json}")
print(f"Issues fetched successfully: {response_json_issue_numbers}")
with open(os.environ['GITHUB_OUTPUT'], 'a') as fh:
print(f"is-pull-request-linked-to-issues={True}", file=fh)
with open(os.environ['GITHUB_OUTPUT'], 'a') as fh:
print(f"linked-issues={response_json_issue_numbers}", file=fh)
with open(os.environ['GITHUB_OUTPUT'], 'a') as fh:
pull_request_labels = [label.name for label in github.get_repo(repository).get_pull(
int(pull_request_number)).get_labels()]
print(f"pull-request-labels={pull_request_labels}", file=fh)
if __name__ == "__main__":
main()