Skip to content

Commit dd2560e

Browse files
authored
Merge pull request #3607 from Flow-Launcher/add_release_pr_workflow
Add release PR workflow to auto update PR description
2 parents a06cb43 + ef84add commit dd2560e

File tree

2 files changed

+240
-0
lines changed

2 files changed

+240
-0
lines changed

.github/update_release_pr.py

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
from os import getenv
2+
3+
import requests
4+
5+
6+
def get_github_prs(token: str, owner: str, repo: str, label: str = "", state: str = "all") -> list[dict]:
7+
"""
8+
Fetches pull requests from a GitHub repository that match a given milestone and label.
9+
10+
Args:
11+
token (str): GitHub token.
12+
owner (str): The owner of the repository.
13+
repo (str): The name of the repository.
14+
label (str): The label name.
15+
state (str): State of PR, e.g. open, closed, all
16+
17+
Returns:
18+
list: A list of dictionaries, where each dictionary represents a pull request.
19+
Returns an empty list if no PRs are found or an error occurs.
20+
"""
21+
headers = {
22+
"Authorization": f"token {token}",
23+
"Accept": "application/vnd.github.v3+json",
24+
}
25+
26+
milestone_id = None
27+
milestone_url = f"https://api.github.com/repos/{owner}/{repo}/milestones"
28+
params = {"state": "open"}
29+
30+
try:
31+
response = requests.get(milestone_url, headers=headers, params=params)
32+
response.raise_for_status()
33+
milestones = response.json()
34+
35+
if len(milestones) > 2:
36+
print("More than two milestones found, unable to determine the milestone required.")
37+
exit(1)
38+
39+
# milestones.pop()
40+
for ms in milestones:
41+
if ms["title"] != "Future":
42+
milestone_id = ms["number"]
43+
print(f"Gathering PRs with milestone {ms['title']}...")
44+
break
45+
46+
if not milestone_id:
47+
print(f"No suitable milestone found in repository '{owner}/{repo}'.")
48+
exit(1)
49+
50+
except requests.exceptions.RequestException as e:
51+
print(f"Error fetching milestones: {e}")
52+
exit(1)
53+
54+
# This endpoint allows filtering by milestone and label. A PR in GH's perspective is a type of issue.
55+
prs_url = f"https://api.github.com/repos/{owner}/{repo}/issues"
56+
params = {
57+
"state": state,
58+
"milestone": milestone_id,
59+
"labels": label,
60+
"per_page": 100,
61+
}
62+
63+
all_prs = []
64+
page = 1
65+
while True:
66+
try:
67+
params["page"] = page
68+
response = requests.get(prs_url, headers=headers, params=params)
69+
response.raise_for_status() # Raise an exception for HTTP errors
70+
prs = response.json()
71+
72+
if not prs:
73+
break # No more PRs to fetch
74+
75+
# Check for pr key since we are using issues endpoint instead.
76+
all_prs.extend([item for item in prs if "pull_request" in item])
77+
page += 1
78+
79+
except requests.exceptions.RequestException as e:
80+
print(f"Error fetching pull requests: {e}")
81+
exit(1)
82+
83+
return all_prs
84+
85+
86+
def get_prs(pull_request_items: list[dict], label: str = "", state: str = "all") -> list[dict]:
87+
"""
88+
Returns a list of pull requests after applying the label and state filters.
89+
90+
Args:
91+
pull_request_items (list[dict]): List of PR items.
92+
label (str): The label name.
93+
state (str): State of PR, e.g. open, closed, all
94+
95+
Returns:
96+
list: A list of dictionaries, where each dictionary represents a pull request.
97+
Returns an empty list if no PRs are found.
98+
"""
99+
pr_list = []
100+
count = 0
101+
for pr in pull_request_items:
102+
if pr["state"] == state and [item for item in pr["labels"] if item["name"] == label]:
103+
pr_list.append(pr)
104+
count += 1
105+
106+
print(f"Found {count} PRs with {label if label else 'no'} label and state as {state}")
107+
108+
return pr_list
109+
110+
111+
def get_pr_descriptions(pull_request_items: list[dict]) -> str:
112+
"""
113+
Returns the concatenated string of pr title and number in the format of
114+
'- PR title 1 #3651
115+
- PR title 2 #3652
116+
- PR title 3 #3653
117+
'
118+
119+
Args:
120+
pull_request_items (list[dict]): List of PR items.
121+
122+
Returns:
123+
str: a string of PR titles and numbers
124+
"""
125+
description_content = ""
126+
for pr in pull_request_items:
127+
description_content += f"- {pr['title']} #{pr['number']}\n"
128+
129+
return description_content
130+
131+
132+
def update_pull_request_description(token: str, owner: str, repo: str, pr_number: int, new_description: str) -> None:
133+
"""
134+
Updates the description (body) of a GitHub Pull Request.
135+
136+
Args:
137+
token (str): Token.
138+
owner (str): The owner of the repository.
139+
repo (str): The name of the repository.
140+
pr_number (int): The number of the pull request to update.
141+
new_description (str): The new content for the PR's description.
142+
143+
Returns:
144+
dict or None: The updated PR object (as a dictionary) if successful,
145+
None otherwise.
146+
"""
147+
headers = {
148+
"Authorization": f"token {token}",
149+
"Accept": "application/vnd.github.v3+json",
150+
"Content-Type": "application/json",
151+
}
152+
153+
url = f"https://api.github.com/repos/{owner}/{repo}/pulls/{pr_number}"
154+
155+
payload = {"body": new_description}
156+
157+
print(f"Attempting to update PR #{pr_number} in {owner}/{repo}...")
158+
print(f"URL: {url}")
159+
160+
try:
161+
response = None
162+
response = requests.patch(url, headers=headers, json=payload)
163+
response.raise_for_status()
164+
165+
print(f"Successfully updated PR #{pr_number}.")
166+
167+
except requests.exceptions.RequestException as e:
168+
print(f"Error updating pull request #{pr_number}: {e}")
169+
if response is not None:
170+
print(f"Response status code: {response.status_code}")
171+
print(f"Response text: {response.text}")
172+
exit(1)
173+
174+
175+
if __name__ == "__main__":
176+
github_token = getenv("GITHUB_TOKEN")
177+
178+
if not github_token:
179+
print("Error: GITHUB_TOKEN environment variable not set.")
180+
exit(1)
181+
182+
repository_owner = "flow-launcher"
183+
repository_name = "flow.launcher"
184+
state = "all"
185+
186+
print(f"Fetching {state} PRs for {repository_owner}/{repository_name} ...")
187+
188+
pull_requests = get_github_prs(github_token, repository_owner, repository_name)
189+
190+
if not pull_requests:
191+
print("No matching pull requests found")
192+
exit(1)
193+
194+
print(f"\nFound total of {len(pull_requests)} pull requests")
195+
196+
release_pr = get_prs(pull_requests, "release", "open")
197+
198+
if len(release_pr) != 1:
199+
print(f"Unable to find the exact release PR. Returned result: {release_pr}")
200+
exit(1)
201+
202+
print(f"Found release PR: {release_pr[0]['title']}")
203+
204+
enhancement_prs = get_prs(pull_requests, "enhancement", "closed")
205+
bug_fix_prs = get_prs(pull_requests, "bug", "closed")
206+
207+
description_content = "# Release notes\n"
208+
description_content += f"## Features\n{get_pr_descriptions(enhancement_prs)}" if enhancement_prs else ""
209+
description_content += f"## Bug fixes\n{get_pr_descriptions(bug_fix_prs)}" if bug_fix_prs else ""
210+
211+
update_pull_request_description(
212+
github_token, repository_owner, repository_name, release_pr[0]["number"], description_content
213+
)
214+
215+
print(f"PR content updated to:\n{description_content}")

.github/workflows/release_pr.yml

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
name: Update release PR
2+
3+
on:
4+
pull_request:
5+
types: [opened, reopened, synchronize]
6+
branches:
7+
- master
8+
workflow_dispatch:
9+
10+
jobs:
11+
update-pr:
12+
runs-on: ubuntu-latest
13+
steps:
14+
- uses: actions/checkout@v4
15+
16+
- uses: actions/setup-python@v5
17+
with:
18+
python-version: "3.x"
19+
20+
- name: Run release PR update
21+
env:
22+
GITHUB_TOKEN: ${{ secrets.PR_TOKEN }}
23+
run: |
24+
pip install requests -q
25+
python3 ./.github/update_release_pr.py

0 commit comments

Comments
 (0)