Debian Codegraph @

bin/pick/core.py

raw
1 # Copyright © 2019-2020 Intel Corporation
2
3 # Permission is hereby granted, free of charge, to any person obtaining a copy
4 # of this software and associated documentation files (the "Software"), to deal
5 # in the Software without restriction, including without limitation the rights
6 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 # copies of the Software, and to permit persons to whom the Software is
8 # furnished to do so, subject to the following conditions:
9
10 # The above copyright notice and this permission notice shall be included in
11 # all copies or substantial portions of the Software.
12
13 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 # SOFTWARE.
20
21 """Core data structures and routines for pick."""
22
23 import asyncio
24 import enum
25 import json
26 import pathlib
27 import re
28 import subprocess
29 import typing
30
31 import attr
32 from packaging.version import Version
33
34 if typing.TYPE_CHECKING:
35 from .ui import UI
36
37 import typing_extensions
38
39 class CommitDict(typing_extensions.TypedDict):
40
41 sha: str
42 description: str
43 nominated: bool
44 nomination_type: int
45 resolution: typing.Optional[int]
46 main_sha: typing.Optional[str]
47 because_sha: typing.Optional[str]
48 notes: typing.Optional[str] = attr.ib(None)
49
50 IS_FIX = re.compile(r'^\s*fixes:\s*([a-f0-9]{6,40})', flags=re.MULTILINE | re.IGNORECASE)
51 # FIXME: I dislike the duplication in this regex, but I couldn't get it to work otherwise
52 IS_CC = re.compile(r'^\s*cc:\s*["\']?([0-9]{2}\.[0-9])?["\']?\s*["\']?([0-9]{2}\.[0-9])?["\']?\s*\<?mesa-stable',
53 flags=re.MULTILINE | re.IGNORECASE)
54 IS_REVERT = re.compile(r'This reverts commit ([0-9a-f]{40})')
55 IS_BACKPORT = re.compile(r'^\s*backport-to:\s*(?:(\d{2}\.\d),?\s*(\d{2}\.\d)?|(\*))',
56 flags=re.MULTILINE | re.IGNORECASE)
57
58 # XXX: hack
59 SEM = asyncio.Semaphore(50)
60
61 COMMIT_LOCK = asyncio.Lock()
62
63 git_toplevel = subprocess.check_output(['git', 'rev-parse', '--show-toplevel'],
64 stderr=subprocess.DEVNULL).decode("ascii").strip()
65 pick_status_json = pathlib.Path(git_toplevel) / '.pick_status.json'
66
67
68 class PickUIException(Exception):
69 pass
70
71
72 @enum.unique
73 class NominationType(enum.Enum):
74
75 NONE = 0
76 CC = 1
77 FIXES = 2
78 REVERT = 3
79 BACKPORT = 4
80
81
82 @enum.unique
83 class Resolution(enum.Enum):
84
85 UNRESOLVED = 0
86 MERGED = 1
87 DENOMINATED = 2
88 BACKPORTED = 3
89 NOTNEEDED = 4
90
91
92 async def commit_state(*, amend: bool = False, message: str = 'Update') -> bool:
93 """Commit the .pick_status.json file."""
94 async with COMMIT_LOCK:
95 p = await asyncio.create_subprocess_exec(
96 'git', 'add', pick_status_json.as_posix(),
97 stdout=asyncio.subprocess.DEVNULL,
98 stderr=asyncio.subprocess.DEVNULL,
99 )
100 v = await p.wait()
101 if v != 0:
102 return False
103
104 if amend:
105 cmd = ['--amend', '--no-edit']
106 else:
107 cmd = ['--message', f'.pick_status.json: {message}']
108 p = await asyncio.create_subprocess_exec(
109 'git', 'commit', *cmd,
110 stdout=asyncio.subprocess.DEVNULL,
111 stderr=asyncio.subprocess.DEVNULL,
112 )
113 v = await p.wait()
114 if v != 0:
115 return False
116 return True
117
118
119 @attr.s(slots=True)
120 class Commit:
121
122 sha: str = attr.ib()
123 description: str = attr.ib()
124 nominated: bool = attr.ib(False)
125 nomination_type: NominationType = attr.ib(NominationType.NONE)
126 resolution: Resolution = attr.ib(Resolution.UNRESOLVED)
127 main_sha: typing.Optional[str] = attr.ib(None)
128 because_sha: typing.Optional[str] = attr.ib(None)
129 notes: typing.Optional[str] = attr.ib(None)
130
131 def to_json(self) -> 'CommitDict':
132 d: typing.Dict[str, typing.Any] = attr.asdict(self)
133 d['nomination_type'] = self.nomination_type.value
134 if self.resolution is not None:
135 d['resolution'] = self.resolution.value
136 return typing.cast('CommitDict', d)
137
138 @classmethod
139 def from_json(cls, data: 'CommitDict') -> 'Commit':
140 c = cls(data['sha'], data['description'], data['nominated'], main_sha=data['main_sha'],
141 because_sha=data['because_sha'], notes=data['notes'])
142 c.nomination_type = NominationType(data['nomination_type'])
143 if data['resolution'] is not None:
144 c.resolution = Resolution(data['resolution'])
145 return c
146
147 def date(self) -> str:
148 # Show commit date, ie. when the commit actually landed
149 # (as opposed to when it was first written)
150 return subprocess.check_output(
151 ['git', 'show', '--no-patch', '--format=%cs', self.sha],
152 stderr=subprocess.DEVNULL
153 ).decode("ascii").strip()
154
155 async def apply(self, ui: 'UI') -> typing.Tuple[bool, str]:
156 # FIXME: This isn't really enough if we fail to cherry-pick because the
157 # git tree will still be dirty
158 async with COMMIT_LOCK:
159 p = await asyncio.create_subprocess_exec(
160 'git', 'cherry-pick', '-x', self.sha,
161 stdout=asyncio.subprocess.DEVNULL,
162 stderr=asyncio.subprocess.PIPE,
163 )
164 _, err = await p.communicate()
165
166 if p.returncode != 0:
167 return (False, err.decode())
168
169 self.resolution = Resolution.MERGED
170 await ui.feedback(f'{self.sha} ({self.description}) applied successfully')
171
172 # Append the changes to the .pickstatus.json file
173 ui.save()
174 v = await commit_state(amend=True)
175 return (v, '')
176
177 async def abort_cherry(self, ui: 'UI', err: str) -> None:
178 await ui.feedback(f'{self.sha} ({self.description}) failed to apply\n{err}')
179 async with COMMIT_LOCK:
180 p = await asyncio.create_subprocess_exec(
181 'git', 'cherry-pick', '--abort',
182 stdout=asyncio.subprocess.DEVNULL,
183 stderr=asyncio.subprocess.DEVNULL,
184 )
185 r = await p.wait()
186 await ui.feedback(f'{"Successfully" if r == 0 else "Failed to"} abort cherry-pick.')
187
188 async def denominate(self, ui: 'UI') -> bool:
189 self.resolution = Resolution.DENOMINATED
190 ui.save()
191 v = await commit_state(message=f'Mark {self.sha} as denominated')
192 assert v
193 await ui.feedback(f'{self.sha} ({self.description}) denominated successfully')
194 return True
195
196 async def backport(self, ui: 'UI') -> bool:
197 self.resolution = Resolution.BACKPORTED
198 ui.save()
199 v = await commit_state(message=f'Mark {self.sha} as backported')
200 assert v
201 await ui.feedback(f'{self.sha} ({self.description}) backported successfully')
202 return True
203
204 async def resolve(self, ui: 'UI') -> None:
205 self.resolution = Resolution.MERGED
206 ui.save()
207 v = await commit_state(amend=True)
208 assert v
209 await ui.feedback(f'{self.sha} ({self.description}) committed successfully')
210
211 async def update_notes(self, ui: 'UI', notes: typing.Optional[str]) -> None:
212 self.notes = notes
213 async with ui.git_lock:
214 ui.save()
215 v = await commit_state(message=f'Updates notes for {self.sha}')
216 assert v
217 await ui.feedback(f'{self.sha} ({self.description}) notes updated successfully')
218
219
220 async def get_new_commits(sha: str) -> typing.List[typing.Tuple[str, str]]:
221 # Try to get the authoritative upstream main
222 p = await asyncio.create_subprocess_exec(
223 'git', 'for-each-ref', '--format=%(upstream)', 'refs/heads/main',
224 stdout=asyncio.subprocess.PIPE,
225 stderr=asyncio.subprocess.DEVNULL)
226 out, _ = await p.communicate()
227 upstream = out.decode().strip()
228
229 p = await asyncio.create_subprocess_exec(
230 'git', 'log', '--pretty=oneline', f'{sha}..{upstream}',
231 stdout=asyncio.subprocess.PIPE,
232 stderr=asyncio.subprocess.DEVNULL)
233 out, _ = await p.communicate()
234 assert p.returncode == 0, f"git log didn't work: {sha}"
235 return list(split_commit_list(out.decode().strip()))
236
237
238 def split_commit_list(commits: str) -> typing.Generator[typing.Tuple[str, str], None, None]:
239 if not commits:
240 return
241 for line in commits.split('\n'):
242 v = tuple(line.split(' ', 1))
243 assert len(v) == 2, 'this is really just for mypy'
244 yield typing.cast(typing.Tuple[str, str], v)
245
246
247 async def is_commit_in_branch(sha: str) -> bool:
248 async with SEM:
249 p = await asyncio.create_subprocess_exec(
250 'git', 'merge-base', '--is-ancestor', sha, 'HEAD',
251 stdout=asyncio.subprocess.DEVNULL,
252 stderr=asyncio.subprocess.DEVNULL,
253 )
254 await p.wait()
255 return p.returncode == 0
256
257
258 async def full_sha(sha: str) -> str:
259 async with SEM:
260 p = await asyncio.create_subprocess_exec(
261 'git', 'rev-parse', sha,
262 stdout=asyncio.subprocess.PIPE,
263 stderr=asyncio.subprocess.DEVNULL,
264 )
265 out, _ = await p.communicate()
266 if p.returncode:
267 raise PickUIException(f'Invalid Sha {sha}')
268 return out.decode().strip()
269
270
271 async def resolve_nomination(commit: 'Commit', version: str) -> 'Commit':
272 async with SEM:
273 p = await asyncio.create_subprocess_exec(
274 'git', 'log', '--format=%B', '-1', commit.sha,
275 stdout=asyncio.subprocess.PIPE,
276 stderr=asyncio.subprocess.DEVNULL,
277 )
278 _out, _ = await p.communicate()
279 assert p.returncode == 0, f'git log for {commit.sha} failed'
280 commit_message = _out.decode()
281
282 # We give precedence to fixes and cc tags over revert tags.
283 if fix_for_commit := IS_FIX.search(commit_message):
284 # We set the nomination_type and because_sha here so that we can later
285 # check to see if this fixes another staged commit.
286 try:
287 commit.because_sha = fixed = await full_sha(fix_for_commit.group(1))
288 except PickUIException:
289 pass
290 else:
291 commit.nomination_type = NominationType.FIXES
292 if await is_commit_in_branch(fixed):
293 commit.nominated = True
294 return commit
295
296 if backport_to := IS_BACKPORT.findall(commit_message):
297 for match in backport_to:
298 if any(backport_version == '*' or Version(version) >= Version(backport_version)
299 for backport_version in match if backport_version != ''):
300 commit.nominated = True
301 commit.nomination_type = NominationType.BACKPORT
302 return commit
303
304 if cc_to := IS_CC.search(commit_message):
305 if cc_to.groups() == (None, None) or version in cc_to.groups():
306 commit.nominated = True
307 commit.nomination_type = NominationType.CC
308 return commit
309
310 if revert_of := IS_REVERT.search(commit_message):
311 # See comment for IS_FIX path
312 try:
313 commit.because_sha = reverted = await full_sha(revert_of.group(1))
314 except PickUIException:
315 pass
316 else:
317 commit.nomination_type = NominationType.REVERT
318 if await is_commit_in_branch(reverted):
319 commit.nominated = True
320 return commit
321
322 return commit
323
324
325 async def resolve_fixes(commits: typing.List['Commit'], previous: typing.List['Commit']) -> None:
326 """Determine if any of the undecided commits fix/revert a staged commit.
327
328 The are still needed if they apply to a commit that is staged for
329 inclusion, but not yet included.
330
331 This must be done in order, because a commit 3 might fix commit 2 which
332 fixes commit 1.
333 """
334 shas: typing.Set[str] = set(c.sha for c in previous if c.nominated)
335 assert None not in shas, 'None in shas'
336
337 for commit in reversed(commits):
338 if not commit.nominated and commit.nomination_type is NominationType.FIXES:
339 commit.nominated = commit.because_sha in shas
340
341 if commit.nominated:
342 shas.add(commit.sha)
343
344 for commit in commits:
345 if (commit.nomination_type is NominationType.REVERT and
346 commit.because_sha in shas):
347 for oldc in reversed(commits):
348 if oldc.sha == commit.because_sha:
349 # In this case a commit that hasn't yet been applied is
350 # reverted, we don't want to apply that commit at all
351 oldc.nominated = False
352 oldc.resolution = Resolution.DENOMINATED
353 commit.nominated = False
354 commit.resolution = Resolution.DENOMINATED
355 shas.remove(commit.because_sha)
356 break
357
358
359 async def gather_commits(version: str, previous: typing.List['Commit'],
360 new: typing.List[typing.Tuple[str, str]], cb) -> typing.List['Commit']:
361 # We create an array of the final size up front, then we pass that array
362 # to the "inner" co-routine, which is turned into a list of tasks and
363 # collected by asyncio.gather. We do this to allow the tasks to be
364 # asynchronously gathered, but to also ensure that the commits list remains
365 # in order.
366 m_commits: typing.List[typing.Optional['Commit']] = [None] * len(new)
367 tasks = []
368
369 async def inner(commit: 'Commit', version: str,
370 commits: typing.List[typing.Optional['Commit']],
371 index: int, cb) -> None:
372 commits[index] = await resolve_nomination(commit, version)
373 cb()
374
375 for i, (sha, desc) in enumerate(new):
376 tasks.append(asyncio.ensure_future(
377 inner(Commit(sha, desc), version, m_commits, i, cb)))
378
379 await asyncio.gather(*tasks)
380 assert None not in m_commits
381 commits = typing.cast(typing.List[Commit], m_commits)
382
383 await resolve_fixes(commits, previous)
384
385 for commit in commits:
386 if commit.resolution is Resolution.UNRESOLVED and not commit.nominated:
387 commit.resolution = Resolution.NOTNEEDED
388
389 return commits
390
391
392 def load() -> typing.List['Commit']:
393 if not pick_status_json.exists():
394 return []
395 with pick_status_json.open('r') as f:
396 raw = json.load(f)
397 return [Commit.from_json(c) for c in raw]
398
399
400 def save(commits: typing.Iterable['Commit']) -> None:
401 commits = list(commits)
402 with pick_status_json.open('wt') as f:
403 json.dump([c.to_json() for c in commits], f, indent=4)
404
405 asyncio.ensure_future(commit_state(message=f'Update to {commits[0].sha}'))