forked from jaegertracing/jaeger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrelease-notes.py
executable file
·233 lines (190 loc) · 8.75 KB
/
release-notes.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#!/usr/bin/env python3
# This script can read N latest commits from one of Jaeger repos
# and output them in the release notes format:
# * {title} ({author} in {pull_request})
#
# Requires personal GitHub token with default permissions:
# https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token
#
# Usage: ./release-notes.py --help
#
import argparse
import json
import os.path
import urllib.parse
from os.path import expanduser
import sys
from urllib.request import (
urlopen,
Request
)
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def num_commits_since_prev_tag(token, base_url):
tags_url = f"{base_url}/tags"
trunk = "main"
req = Request(tags_url)
req.add_header("Authorization", f"token {token}")
tags = json.loads(urlopen(req).read())
prev_release_tag = tags[0]['name']
compare_url = f"{base_url}/compare/{trunk}...{prev_release_tag}"
req = Request(compare_url)
req.add_header("Authorization", f"token {token}")
compare_results = json.loads(urlopen(req).read())
num_commits = compare_results['behind_by']
print(f"There are {num_commits} new commits since {prev_release_tag}")
return num_commits
UNCATTEGORIZED = 'Uncategorized'
categories = [
{'title': '#### ⛔ Breaking Changes', 'label': 'changelog:breaking-change'},
{'title': '#### ✨ New Features', 'label': 'changelog:new-feature'},
{'title': '#### 🐞 Bug fixes, Minor Improvements', 'label': 'changelog:bugfix-or-minor-feature'},
{'title': '#### 🚧 Experimental Features', 'label': 'changelog:exprimental'},
{'title': '#### 👷 CI Improvements', 'label': 'changelog:ci'},
{'title': None, 'label': 'changelog:test'},
{'title': None, 'label': 'changelog:skip'},
{'title': None, 'label': 'changelog:dependencies'},
]
def categorize_pull_request(label):
for category, prefix in categories.items():
if label.startswith(prefix):
return category
return UNCATTEGORIZED # Default category if no matching prefix is found
def updateProgress(iteration, total_iterations):
progress = (iteration + 1) / total_iterations
percentage = progress * 100
sys.stdout.write('\r[' + '='*int(progress*50) + ' '*(50-int(progress*50)) + f'] {percentage:.2f}%')
sys.stdout.flush()
if iteration >= total_iterations - 1:
print()
return iteration + 1
def main(token, repo, num_commits, exclude_dependabot):
accept_header = "application/vnd.github.groot-preview+json"
base_url = f"https://api.github.com/repos/jaegertracing/{repo}"
commits_url = f"{base_url}/commits"
skipped_dependabot = 0
# If num_commits isn't set, get the number of commits made since the previous release tag.
if not num_commits:
num_commits = num_commits_since_prev_tag(token, base_url)
if not num_commits:
return
# Load commits
data = urllib.parse.urlencode({'per_page': num_commits})
req = Request(commits_url + '?' + data)
print(req.full_url)
req.add_header('Authorization', f'token {token}')
commits = json.loads(urlopen(req).read())
print('Retrieved', len(commits), 'commits')
# Load PR for each commit and print summary
category_results = {category['title']: [] for category in categories}
other_results = []
commits_with_multiple_labels = []
progress_iterator = 0
for commit in commits:
# Update the progress bar
progress_iterator = updateProgress(progress_iterator, num_commits)
sha = commit['sha']
author = commit['author']['login']
if exclude_dependabot and author == "dependabot[bot]":
skipped_dependabot += 1
continue
author_url = commit['author']['html_url']
msg_lines = commit['commit']['message'].split('\n')
msg = msg_lines[0].capitalize()
req = Request(f"{commits_url}/{sha}/pulls")
req.add_header('accept', accept_header)
req.add_header('Authorization', f'token {token}')
pulls = json.loads(urlopen(req).read())
if len(pulls) > 1:
print(f"WARNING: More than one pull request for commit {sha}")
# Handle commits without pull requests.
if not pulls:
short_sha = sha[:7]
commit_url = commit['html_url']
result = f'* {msg} ([@{author}]({author_url}) in [{short_sha}]({commit_url}))'
other_results.append(result)
continue
pull = pulls[0]
pull_id = pull['number']
pull_url = pull['html_url']
msg = msg.replace(f'(#{pull_id})', '').strip()
# Check if the pull request has changelog label
pull_labels = get_pull_request_labels(token, args.repo, pull_id)
changelog_labels = [label for label in pull_labels if label.startswith('changelog:')]
# Handle multiple changelog labels
if len(changelog_labels) > 1:
commits_with_multiple_labels.append((sha, pull_id, changelog_labels))
continue
category = UNCATTEGORIZED
if changelog_labels:
for cat in categories:
if changelog_labels[0].startswith(cat['label']):
category = cat['title']
break
result = f'* {msg} ([@{author}]({author_url}) in [#{pull_id}]({pull_url}))'
if category == UNCATTEGORIZED:
other_results.append(result)
else:
category_results[category].append(result)
# Print categorized pull requests
print()
print('### Backend Changes')
print()
for category, results in category_results.items():
if results and category:
print(f'{category}\n')
for result in results:
print(result)
print()
print()
print('### 📊 UI Changes')
print()
print('* UI pinned to version [x.y.z](https://github.com/jaegertracing/jaeger-ui/blob/main/CHANGELOG.md#---ANCHOR---).')
# Print pull requests in the 'UNCATTEGORIZED' category
if other_results:
print(f'#### 💩💩💩 The following commits cannot be categorized (missing changeglog labels):\n')
for result in other_results:
print(result)
print()
# Print warnings for commits with more than one changelog label
if commits_with_multiple_labels:
print("Warnings: Commits with more than one changelog label found. Please fix them:\n")
for sha, pull_id, labels in commits_with_multiple_labels:
pr_url = f"https://github.com/jaegertracing/{repo}/pull/{pull_id}"
print(f"Commit {sha} associated with multiple changelog labels: {', '.join(labels)}")
print(f"Pull Request URL: {pr_url}\n")
print()
if skipped_dependabot:
print(f"(Skipped dependabot commits: {skipped_dependabot})")
def get_pull_request_labels(token, repo, pull_number):
labels_url = f"https://api.github.com/repos/jaegertracing/{repo}/issues/{pull_number}/labels"
req = Request(labels_url)
req.add_header('Authorization', f'token {token}')
labels = json.loads(urlopen(req).read())
return [label['name'] for label in labels]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='List changes based on git log for release notes.')
parser.add_argument('--token-file', type=str, default="~/.github_token",
help='The file containing your personal github token to access the github API. ' +
'(default: ~/.github_token)')
parser.add_argument('--repo', type=str, default='jaeger',
help='The repository name to fetch commit logs from. (default: jaeger)')
parser.add_argument('--exclude-dependabot', action='store_true',
help='Excludes dependabot commits. (default: false)')
parser.add_argument('--num-commits', type=int,
help='Print this number of commits from git log. ' +
'(default: number of commits before the previous tag)')
args = parser.parse_args()
generate_token_url = "https://github.com/settings/tokens/new?description=GitHub%20Changelog%20Generator%20token"
generate_err_msg = (f"Please generate a token from this URL: {generate_token_url} and "
f"place it in the token-file. Protect the file so only you can read it: chmod 0600 <file>.")
token_file = expanduser(args.token_file)
if not os.path.exists(token_file):
eprint(f"No such token-file: {token_file}.\n{generate_err_msg}")
sys.exit(1)
with open(token_file, 'r') as file:
token = file.read().replace('\n', '')
if not token:
eprint(f"{token_file} is missing your personal github token.\n{generate_err_msg}")
sys.exit(1)
main(token, args.repo, args.num_commits, args.exclude_dependabot)