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 | """Urwid UI for pick script."""
|
---|
22 |
|
---|
23 | import asyncio
|
---|
24 | import itertools
|
---|
25 | import textwrap
|
---|
26 | import typing
|
---|
27 |
|
---|
28 | import attr
|
---|
29 | import urwid
|
---|
30 |
|
---|
31 | from . import core
|
---|
32 |
|
---|
33 | if typing.TYPE_CHECKING:
|
---|
34 | WidgetType = typing.TypeVar('WidgetType', bound=urwid.Widget)
|
---|
35 |
|
---|
36 | PALETTE = [
|
---|
37 | ('a', 'black', 'light gray'),
|
---|
38 | ('b', 'black', 'dark red'),
|
---|
39 | ('bg', 'black', 'dark blue'),
|
---|
40 | ('reversed', 'standout', ''),
|
---|
41 | ]
|
---|
42 |
|
---|
43 |
|
---|
44 | class RootWidget(urwid.Frame):
|
---|
45 |
|
---|
46 | def __init__(self, *args, ui: 'UI', **kwargs):
|
---|
47 | super().__init__(*args, **kwargs)
|
---|
48 | self.ui = ui
|
---|
49 |
|
---|
50 |
|
---|
51 | class CommitList(urwid.ListBox):
|
---|
52 |
|
---|
53 | def __init__(self, *args, ui: 'UI', **kwargs):
|
---|
54 | super().__init__(*args, **kwargs)
|
---|
55 | self.ui = ui
|
---|
56 |
|
---|
57 | def keypress(self, size: int, key: str) -> typing.Optional[str]:
|
---|
58 | if key == 'q':
|
---|
59 | raise urwid.ExitMainLoop()
|
---|
60 | elif key == 'u':
|
---|
61 | asyncio.ensure_future(self.ui.update())
|
---|
62 | elif key == 'a':
|
---|
63 | self.ui.add()
|
---|
64 | else:
|
---|
65 | return super().keypress(size, key)
|
---|
66 | return None
|
---|
67 |
|
---|
68 |
|
---|
69 | class CommitWidget(urwid.Text):
|
---|
70 |
|
---|
71 | # urwid.Text is normally not interactable, this is required to tell urwid
|
---|
72 | # to use our keypress method
|
---|
73 | _selectable = True
|
---|
74 |
|
---|
75 | def __init__(self, ui: 'UI', commit: 'core.Commit'):
|
---|
76 | reason = commit.nomination_type.name.ljust(6)
|
---|
77 | super().__init__(f'{commit.date()} {reason} {commit.sha[:10]} {commit.description}')
|
---|
78 | self.ui = ui
|
---|
79 | self.commit = commit
|
---|
80 |
|
---|
81 | async def apply(self) -> None:
|
---|
82 | async with self.ui.git_lock:
|
---|
83 | result, err = await self.commit.apply(self.ui)
|
---|
84 | if not result:
|
---|
85 | self.ui.chp_failed(self, err)
|
---|
86 | else:
|
---|
87 | self.ui.remove_commit(self)
|
---|
88 |
|
---|
89 | async def denominate(self) -> None:
|
---|
90 | async with self.ui.git_lock:
|
---|
91 | await self.commit.denominate(self.ui)
|
---|
92 | self.ui.remove_commit(self)
|
---|
93 |
|
---|
94 | async def backport(self) -> None:
|
---|
95 | async with self.ui.git_lock:
|
---|
96 | await self.commit.backport(self.ui)
|
---|
97 | self.ui.remove_commit(self)
|
---|
98 |
|
---|
99 | def keypress(self, size: int, key: str) -> typing.Optional[str]:
|
---|
100 | if key == 'c':
|
---|
101 | asyncio.ensure_future(self.apply())
|
---|
102 | elif key == 'd':
|
---|
103 | asyncio.ensure_future(self.denominate())
|
---|
104 | elif key == 'b':
|
---|
105 | asyncio.ensure_future(self.backport())
|
---|
106 | else:
|
---|
107 | return key
|
---|
108 | return None
|
---|
109 |
|
---|
110 |
|
---|
111 | class FocusAwareEdit(urwid.Edit):
|
---|
112 |
|
---|
113 | """An Edit type that signals when it comes into and leaves focus."""
|
---|
114 |
|
---|
115 | signals = urwid.Edit.signals + ['focus_changed']
|
---|
116 |
|
---|
117 | def __init__(self, *args, **kwargs):
|
---|
118 | super().__init__(*args, **kwargs)
|
---|
119 | self.__is_focus = False
|
---|
120 |
|
---|
121 | def render(self, size: typing.Tuple[int], focus: bool = False) -> urwid.Canvas:
|
---|
122 | if focus != self.__is_focus:
|
---|
123 | self._emit("focus_changed", focus)
|
---|
124 | self.__is_focus = focus
|
---|
125 | return super().render(size, focus)
|
---|
126 |
|
---|
127 |
|
---|
128 | @attr.s(slots=True)
|
---|
129 | class UI:
|
---|
130 |
|
---|
131 | """Main management object.
|
---|
132 |
|
---|
133 | :previous_commits: A list of commits to main since this branch was created
|
---|
134 | :new_commits: Commits added to main since the last time this script was run
|
---|
135 | """
|
---|
136 |
|
---|
137 | commit_list: typing.List['urwid.Button'] = attr.ib(factory=lambda: urwid.SimpleFocusListWalker([]), init=False)
|
---|
138 | feedback_box: typing.List['urwid.Text'] = attr.ib(factory=lambda: urwid.SimpleFocusListWalker([]), init=False)
|
---|
139 | notes: 'FocusAwareEdit' = attr.ib(factory=lambda: FocusAwareEdit('', multiline=True), init=False)
|
---|
140 | header: 'urwid.Text' = attr.ib(factory=lambda: urwid.Text('Mesa Stable Picker', align='center'), init=False)
|
---|
141 | body: 'urwid.Columns' = attr.ib(attr.Factory(lambda s: s._make_body(), True), init=False)
|
---|
142 | footer: 'urwid.Columns' = attr.ib(attr.Factory(lambda s: s._make_footer(), True), init=False)
|
---|
143 | root: RootWidget = attr.ib(attr.Factory(lambda s: s._make_root(), True), init=False)
|
---|
144 | mainloop: urwid.MainLoop = attr.ib(None, init=False)
|
---|
145 |
|
---|
146 | previous_commits: typing.List['core.Commit'] = attr.ib(factory=list, init=False)
|
---|
147 | new_commits: typing.List['core.Commit'] = attr.ib(factory=list, init=False)
|
---|
148 | git_lock: asyncio.Lock = attr.ib(factory=asyncio.Lock, init=False)
|
---|
149 |
|
---|
150 | def _get_current_commit(self) -> typing.Optional['core.Commit']:
|
---|
151 | entry = self.commit_list.get_focus()[0]
|
---|
152 | return entry.original_widget.commit if entry is not None else None
|
---|
153 |
|
---|
154 | def _change_notes_cb(self) -> None:
|
---|
155 | commit = self._get_current_commit()
|
---|
156 | if commit and commit.notes:
|
---|
157 | self.notes.set_edit_text(commit.notes)
|
---|
158 | else:
|
---|
159 | self.notes.set_edit_text('')
|
---|
160 |
|
---|
161 | def _change_notes_focus_cb(self, notes: 'FocusAwareEdit', focus: 'bool') -> 'None':
|
---|
162 | # in the case of coming into focus we don't want to do anything
|
---|
163 | if focus:
|
---|
164 | return
|
---|
165 | commit = self._get_current_commit()
|
---|
166 | if commit is None:
|
---|
167 | return
|
---|
168 | text: str = notes.get_edit_text()
|
---|
169 | if text != commit.notes:
|
---|
170 | asyncio.ensure_future(commit.update_notes(self, text))
|
---|
171 |
|
---|
172 | def _make_body(self) -> 'urwid.Columns':
|
---|
173 | commits = CommitList(self.commit_list, ui=self)
|
---|
174 | feedback = urwid.ListBox(self.feedback_box)
|
---|
175 | urwid.connect_signal(self.commit_list, 'modified', self._change_notes_cb)
|
---|
176 | notes = urwid.Filler(self.notes)
|
---|
177 | urwid.connect_signal(self.notes, 'focus_changed', self._change_notes_focus_cb)
|
---|
178 |
|
---|
179 | return urwid.Columns([urwid.LineBox(commits), urwid.Pile([urwid.LineBox(notes), urwid.LineBox(feedback)])])
|
---|
180 |
|
---|
181 | def _make_footer(self) -> 'urwid.Columns':
|
---|
182 | body = [
|
---|
183 | urwid.Text('[U]pdate'),
|
---|
184 | urwid.Text('[Q]uit'),
|
---|
185 | urwid.Text('[C]herry Pick'),
|
---|
186 | urwid.Text('[D]enominate'),
|
---|
187 | urwid.Text('[B]ackport'),
|
---|
188 | urwid.Text('[A]pply additional patch'),
|
---|
189 | ]
|
---|
190 | return urwid.Columns(body)
|
---|
191 |
|
---|
192 | def _make_root(self) -> 'RootWidget':
|
---|
193 | return RootWidget(self.body, urwid.LineBox(self.header), urwid.LineBox(self.footer), 'body', ui=self)
|
---|
194 |
|
---|
195 | def render(self) -> 'WidgetType':
|
---|
196 | asyncio.ensure_future(self.update())
|
---|
197 | return self.root
|
---|
198 |
|
---|
199 | def load(self) -> None:
|
---|
200 | self.previous_commits = core.load()
|
---|
201 |
|
---|
202 | async def update(self) -> None:
|
---|
203 | self.load()
|
---|
204 | with open('VERSION', 'r') as f:
|
---|
205 | version = '.'.join(f.read().split('.')[:2])
|
---|
206 | if self.previous_commits:
|
---|
207 | sha = self.previous_commits[0].sha
|
---|
208 | else:
|
---|
209 | sha = f'{version}-branchpoint'
|
---|
210 |
|
---|
211 | new_commits = await core.get_new_commits(sha)
|
---|
212 |
|
---|
213 | if new_commits:
|
---|
214 | pb = urwid.ProgressBar('a', 'b', done=len(new_commits))
|
---|
215 | o = self.mainloop.widget
|
---|
216 | self.mainloop.widget = urwid.Overlay(
|
---|
217 | urwid.Filler(urwid.LineBox(pb)), o, 'center', ('relative', 50), 'middle', ('relative', 50))
|
---|
218 | self.new_commits = await core.gather_commits(
|
---|
219 | version, self.previous_commits, new_commits,
|
---|
220 | lambda: pb.set_completion(pb.current + 1))
|
---|
221 | self.mainloop.widget = o
|
---|
222 |
|
---|
223 | for commit in reversed(list(itertools.chain(self.new_commits, self.previous_commits))):
|
---|
224 | if commit.nominated and commit.resolution is core.Resolution.UNRESOLVED:
|
---|
225 | b = urwid.AttrMap(CommitWidget(self, commit), None, focus_map='reversed')
|
---|
226 | self.commit_list.append(b)
|
---|
227 | self.save()
|
---|
228 |
|
---|
229 | async def feedback(self, text: str) -> None:
|
---|
230 | self.feedback_box.append(urwid.AttrMap(urwid.Text(text), None))
|
---|
231 | latest_item_index = len(self.feedback_box) - 1
|
---|
232 | self.feedback_box.set_focus(latest_item_index)
|
---|
233 |
|
---|
234 | def remove_commit(self, commit: CommitWidget) -> None:
|
---|
235 | for i, c in enumerate(self.commit_list):
|
---|
236 | if c.base_widget is commit:
|
---|
237 | del self.commit_list[i]
|
---|
238 | break
|
---|
239 |
|
---|
240 | def save(self):
|
---|
241 | core.save(itertools.chain(self.new_commits, self.previous_commits))
|
---|
242 |
|
---|
243 | def add(self) -> None:
|
---|
244 | """Add an additional commit which isn't nominated."""
|
---|
245 | o = self.mainloop.widget
|
---|
246 |
|
---|
247 | def reset_cb(_) -> None:
|
---|
248 | self.mainloop.widget = o
|
---|
249 |
|
---|
250 | async def apply_cb(edit: urwid.Edit) -> None:
|
---|
251 | text: str = edit.get_edit_text()
|
---|
252 |
|
---|
253 | # In case the text is empty
|
---|
254 | if not text:
|
---|
255 | return
|
---|
256 |
|
---|
257 | sha = await core.full_sha(text)
|
---|
258 | for c in reversed(list(itertools.chain(self.new_commits, self.previous_commits))):
|
---|
259 | if c.sha == sha:
|
---|
260 | commit = c
|
---|
261 | break
|
---|
262 | else:
|
---|
263 | raise RuntimeError(f"Couldn't find {sha}")
|
---|
264 |
|
---|
265 | await commit.apply(self)
|
---|
266 |
|
---|
267 | q = urwid.Edit("Commit sha\n")
|
---|
268 | ok_btn = urwid.Button('Ok')
|
---|
269 | urwid.connect_signal(ok_btn, 'click', lambda _: asyncio.ensure_future(apply_cb(q)))
|
---|
270 | urwid.connect_signal(ok_btn, 'click', reset_cb)
|
---|
271 |
|
---|
272 | can_btn = urwid.Button('Cancel')
|
---|
273 | urwid.connect_signal(can_btn, 'click', reset_cb)
|
---|
274 |
|
---|
275 | cols = urwid.Columns([ok_btn, can_btn])
|
---|
276 | pile = urwid.Pile([q, cols])
|
---|
277 | box = urwid.LineBox(pile)
|
---|
278 |
|
---|
279 | self.mainloop.widget = urwid.Overlay(
|
---|
280 | urwid.Filler(box), o, 'center', ('relative', 50), 'middle', ('relative', 50)
|
---|
281 | )
|
---|
282 |
|
---|
283 | def chp_failed(self, commit: 'CommitWidget', err: str) -> None:
|
---|
284 | o = self.mainloop.widget
|
---|
285 |
|
---|
286 | def reset_cb(_) -> None:
|
---|
287 | self.mainloop.widget = o
|
---|
288 |
|
---|
289 | t = urwid.Text(textwrap.dedent(f"""
|
---|
290 | Failed to apply {commit.commit.sha} {commit.commit.description} with the following error:
|
---|
291 |
|
---|
292 | {err}
|
---|
293 |
|
---|
294 | You can either cancel, or resolve the conflicts (`git mergetool`), finish the
|
---|
295 | cherry-pick (`git cherry-pick --continue`) and select ok."""))
|
---|
296 |
|
---|
297 | can_btn = urwid.Button('Cancel')
|
---|
298 | urwid.connect_signal(can_btn, 'click', reset_cb)
|
---|
299 | urwid.connect_signal(
|
---|
300 | can_btn, 'click', lambda _: asyncio.ensure_future(commit.commit.abort_cherry(self, err)))
|
---|
301 |
|
---|
302 | ok_btn = urwid.Button('Ok')
|
---|
303 | urwid.connect_signal(ok_btn, 'click', reset_cb)
|
---|
304 | urwid.connect_signal(
|
---|
305 | ok_btn, 'click', lambda _: asyncio.ensure_future(commit.commit.resolve(self)))
|
---|
306 | urwid.connect_signal(
|
---|
307 | ok_btn, 'click', lambda _: self.remove_commit(commit))
|
---|
308 |
|
---|
309 | cols = urwid.Columns([ok_btn, can_btn])
|
---|
310 | pile = urwid.Pile([t, cols])
|
---|
311 | box = urwid.LineBox(pile)
|
---|
312 |
|
---|
313 | self.mainloop.widget = urwid.Overlay(
|
---|
314 | urwid.Filler(box), o, 'center', ('relative', 50), 'middle', ('relative', 50)
|
---|
315 | )
|
---|