blob: cb049f5d99650c863bb5c0bb184054abb15ba21b [file] [log] [blame]
Simon Glass3db916d2020-10-29 21:46:35 -06001# SPDX-License-Identifier: GPL-2.0+
2#
3# Copyright 2020 Google LLC
4#
5"""Talks to the patchwork service to figure out what patches have been reviewed
Simon Glass2112d072020-10-29 21:46:38 -06006and commented on. Provides a way to display review tags and comments.
7Allows creation of a new branch based on the old but with the review tags
8collected from patchwork.
Simon Glass3db916d2020-10-29 21:46:35 -06009"""
10
11import collections
12import concurrent.futures
13from itertools import repeat
Simon Glassd0a0a582020-10-29 21:46:36 -060014
15import pygit2
Simon Glass3db916d2020-10-29 21:46:35 -060016import requests
17
Simon Glass131444f2023-02-23 18:18:04 -070018from u_boot_pylib import terminal
19from u_boot_pylib import tout
Simon Glass232eefd2025-04-29 07:22:14 -060020from patman import patchstream
21from patman import patchwork
22from patman.patchstream import PatchStream
Simon Glass3db916d2020-10-29 21:46:35 -060023
Simon Glass3db916d2020-10-29 21:46:35 -060024
25def to_int(vals):
26 """Convert a list of strings into integers, using 0 if not an integer
27
28 Args:
29 vals (list): List of strings
30
31 Returns:
32 list: List of integers, one for each input string
33 """
34 out = [int(val) if val.isdigit() else 0 for val in vals]
35 return out
36
Simon Glass2112d072020-10-29 21:46:38 -060037
Simon Glass3db916d2020-10-29 21:46:35 -060038def compare_with_series(series, patches):
39 """Compare a list of patches with a series it came from
40
41 This prints any problems as warnings
42
43 Args:
44 series (Series): Series to compare against
45 patches (:type: list of Patch): list of Patch objects to compare with
46
47 Returns:
48 tuple
49 dict:
50 key: Commit number (0...n-1)
51 value: Patch object for that commit
52 dict:
53 key: Patch number (0...n-1)
54 value: Commit object for that patch
55 """
56 # Check the names match
57 warnings = []
58 patch_for_commit = {}
59 all_patches = set(patches)
60 for seq, cmt in enumerate(series.commits):
61 pmatch = [p for p in all_patches if p.subject == cmt.subject]
62 if len(pmatch) == 1:
63 patch_for_commit[seq] = pmatch[0]
64 all_patches.remove(pmatch[0])
65 elif len(pmatch) > 1:
66 warnings.append("Multiple patches match commit %d ('%s'):\n %s" %
67 (seq + 1, cmt.subject,
68 '\n '.join([p.subject for p in pmatch])))
69 else:
70 warnings.append("Cannot find patch for commit %d ('%s')" %
71 (seq + 1, cmt.subject))
72
73
74 # Check the names match
75 commit_for_patch = {}
76 all_commits = set(series.commits)
77 for seq, patch in enumerate(patches):
78 cmatch = [c for c in all_commits if c.subject == patch.subject]
79 if len(cmatch) == 1:
80 commit_for_patch[seq] = cmatch[0]
81 all_commits.remove(cmatch[0])
82 elif len(cmatch) > 1:
83 warnings.append("Multiple commits match patch %d ('%s'):\n %s" %
84 (seq + 1, patch.subject,
85 '\n '.join([c.subject for c in cmatch])))
86 else:
87 warnings.append("Cannot find commit for patch %d ('%s')" %
88 (seq + 1, patch.subject))
89
90 return patch_for_commit, commit_for_patch, warnings
91
Simon Glassf9b03cf2020-11-03 13:54:14 -070092def call_rest_api(url, subpath):
Simon Glass3db916d2020-10-29 21:46:35 -060093 """Call the patchwork API and return the result as JSON
94
95 Args:
Simon Glassf9b03cf2020-11-03 13:54:14 -070096 url (str): URL of patchwork server, e.g. 'https://patchwork.ozlabs.org'
Simon Glass3db916d2020-10-29 21:46:35 -060097 subpath (str): URL subpath to use
98
99 Returns:
100 dict: Json result
101
102 Raises:
103 ValueError: the URL could not be read
104 """
Simon Glassf9b03cf2020-11-03 13:54:14 -0700105 full_url = '%s/api/1.2/%s' % (url, subpath)
106 response = requests.get(full_url)
Simon Glass3db916d2020-10-29 21:46:35 -0600107 if response.status_code != 200:
Simon Glassf9b03cf2020-11-03 13:54:14 -0700108 raise ValueError("Could not read URL '%s'" % full_url)
Simon Glass3db916d2020-10-29 21:46:35 -0600109 return response.json()
110
Simon Glass27280f42025-04-29 07:22:17 -0600111def collect_patches(series_id, url, rest_api=call_rest_api):
Simon Glass3db916d2020-10-29 21:46:35 -0600112 """Collect patch information about a series from patchwork
113
114 Uses the Patchwork REST API to collect information provided by patchwork
115 about the status of each patch.
116
117 Args:
Simon Glass3db916d2020-10-29 21:46:35 -0600118 series_id (str): Patch series ID number
Simon Glassf9b03cf2020-11-03 13:54:14 -0700119 url (str): URL of patchwork server, e.g. 'https://patchwork.ozlabs.org'
Simon Glass3db916d2020-10-29 21:46:35 -0600120 rest_api (function): API function to call to access Patchwork, for
121 testing
122
123 Returns:
Simon Glass27280f42025-04-29 07:22:17 -0600124 list of Patch: List of patches sorted by sequence number
Simon Glass3db916d2020-10-29 21:46:35 -0600125
126 Raises:
127 ValueError: if the URL could not be read or the web page does not follow
128 the expected structure
129 """
Simon Glassf9b03cf2020-11-03 13:54:14 -0700130 data = rest_api(url, 'series/%s/' % series_id)
Simon Glass3db916d2020-10-29 21:46:35 -0600131
132 # Get all the rows, which are patches
133 patch_dict = data['patches']
134 count = len(patch_dict)
Simon Glass3db916d2020-10-29 21:46:35 -0600135
136 patches = []
137
138 # Work through each row (patch) one at a time, collecting the information
139 warn_count = 0
140 for pw_patch in patch_dict:
Simon Glass232eefd2025-04-29 07:22:14 -0600141 patch = patchwork.Patch(pw_patch['id'])
Simon Glass3db916d2020-10-29 21:46:35 -0600142 patch.parse_subject(pw_patch['name'])
143 patches.append(patch)
144 if warn_count > 1:
Simon Glass011f1b32022-01-29 14:14:15 -0700145 tout.warning(' (total of %d warnings)' % warn_count)
Simon Glass3db916d2020-10-29 21:46:35 -0600146
147 # Sort patches by patch number
148 patches = sorted(patches, key=lambda x: x.seq)
149 return patches
150
Simon Glassf9b03cf2020-11-03 13:54:14 -0700151def find_new_responses(new_rtag_list, review_list, seq, cmt, patch, url,
Simon Glass2112d072020-10-29 21:46:38 -0600152 rest_api=call_rest_api):
Simon Glass3db916d2020-10-29 21:46:35 -0600153 """Find new rtags collected by patchwork that we don't know about
154
155 This is designed to be run in parallel, once for each commit/patch
156
157 Args:
158 new_rtag_list (list): New rtags are written to new_rtag_list[seq]
159 list, each a dict:
160 key: Response tag (e.g. 'Reviewed-by')
161 value: Set of people who gave that response, each a name/email
162 string
Simon Glass2112d072020-10-29 21:46:38 -0600163 review_list (list): New reviews are written to review_list[seq]
164 list, each a
165 List of reviews for the patch, each a Review
Simon Glass3db916d2020-10-29 21:46:35 -0600166 seq (int): Position in new_rtag_list to update
167 cmt (Commit): Commit object for this commit
168 patch (Patch): Corresponding Patch object for this patch
Simon Glassf9b03cf2020-11-03 13:54:14 -0700169 url (str): URL of patchwork server, e.g. 'https://patchwork.ozlabs.org'
Simon Glass3db916d2020-10-29 21:46:35 -0600170 rest_api (function): API function to call to access Patchwork, for
171 testing
172 """
173 if not patch:
174 return
175
176 # Get the content for the patch email itself as well as all comments
Simon Glassf9b03cf2020-11-03 13:54:14 -0700177 data = rest_api(url, 'patches/%s/' % patch.id)
Simon Glass3db916d2020-10-29 21:46:35 -0600178 pstrm = PatchStream.process_text(data['content'], True)
179
180 rtags = collections.defaultdict(set)
181 for response, people in pstrm.commit.rtags.items():
182 rtags[response].update(people)
183
Simon Glassf9b03cf2020-11-03 13:54:14 -0700184 data = rest_api(url, 'patches/%s/comments/' % patch.id)
Simon Glass3db916d2020-10-29 21:46:35 -0600185
Simon Glass2112d072020-10-29 21:46:38 -0600186 reviews = []
Simon Glass3db916d2020-10-29 21:46:35 -0600187 for comment in data:
188 pstrm = PatchStream.process_text(comment['content'], True)
Simon Glass2112d072020-10-29 21:46:38 -0600189 if pstrm.snippets:
190 submitter = comment['submitter']
191 person = '%s <%s>' % (submitter['name'], submitter['email'])
Simon Glass232eefd2025-04-29 07:22:14 -0600192 reviews.append(patchwork.Review(person, pstrm.snippets))
Simon Glass3db916d2020-10-29 21:46:35 -0600193 for response, people in pstrm.commit.rtags.items():
194 rtags[response].update(people)
195
196 # Find the tags that are not in the commit
197 new_rtags = collections.defaultdict(set)
198 base_rtags = cmt.rtags
199 for tag, people in rtags.items():
200 for who in people:
201 is_new = (tag not in base_rtags or
202 who not in base_rtags[tag])
203 if is_new:
204 new_rtags[tag].add(who)
205 new_rtag_list[seq] = new_rtags
Simon Glass2112d072020-10-29 21:46:38 -0600206 review_list[seq] = reviews
Simon Glass3db916d2020-10-29 21:46:35 -0600207
208def show_responses(rtags, indent, is_new):
209 """Show rtags collected
210
211 Args:
212 rtags (dict): review tags to show
213 key: Response tag (e.g. 'Reviewed-by')
214 value: Set of people who gave that response, each a name/email string
215 indent (str): Indentation string to write before each line
216 is_new (bool): True if this output should be highlighted
217
218 Returns:
219 int: Number of review tags displayed
220 """
221 col = terminal.Color()
222 count = 0
Simon Glass2112d072020-10-29 21:46:38 -0600223 for tag in sorted(rtags.keys()):
224 people = rtags[tag]
225 for who in sorted(people):
Simon Glass02811582022-01-29 14:14:18 -0700226 terminal.tprint(indent + '%s %s: ' % ('+' if is_new else ' ', tag),
Simon Glass3db916d2020-10-29 21:46:35 -0600227 newline=False, colour=col.GREEN, bright=is_new)
Simon Glass02811582022-01-29 14:14:18 -0700228 terminal.tprint(who, colour=col.WHITE, bright=is_new)
Simon Glass3db916d2020-10-29 21:46:35 -0600229 count += 1
230 return count
231
Simon Glassd0a0a582020-10-29 21:46:36 -0600232def create_branch(series, new_rtag_list, branch, dest_branch, overwrite,
233 repo=None):
234 """Create a new branch with review tags added
235
236 Args:
237 series (Series): Series object for the existing branch
238 new_rtag_list (list): List of review tags to add, one for each commit,
239 each a dict:
240 key: Response tag (e.g. 'Reviewed-by')
241 value: Set of people who gave that response, each a name/email
242 string
243 branch (str): Existing branch to update
244 dest_branch (str): Name of new branch to create
245 overwrite (bool): True to force overwriting dest_branch if it exists
246 repo (pygit2.Repository): Repo to use (use None unless testing)
247
248 Returns:
249 int: Total number of review tags added across all commits
250
251 Raises:
252 ValueError: if the destination branch name is the same as the original
253 branch, or it already exists and @overwrite is False
254 """
255 if branch == dest_branch:
256 raise ValueError(
257 'Destination branch must not be the same as the original branch')
258 if not repo:
259 repo = pygit2.Repository('.')
260 count = len(series.commits)
261 new_br = repo.branches.get(dest_branch)
262 if new_br:
263 if not overwrite:
264 raise ValueError("Branch '%s' already exists (-f to overwrite)" %
265 dest_branch)
266 new_br.delete()
267 if not branch:
268 branch = 'HEAD'
269 target = repo.revparse_single('%s~%d' % (branch, count))
270 repo.branches.local.create(dest_branch, target)
271
272 num_added = 0
273 for seq in range(count):
274 parent = repo.branches.get(dest_branch)
275 cherry = repo.revparse_single('%s~%d' % (branch, count - seq - 1))
276
277 repo.merge_base(cherry.oid, parent.target)
278 base_tree = cherry.parents[0].tree
279
280 index = repo.merge_trees(base_tree, parent, cherry)
281 tree_id = index.write_tree(repo)
282
283 lines = []
284 if new_rtag_list[seq]:
285 for tag, people in new_rtag_list[seq].items():
286 for who in people:
287 lines.append('%s: %s' % (tag, who))
288 num_added += 1
289 message = patchstream.insert_tags(cherry.message.rstrip(),
290 sorted(lines))
291
292 repo.create_commit(
293 parent.name, cherry.author, cherry.committer, message, tree_id,
294 [parent.target])
295 return num_added
296
Simon Glass27280f42025-04-29 07:22:17 -0600297def check_status(series, series_id, url, rest_api=call_rest_api):
Simon Glass3db916d2020-10-29 21:46:35 -0600298 """Check the status of a series on Patchwork
299
300 This finds review tags and comments for a series in Patchwork, displaying
301 them to show what is new compared to the local series.
302
303 Args:
304 series (Series): Series object for the existing branch
305 series_id (str): Patch series ID number
Simon Glassf9b03cf2020-11-03 13:54:14 -0700306 url (str): URL of patchwork server, e.g. 'https://patchwork.ozlabs.org'
Simon Glass3db916d2020-10-29 21:46:35 -0600307 rest_api (function): API function to call to access Patchwork, for
308 testing
Simon Glass27280f42025-04-29 07:22:17 -0600309
310 Return:
311 tuple:
312 list of Patch: List of patches sorted by sequence number
313 dict: Patches for commit
314 key: Commit number (0...n-1)
315 value: Patch object for that commit
316 list of dict: review tags:
317 key: Response tag (e.g. 'Reviewed-by')
318 value: Set of people who gave that response, each a name/email
319 string
320 list for each patch, each a:
321 list of Review objects for the patch
Simon Glass3db916d2020-10-29 21:46:35 -0600322 """
Simon Glass27280f42025-04-29 07:22:17 -0600323 patches = collect_patches(series_id, url, rest_api)
Simon Glass3db916d2020-10-29 21:46:35 -0600324 count = len(series.commits)
325 new_rtag_list = [None] * count
Simon Glass2112d072020-10-29 21:46:38 -0600326 review_list = [None] * count
Simon Glass3db916d2020-10-29 21:46:35 -0600327
328 patch_for_commit, _, warnings = compare_with_series(series, patches)
329 for warn in warnings:
Simon Glass011f1b32022-01-29 14:14:15 -0700330 tout.warning(warn)
Simon Glass3db916d2020-10-29 21:46:35 -0600331
332 patch_list = [patch_for_commit.get(c) for c in range(len(series.commits))]
333
334 with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
335 futures = executor.map(
Simon Glass2112d072020-10-29 21:46:38 -0600336 find_new_responses, repeat(new_rtag_list), repeat(review_list),
Simon Glassf9b03cf2020-11-03 13:54:14 -0700337 range(count), series.commits, patch_list, repeat(url),
338 repeat(rest_api))
Simon Glass3db916d2020-10-29 21:46:35 -0600339 for fresponse in futures:
340 if fresponse:
341 raise fresponse.exception()
Simon Glass27280f42025-04-29 07:22:17 -0600342 return patches, patch_for_commit, new_rtag_list, review_list
Simon Glass3db916d2020-10-29 21:46:35 -0600343
Simon Glass27280f42025-04-29 07:22:17 -0600344
345def check_patch_count(num_commits, num_patches):
346 """Check the number of commits and patches agree
347
348 Args:
349 num_commits (int): Number of commits
350 num_patches (int): Number of patches
351 """
352 if num_patches != num_commits:
353 tout.warning(f'Warning: Patchwork reports {num_patches} patches, '
354 f'series has {num_commits}')
355
356
357def do_show_status(series, patch_for_commit, show_comments, new_rtag_list,
358 review_list, col):
Simon Glass3db916d2020-10-29 21:46:35 -0600359 num_to_add = 0
360 for seq, cmt in enumerate(series.commits):
361 patch = patch_for_commit.get(seq)
362 if not patch:
363 continue
Simon Glass02811582022-01-29 14:14:18 -0700364 terminal.tprint('%3d %s' % (patch.seq, patch.subject[:50]),
Simon Glass3db916d2020-10-29 21:46:35 -0600365 colour=col.BLUE)
366 cmt = series.commits[seq]
367 base_rtags = cmt.rtags
368 new_rtags = new_rtag_list[seq]
369
370 indent = ' ' * 2
371 show_responses(base_rtags, indent, False)
372 num_to_add += show_responses(new_rtags, indent, True)
Simon Glass2112d072020-10-29 21:46:38 -0600373 if show_comments:
374 for review in review_list[seq]:
Simon Glass02811582022-01-29 14:14:18 -0700375 terminal.tprint('Review: %s' % review.meta, colour=col.RED)
Simon Glass2112d072020-10-29 21:46:38 -0600376 for snippet in review.snippets:
377 for line in snippet:
378 quoted = line.startswith('>')
Simon Glass02811582022-01-29 14:14:18 -0700379 terminal.tprint(' %s' % line,
Simon Glass2112d072020-10-29 21:46:38 -0600380 colour=col.MAGENTA if quoted else None)
Simon Glass02811582022-01-29 14:14:18 -0700381 terminal.tprint()
Simon Glass27280f42025-04-29 07:22:17 -0600382 return num_to_add
383
384
385def show_status(series, branch, dest_branch, force, patches, patch_for_commit,
386 show_comments, new_rtag_list, review_list, test_repo=None):
387 """Show status to the user and allow a branch to be written
388
389 Args:
390 series (Series): Series object for the existing branch
391 branch (str): Existing branch to update, or None
392 dest_branch (str): Name of new branch to create, or None
393 force (bool): True to force overwriting dest_branch if it exists
394 patches (list of Patch): Patches sorted by sequence number
395 patch_for_commit (dict): Patches for commit
396 key: Commit number (0...n-1)
397 value: Patch object for that commit
398 show_comments (bool): True to show patch comments
399 new_rtag_list (list of dict) review tags for each patch:
400 key: Response tag (e.g. 'Reviewed-by')
401 value: Set of people who gave that response, each a name/email
402 string
403 review_list (list of list): list for each patch, each a:
404 list of Review objects for the patch
405 test_repo (pygit2.Repository): Repo to use (use None unless testing)
406 """
407 col = terminal.Color()
408 check_patch_count(len(series.commits), len(patches))
409 num_to_add = do_show_status(series, patch_for_commit, show_comments,
410 new_rtag_list, review_list, col)
Simon Glass3db916d2020-10-29 21:46:35 -0600411
Simon Glass02811582022-01-29 14:14:18 -0700412 terminal.tprint("%d new response%s available in patchwork%s" %
Simon Glassd0a0a582020-10-29 21:46:36 -0600413 (num_to_add, 's' if num_to_add != 1 else '',
414 '' if dest_branch
415 else ' (use -d to write them to a new branch)'))
416
417 if dest_branch:
Simon Glass27280f42025-04-29 07:22:17 -0600418 num_added = create_branch(series, new_rtag_list, branch, dest_branch,
419 force, test_repo)
Simon Glass02811582022-01-29 14:14:18 -0700420 terminal.tprint(
Simon Glassd0a0a582020-10-29 21:46:36 -0600421 "%d response%s added from patchwork into new branch '%s'" %
422 (num_added, 's' if num_added != 1 else '', dest_branch))
Simon Glass27280f42025-04-29 07:22:17 -0600423
424
425def check_and_show_status(series, link, branch, dest_branch, force,
426 show_comments, url, rest_api=call_rest_api,
427 test_repo=None):
428 """Read the series status from patchwork and show it to the user
429
430 Args:
431 series (Series): Series object for the existing branch
432 link (str): Patch series ID number
433 branch (str): Existing branch to update, or None
434 dest_branch (str): Name of new branch to create, or None
435 force (bool): True to force overwriting dest_branch if it exists
436 show_comments (bool): True to show patch comments
437 url (str): URL of patchwork server, e.g. 'https://patchwork.ozlabs.org'
438 rest_api (function): API function to call to access Patchwork, for
439 testing
440 test_repo (pygit2.Repository): Repo to use (use None unless testing)
441 """
442 patches, patch_for_commit, new_rtag_list, review_list = check_status(
443 series, link, url, rest_api)
444 show_status(series, branch, dest_branch, force, patches, patch_for_commit,
445 show_comments, new_rtag_list, review_list, test_repo)