blob: e0adbdb64818c6b3e58554db305eda777c327751 [file] [log] [blame]
Simon Glass2c266d82025-04-29 07:22:13 -06001# SPDX-License-Identifier: GPL-2.0+
2#
3# Copyright 2025 Simon Glass <sjg@chromium.org>
4#
5"""Provides a basic API for the patchwork server
6"""
7
8import asyncio
Simon Glass232eefd2025-04-29 07:22:14 -06009import re
Simon Glass2c266d82025-04-29 07:22:13 -060010
11import aiohttp
12
13# Number of retries
14RETRIES = 3
15
16# Max concurrent request
17MAX_CONCURRENT = 50
18
Simon Glass232eefd2025-04-29 07:22:14 -060019# Patches which are part of a multi-patch series are shown with a prefix like
20# [prefix, version, sequence], for example '[RFC, v2, 3/5]'. All but the last
21# part is optional. This decodes the string into groups. For single patches
22# the [] part is not present:
23# Groups: (ignore, ignore, ignore, prefix, version, sequence, subject)
24RE_PATCH = re.compile(r'(\[(((.*),)?(.*),)?(.*)\]\s)?(.*)$')
25
26# This decodes the sequence string into a patch number and patch count
27RE_SEQ = re.compile(r'(\d+)/(\d+)')
28
29
30class Patch(dict):
31 """Models a patch in patchwork
32
33 This class records information obtained from patchwork
34
35 Some of this information comes from the 'Patch' column:
36
37 [RFC,v2,1/3] dm: Driver and uclass changes for tiny-dm
38
39 This shows the prefix, version, seq, count and subject.
40
41 The other properties come from other columns in the display.
42
43 Properties:
44 pid (str): ID of the patch (typically an integer)
45 seq (int): Sequence number within series (1=first) parsed from sequence
46 string
47 count (int): Number of patches in series, parsed from sequence string
48 raw_subject (str): Entire subject line, e.g.
49 "[1/2,v2] efi_loader: Sort header file ordering"
50 prefix (str): Prefix string or None (e.g. 'RFC')
51 version (str): Version string or None (e.g. 'v2')
52 raw_subject (str): Raw patch subject
53 subject (str): Patch subject with [..] part removed (same as commit
54 subject)
55 """
56 def __init__(self, pid):
57 super().__init__()
58 self.id = pid # Use 'id' to match what the Rest API provides
59 self.seq = None
60 self.count = None
61 self.prefix = None
62 self.version = None
63 self.raw_subject = None
64 self.subject = None
65
66 # These make us more like a dictionary
67 def __setattr__(self, name, value):
68 self[name] = value
69
70 def __getattr__(self, name):
71 return self[name]
72
73 def __hash__(self):
74 return hash(frozenset(self.items()))
75
76 def __str__(self):
77 return self.raw_subject
78
79 def parse_subject(self, raw_subject):
80 """Parse the subject of a patch into its component parts
81
82 See RE_PATCH for details. The parsed info is placed into seq, count,
83 prefix, version, subject
84
85 Args:
86 raw_subject (str): Subject string to parse
87
88 Raises:
89 ValueError: the subject cannot be parsed
90 """
91 self.raw_subject = raw_subject.strip()
92 mat = RE_PATCH.search(raw_subject.strip())
93 if not mat:
94 raise ValueError(f"Cannot parse subject '{raw_subject}'")
95 self.prefix, self.version, seq_info, self.subject = mat.groups()[3:]
96 mat_seq = RE_SEQ.match(seq_info) if seq_info else False
97 if mat_seq is None:
98 self.version = seq_info
99 seq_info = None
100 if self.version and not self.version.startswith('v'):
101 self.prefix = self.version
102 self.version = None
103 if seq_info:
104 if mat_seq:
105 self.seq = int(mat_seq.group(1))
106 self.count = int(mat_seq.group(2))
107 else:
108 self.seq = 1
109 self.count = 1
110
111
112class Review:
113 """Represents a single review email collected in Patchwork
114
115 Patches can attract multiple reviews. Each consists of an author/date and
116 a variable number of 'snippets', which are groups of quoted and unquoted
117 text.
118 """
119 def __init__(self, meta, snippets):
120 """Create new Review object
121
122 Args:
123 meta (str): Text containing review author and date
124 snippets (list): List of snippets in th review, each a list of text
125 lines
126 """
127 self.meta = ' : '.join([line for line in meta.splitlines() if line])
128 self.snippets = snippets
129
130
Simon Glass2c266d82025-04-29 07:22:13 -0600131class Patchwork:
132 """Class to handle communication with patchwork
133 """
134 def __init__(self, url, show_progress=True):
135 """Set up a new patchwork handler
136
137 Args:
138 url (str): URL of patchwork server, e.g.
139 'https://patchwork.ozlabs.org'
140 """
141 self.url = url
142 self.proj_id = None
143 self.link_name = None
144 self._show_progress = show_progress
145 self.semaphore = asyncio.Semaphore(MAX_CONCURRENT)
146 self.request_count = 0
147
148 async def _request(self, client, subpath):
149 """Call the patchwork API and return the result as JSON
150
151 Args:
152 client (aiohttp.ClientSession): Session to use
153 subpath (str): URL subpath to use
154
155 Returns:
156 dict: Json result
157
158 Raises:
159 ValueError: the URL could not be read
160 """
161 # print('subpath', subpath)
162 self.request_count += 1
163
164 full_url = f'{self.url}/api/1.2/{subpath}'
165 async with self.semaphore:
166 # print('full_url', full_url)
167 for i in range(RETRIES + 1):
168 try:
169 async with client.get(full_url) as response:
170 if response.status != 200:
171 raise ValueError(
172 f"Could not read URL '{full_url}'")
173 result = await response.json()
174 # print('- done', full_url)
175 return result
176 break
177 except aiohttp.client_exceptions.ServerDisconnectedError:
178 if i == RETRIES:
179 raise
Simon Glass1568b692025-04-29 07:22:15 -0600180
181 async def get_series(self, client, link):
182 """Read information about a series
183
184 Args:
185 client (aiohttp.ClientSession): Session to use
186 link (str): Patchwork series ID
187
188 Returns: dict containing patchwork's series information
189 id (int): series ID unique across patchwork instance, e.g. 3
190 url (str): Full URL, e.g.
191 'https://patchwork.ozlabs.org/api/1.2/series/3/'
192 web_url (str): Full URL, e.g.
193 'https://patchwork.ozlabs.org/project/uboot/list/?series=3
194 project (dict): project information (id, url, name, link_name,
195 list_id, list_email, etc.
196 name (str): Series name, e.g. '[U-Boot] moveconfig: fix error'
197 date (str): Date, e.g. '2017-08-27T08:00:51'
198 submitter (dict): id, url, name, email, e.g.:
199 "id": 6125,
200 "url": "https://patchwork.ozlabs.org/api/1.2/people/6125/",
201 "name": "Chris Packham",
202 "email": "judge.packham@gmail.com"
203 version (int): Version number
204 total (int): Total number of patches based on subject
205 received_total (int): Total patches received by patchwork
206 received_all (bool): True if all patches were received
207 mbox (str): URL of mailbox, e.g.
208 'https://patchwork.ozlabs.org/series/3/mbox/'
209 cover_letter (dict) or None, e.g.:
210 "id": 806215,
211 "url": "https://patchwork.ozlabs.org/api/1.2/covers/806215/",
212 "web_url": "https://patchwork.ozlabs.org/project/uboot/cover/
213 20170827094411.8583-1-judge.packham@gmail.com/",
214 "msgid": "<20170827094411.8583-1-judge.packham@gmail.com>",
215 "list_archive_url": null,
216 "date": "2017-08-27T09:44:07",
217 "name": "[U-Boot,v2,0/4] usb: net: Migrate USB Ethernet",
218 "mbox": "https://patchwork.ozlabs.org/project/uboot/cover/
219 20170827094411.8583-1-judge.packham@gmail.com/mbox/"
220 patches (list of dict), each e.g.:
221 "id": 806202,
222 "url": "https://patchwork.ozlabs.org/api/1.2/patches/806202/",
223 "web_url": "https://patchwork.ozlabs.org/project/uboot/patch/
224 20170827080051.816-1-judge.packham@gmail.com/",
225 "msgid": "<20170827080051.816-1-judge.packham@gmail.com>",
226 "list_archive_url": null,
227 "date": "2017-08-27T08:00:51",
228 "name": "[U-Boot] moveconfig: fix error message do_autoconf()",
229 "mbox": "https://patchwork.ozlabs.org/project/uboot/patch/
230 20170827080051.816-1-judge.packham@gmail.com/mbox/"
231 """
232 return await self._request(client, f'series/{link}/')
233
234 async def get_patch(self, client, patch_id):
235 """Read information about a patch
236
237 Args:
238 client (aiohttp.ClientSession): Session to use
239 patch_id (str): Patchwork patch ID
240
241 Returns: dict containing patchwork's patch information
242 "id": 185,
243 "url": "https://patchwork.ozlabs.org/api/1.2/patches/185/",
244 "web_url": "https://patchwork.ozlabs.org/project/cbe-oss-dev/patch/
245 200809050416.27831.adetsch@br.ibm.com/",
246 project (dict): project information (id, url, name, link_name,
247 list_id, list_email, etc.
248 "msgid": "<200809050416.27831.adetsch@br.ibm.com>",
249 "list_archive_url": null,
250 "date": "2008-09-05T07:16:27",
251 "name": "powerpc/spufs: Fix possible scheduling of a context",
252 "commit_ref": "b2e601d14deb2083e2a537b47869ab3895d23a28",
253 "pull_url": null,
254 "state": "accepted",
255 "archived": false,
256 "hash": "bc1c0b80d7cff66c0d1e5f3f8f4d10eb36176f0d",
257 "submitter": {
258 "id": 93,
259 "url": "https://patchwork.ozlabs.org/api/1.2/people/93/",
260 "name": "Andre Detsch",
261 "email": "adetsch@br.ibm.com"
262 },
263 "delegate": {
264 "id": 1,
265 "url": "https://patchwork.ozlabs.org/api/1.2/users/1/",
266 "username": "jk",
267 "first_name": "Jeremy",
268 "last_name": "Kerr",
269 "email": "jk@ozlabs.org"
270 },
271 "mbox": "https://patchwork.ozlabs.org/project/cbe-oss-dev/patch/
272 200809050416.27831.adetsch@br.ibm.com/mbox/",
273 "series": [],
274 "comments": "https://patchwork.ozlabs.org/api/patches/185/
275 comments/",
276 "check": "pending",
277 "checks": "https://patchwork.ozlabs.org/api/patches/185/checks/",
278 "tags": {},
279 "related": [],
280 "headers": {...}
281 "content": "We currently have a race when scheduling a context
282 after we have found a runnable context in spusched_tick, the
283 context may have been scheduled by spu_activate().
284
285 This may result in a panic if we try to unschedule a context
286 been freed in the meantime.
287
288 This change exits spu_schedule() if the context has already
289 scheduled, so we don't end up scheduling it twice.
290
291 Signed-off-by: Andre Detsch <adetsch@br.ibm.com>",
292 "diff": '''Index: spufs/arch/powerpc/platforms/cell/spufs/sched.c
293 =======================================================
294 --- spufs.orig/arch/powerpc/platforms/cell/spufs/sched.c
295 +++ spufs/arch/powerpc/platforms/cell/spufs/sched.c
296 @@ -727,7 +727,8 @@ static void spu_schedule(struct spu *spu
297 \t/* not a candidate for interruptible because it's called
298 \t from the scheduler thread or from spu_deactivate */
299 \tmutex_lock(&ctx->state_mutex);
300 -\t__spu_schedule(spu, ctx);
301 +\tif (ctx->state == SPU_STATE_SAVED)
302 +\t\t__spu_schedule(spu, ctx);
303 \tspu_release(ctx);
304 }
305 '''
306 "prefixes": ["3/3", ...]
307 """
308 return await self._request(client, f'patches/{patch_id}/')
309
310 async def _get_patch_comments(self, client, patch_id):
311 """Read comments about a patch
312
313 Args:
314 client (aiohttp.ClientSession): Session to use
315 patch_id (str): Patchwork patch ID
316
317 Returns: list of dict: list of comments:
318 id (int): series ID unique across patchwork instance, e.g. 3331924
319 web_url (str): Full URL, e.g.
320 'https://patchwork.ozlabs.org/comment/3331924/'
321 msgid (str): Message ID, e.g.
322 '<d2526c98-8198-4b8b-ab10-20bda0151da1@gmx.de>'
323 list_archive_url: (unknown?)
324 date (str): Date, e.g. '2024-06-20T13:38:03'
325 subject (str): email subject, e.g. 'Re: [PATCH 3/5] buildman:
326 Support building within a Python venv'
327 date (str): Date, e.g. '2017-08-27T08:00:51'
328 submitter (dict): id, url, name, email, e.g.:
329 "id": 61270,
330 "url": "https://patchwork.ozlabs.org/api/people/61270/",
331 "name": "Heinrich Schuchardt",
332 "email": "xypron.glpk@gmx.de"
333 content (str): Content of email, e.g. 'On 20.06.24 15:19,
334 Simon Glass wrote:
335 >...'
336 headers: dict: email headers, see get_cover() for an example
337 """
338 return await self._request(client, f'patches/{patch_id}/comments/')
339
340 async def get_patch_comments(self, patch_id):
341 async with aiohttp.ClientSession() as client:
342 return await self._get_patch_comments(client, patch_id)
343
344 async def _get_patch_status(self, client, patch_id):
345 """Get the patch status
346
347 Args:
348 client (aiohttp.ClientSession): Session to use
349 patch_id (int): Patch ID to look up in patchwork
350
351 Return:
352 PATCH: Patch information
353
354 Requests:
355 1 for patch, 1 for patch comments
356 """
357 data = await self.get_patch(client, patch_id)
358 state = data['state']
359 comment_data = await self._get_patch_comments(client, patch_id)
360
361 return Patch(patch_id, state, data, comment_data)
362
363 async def series_get_state(self, client, link, read_comments):
364 """Sync the series information against patchwork, to find patch status
365
366 Args:
367 client (aiohttp.ClientSession): Session to use
368 link (str): Patchwork series ID
369 read_comments (bool): True to read the comments on the patches
370
371 Return: tuple:
372 list of Patch objects
373 """
374 data = await self.get_series(client, link)
375 patch_list = list(data['patches'])
376
377 count = len(patch_list)
378 patches = []
379 if read_comments:
380 # Returns a list of Patch objects
381 tasks = [self._get_patch_status(client, patch_list[i]['id'])
382 for i in range(count)]
383
384 patch_status = await asyncio.gather(*tasks)
385 for patch_data, status in zip(patch_list, patch_status):
386 status.series_data = patch_data
387 patches.append(status)
388 else:
389 for i in range(count):
390 info = patch_list[i]
391 pat = Patch(info['id'], series_data=info)
392 pat.raw_subject = info['name']
393 patches.append(pat)
394 if self._show_progress:
395 terminal.print_clear()
396
397 return patches