Debian Codegraph @

lib/subprocess.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # QBrz - Qt frontend to Breezy commands
4 # Copyright (C) 2006 Lukáš Lalinský <[email protected]m>
5 # Copyright (C) 2008 Gary van der Merwe <[email protected]>
6 # Copyright (C) 2009 Alexander Belchenko
7 # Copyright (C) 2010 QBzr Developers
8 #
9 # This program is free software; you can redistribute it and/or
10 # modify it under the terms of the GNU General Public License
11 # as published by the Free Software Foundation; either version 2
12 # of the License, or (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program; if not, write to the Free Software
21 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22
23 import os
24 import sys
25 import time
26
27 from PyQt5 import QtCore, QtGui, QtWidgets
28 from contextlib import contextmanager
29
30 from breezy.plugins.qbrz.lib import MS_WINDOWS
31 from breezy.plugins.qbrz.lib.i18n import gettext, N_
32 from breezy.plugins.qbrz.lib.util import (
33 BTN_CANCEL,
34 BTN_CLOSE,
35 BTN_OK,
36 QBzrDialog,
37 QBzrWindow,
38 StandardButton,
39 ensure_unicode,
40 InfoWidget,
41 )
42
43 from breezy.ui.text import TextProgressView, TextUIFactory
44
45 import fastbencode as bencode
46
47 import codecs
48 import re
49 import signal
50 import tempfile
51 if MS_WINDOWS:
52 import thread
53
54 from breezy import commands, errors, osutils, ui
55
56 # Subprocess service messages markers
57 SUB_PROGRESS = "qbrz:PROGRESS:"
58 SUB_GETPASS = "qbrz:GETPASS:"
59 SUB_GETUSER = "qbrz:GETUSER:"
60 SUB_GETBOOL = "qbrz:GETBOOL:"
61 SUB_CHOOSE = "qbrz:CHOOSE:"
62 SUB_ERROR = "qbrz:ERROR:"
63 SUB_NOTIFY = "qbrz:NOTIFY:"
64
65 NOTIFY_CONFLICT = "conflict:"
66
67
68 class WarningInfoWidget(InfoWidget):
69 def __init__(self, parent):
70 InfoWidget.__init__(self, parent)
71 layout = QtWidgets.QVBoxLayout(self)
72 label_layout = QtWidgets.QHBoxLayout()
73
74 icon = QtWidgets.QLabel()
75 icon.setPixmap(self.style().standardPixmap(QtWidgets.QStyle.SP_MessageBoxWarning))
76 label_layout.addWidget(icon)
77 self.label = QtWidgets.QLabel()
78 label_layout.addWidget(self.label, 2)
79 layout.addLayout(label_layout)
80 self.button_layout = QtWidgets.QHBoxLayout()
81 self.button_layout.addStretch(1)
82 layout.addLayout(self.button_layout)
83
84 self.buttons = []
85
86 def add_button(self, text, on_click):
87 button = QtWidgets.QPushButton(gettext(text))
88 button.clicked[bool].connect(on_click)
89 self.button_layout.addWidget(button)
90 self.buttons.append((button, on_click))
91
92 def remove_all_buttons(self):
93 for button, on_click in self.buttons:
94 button.clicked[bool].disconnect(on_click)
95 self.button_layout.removeWidget(button)
96 button.close()
97 del(self.buttons[:])
98
99 def set_label(self, text):
100 self.label.setText(gettext(text))
101
102 def setup_for_uncommitted(self, on_commit, on_revert, on_shelve):
103 self.remove_all_buttons()
104 self.set_label(N_('Working tree has uncommitted changes.'))
105 self.add_button(N_('Commit'), on_commit)
106 self.add_button(N_('Revert'), on_revert)
107 self.add_button(N_('Shelve'), on_shelve)
108
109 def setup_for_conflicted(self, on_conflict, on_revert):
110 self.remove_all_buttons()
111 self.set_label(N_('Working tree has conflicts.'))
112 self.add_button(N_('Resolve'), on_conflict)
113 self.add_button(N_('Revert'), on_revert)
114
115 def setup_for_locked(self, on_retry):
116 self.remove_all_buttons()
117 self.set_label(N_('Could not acquire lock. Please retry later.'))
118 self.add_button(N_('Retry'), on_retry)
119
120
121 class SubProcessWindowBase:
122
123 subprocessStarted = QtCore.pyqtSignal(bool)
124 disableUi = QtCore.pyqtSignal(bool)
125 subprocessFinished = QtCore.pyqtSignal(bool)
126 subprocessFailed = QtCore.pyqtSignal(bool)
127 subprocessError = QtCore.pyqtSignal(bool)
128
129 def __init_internal__(self, title,
130 name="genericsubprocess",
131 args=None,
132 dir=None,
133 default_size=None,
134 ui_mode=True,
135 dialog=True,
136 parent=None,
137 hide_progress=False,
138 immediate=False):
139 self.restoreSize(name, default_size)
140 self._name = name
141 self._default_size = default_size
142 self.args = args
143 self.dir = dir
144 self.ui_mode = ui_mode
145
146 self.return_code = 1
147
148 if dialog:
149 flags = (self.windowFlags() & ~QtCore.Qt.Window) | QtCore.Qt.Dialog
150 self.setWindowFlags(flags)
151
152 self.process_widget = SubProcessWidget(self.ui_mode, self, hide_progress)
153 self.process_widget.finished.connect(self.on_finished)
154 self.process_widget.failed['QString'].connect(self.on_failed)
155 self.process_widget.error.connect(self.on_error)
156 self.process_widget.conflicted['QString'].connect(self.on_conflicted)
157
158 self.closeButton = StandardButton(BTN_CLOSE)
159 self.okButton = StandardButton(BTN_OK)
160 self.cancelButton = StandardButton(BTN_CANCEL)
161
162 # ok button gets disabled when we start.
163 self.subprocessStarted[bool].connect(self.okButton.setDisabled)
164
165 # ok button gets hidden when we finish.
166 self.subprocessFinished[bool].connect(self.okButton.setHidden)
167
168 # close button gets shown when we finish.
169 self.subprocessFinished[bool].connect(self.closeButton.setVisible)
170
171 # cancel button gets disabled when finished.
172 self.subprocessFinished[bool].connect(self.cancelButton.setDisabled)
173
174 # ok button gets enabled when we fail.
175 self.subprocessFailed[bool].connect(self.okButton.setDisabled)
176
177 # Change the ok button to 'retry' if we fail.
178 self.subprocessFailed[bool].connect(lambda failed: self.okButton.setText(gettext('&Retry')))
179
180 self.buttonbox = QtWidgets.QDialogButtonBox(self)
181 self.buttonbox.addButton(self.okButton, QtWidgets.QDialogButtonBox.AcceptRole)
182 self.buttonbox.addButton(self.closeButton, QtWidgets.QDialogButtonBox.AcceptRole)
183 self.buttonbox.addButton(self.cancelButton, QtWidgets.QDialogButtonBox.RejectRole)
184 self.buttonbox.accepted.connect(self.do_accept)
185 self.buttonbox.rejected.connect(self.do_reject)
186 self.closeButton.setHidden(True) # but 'close' starts as hidden.
187
188 self.infowidget = WarningInfoWidget(self)
189 self.infowidget.hide()
190 self.subprocessStarted[bool].connect(self.infowidget.setHidden)
191
192 if immediate:
193 self.do_accept()
194
195 def make_default_status_box(self):
196 panel = QtWidgets.QWidget()
197 vbox = QtWidgets.QVBoxLayout(panel)
198 vbox.setContentsMargins(0, 0, 0, 0)
199 vbox.addWidget(self.infowidget)
200 status_group_box = QtWidgets.QGroupBox(gettext("Status"))
201 status_layout = QtWidgets.QVBoxLayout(status_group_box)
202 status_layout.setContentsMargins(0, 0, 0, 0)
203 status_layout.addWidget(self.process_widget)
204 vbox.addWidget(status_group_box)
205 return panel
206
207 def make_process_panel(self):
208 panel = QtWidgets.QWidget()
209 vbox = QtWidgets.QVBoxLayout(panel)
210 vbox.setContentsMargins(0, 0, 0, 0)
211 vbox.addWidget(self.infowidget)
212 vbox.addWidget(self.process_widget)
213 return panel
214
215 def make_default_layout_widgets(self):
216 """Yields widgets to add to main dialog layout: status and button boxes.
217 Status box has progress bar and console area.
218 Button box has 2 buttons: OK and Cancel (after successfull command
219 execution there will be Close and Cancel).
220 """
221 yield self.make_default_status_box()
222 yield self.buttonbox
223
224 def validate(self):
225 """Override this method in your class and do any validation there.
226 Return True if all parameters is OK and subprocess can be started.
227 """
228 return True
229
230 def _check_args(self):
231 """Check that self.args is not None and return True.
232 Otherwise show error dialog to the user and return False.
233 """
234 if self.args is None:
235 raise RuntimeError('Subprocess action "%s" cannot be started\n'
236 'because self.args is None.' % self._name)
237 return True
238
239 def do_accept(self):
240 if self.process_widget.is_finished:
241 self.close()
242 else:
243 try:
244 if not self.validate():
245 return
246 except:
247 report_exception(type=SUB_LOAD_METHOD, window=self.window())
248 return
249
250 self.subprocessStarted.emit(True)
251 self.disableUi.emit(True)
252 self.do_start()
253
254 def do_start(self):
255 if self._check_args():
256 self.process_widget.do_start(self.dir, *self.args)
257 else:
258 self.on_failed('CheckArgsFailed')
259
260 def do_reject(self):
261 if self.process_widget.is_running():
262 self.process_widget.abort()
263 else:
264 self.close()
265
266 def on_finished(self):
267 if hasattr(self, 'setResult'):
268 self.setResult(QtWidgets.QDialog.Accepted)
269
270 self.subprocessFinished.emit(True)
271 self.disableUi.emit(False)
272
273 self.return_code = 0
274
275 if not self.ui_mode and not self.infowidget.isVisible():
276 self.close()
277
278 def on_conflicted(self, tree_path):
279 if tree_path:
280 self.action_url = str(tree_path) # QString -> unicode
281 self.infowidget.setup_for_conflicted(self.open_conflicts_win, self.open_revert_win)
282 self.infowidget.show()
283
284 def on_failed(self, error):
285 self.subprocessFailed.emit(False)
286 self.disableUi.emit(False)
287
288 if error == 'UncommittedChanges':
289 self.action_url = self.process_widget.error_data['display_url']
290 self.infowidget.setup_for_uncommitted(self.open_commit_win, self.open_revert_win, self.open_shelve_win)
291 self.infowidget.show()
292
293 elif error == 'LockContention':
294 self.infowidget.setup_for_locked(self.do_accept)
295 self.infowidget.show()
296
297 def on_error(self):
298 self.subprocessError.emit(False)
299
300 def setupUi(self, ui):
301 ui.setupUi(self)
302 if self._restore_size:
303 self.resize(self._restore_size)
304
305 def open_commit_win(self, b):
306 # XXX refactor so that the tree can be opened by the window
307 from breezy.plugins.qbrz.lib.commit import CommitWindow
308 tree, branch = BzrDir.open_tree_or_branch(self.action_url)
309 commit_window = CommitWindow(tree=tree, selected_list=None, parent=self)
310 self.windows.append(commit_window)
311 commit_window.show()
312
313 def open_revert_win(self, b):
314 from breezy.plugins.qbrz.lib.revert import RevertWindow
315 # XXX refactor so that the tree can be opened by the window
316 tree, branch = BzrDir.open_tree_or_branch(self.action_url)
317 revert_window = RevertWindow(tree, None, parent=self)
318 self.windows.append(revert_window)
319 revert_window.show()
320
321 def open_shelve_win(self, b):
322 from breezy.plugins.qbrz.lib.shelvewindow import ShelveWindow
323 shelve_window = ShelveWindow(directory=self.action_url, parent=self)
324 self.windows.append(shelve_window)
325 shelve_window.show()
326
327 def open_conflicts_win(self, b):
328 from breezy.plugins.qbrz.lib.conflicts import ConflictsWindow
329 window = ConflictsWindow(self.action_url, parent=self)
330 self.windows.append(window)
331 window.show()
332 window.allResolved[bool].connect(self.infowidget.setHidden)
333
334
335 class SubProcessWindow(SubProcessWindowBase, QBzrWindow):
336
337 def __init__(self, title, name="genericsubprocess", args=None, dir=None, default_size=None,
338 ui_mode=True, dialog=True, parent=None, hide_progress=False):
339 QBzrWindow.__init__(self, title, parent)
340 self.__init_internal__(title, name=name, args=args, dir=dir, default_size=default_size,
341 ui_mode=ui_mode, dialog=dialog, parent=parent, hide_progress=hide_progress)
342
343 def closeEvent(self, event):
344 if not self.process_widget.is_running():
345 QBzrWindow.closeEvent(self, event)
346 else:
347 self.process_widget.abort()
348 event.ignore()
349
350
351 class SubProcessDialog(SubProcessWindowBase, QBzrDialog):
352 """An abstract base-class for all subprocess related dialogs.
353
354 It is expected that sub-classes of this will create their own UI, and while
355 doing so, will add the widgets returned by
356 self.make_default_layout_widgets()
357 """
358
359 def __init__(self, title=None, name="genericsubprocess", args=None, dir=None, default_size=None,
360 ui_mode=True, dialog=True, parent=None, hide_progress=False, immediate=False):
361 QBzrDialog.__init__(self, title, parent)
362 self.__init_internal__(title, name=name, args=args, dir=dir, default_size=default_size,
363 ui_mode=ui_mode, dialog=dialog, parent=parent, hide_progress=hide_progress, immediate=immediate)
364
365 def closeEvent(self, event):
366 if not self.process_widget.is_running():
367 QBzrDialog.closeEvent(self, event)
368 else:
369 self.process_widget.abort()
370 event.ignore()
371
372
373 class SimpleSubProcessDialog(SubProcessDialog):
374 """A concrete helper class of SubProcessDialog, which has a single label
375 widget for displaying a simple description before executing a subprocess.
376 """
377
378 def __init__(self, title, desc,
379 name="genericsubprocess",
380 args=None,
381 dir=None,
382 default_size=None,
383 ui_mode=True,
384 dialog=True,
385 hide_progress=False,
386 auto_start_show_on_failed=False,
387 parent=None,
388 immediate=False
389 ):
390 super(SimpleSubProcessDialog, self).__init__(
391 title,
392 name=name,
393 args=args,
394 dir=dir,
395 default_size=default_size,
396 ui_mode=ui_mode,
397 dialog=dialog,
398 parent=parent,
399 hide_progress=hide_progress,
400 immediate=immediate)
401 self.desc = desc
402 # create a layout to hold our one label and the subprocess widgets.
403 layout = QtWidgets.QVBoxLayout(self)
404 groupbox = QtWidgets.QGroupBox(gettext('Description'))
405 v = QtWidgets.QVBoxLayout(groupbox)
406 label = QtWidgets.QLabel(self.desc)
407 label.font().setBold(True)
408 v.addWidget(label)
409 layout.addWidget(groupbox)
410 # and add the subprocess widgets.
411 for w in self.make_default_layout_widgets():
412 layout.addWidget(w)
413
414 self.auto_start_show_on_failed = auto_start_show_on_failed
415 QtCore.QTimer.singleShot(1, self.auto_start)
416
417 def auto_start(self):
418 if self.auto_start_show_on_failed:
419 self.subprocessFailed[bool].connect(self.setHidden)
420 self.subprocessError[bool].connect(self.setHidden)
421 self.do_start()
422
423
424 class SubProcessWidget(QtWidgets.QWidget):
425 # RJLRJL moved to class members to handle connects to Qt5
426 # 'a signal needs to be defined on class level'
427 failed = QtCore.pyqtSignal('QString')
428 conflicted = QtCore.pyqtSignal('QString')
429 finished = QtCore.pyqtSignal(bool)
430 error = QtCore.pyqtSignal(bool)
431
432 def __init__(self, ui_mode, parent=None, hide_progress=False):
433 QtWidgets.QGroupBox.__init__(self, parent)
434 self.ui_mode = ui_mode
435
436 layout = QtWidgets.QVBoxLayout(self)
437
438 message_layout = QtWidgets.QHBoxLayout()
439
440 self.progressMessage = QtWidgets.QLabel(self)
441 # self.progressMessage.setWordWrap(True) -- this breaks minimal window size hint
442 self.progressMessage.setText(gettext("Ready"))
443 message_layout.addWidget(self.progressMessage, 1)
444
445 self.transportActivity = QtWidgets.QLabel(self)
446 message_layout.addWidget(self.transportActivity)
447
448 layout.addLayout(message_layout)
449
450 self.progressBar = QtWidgets.QProgressBar(self)
451 self.progressBar.setMaximum(1000000)
452 layout.addWidget(self.progressBar)
453
454 self.console = QtWidgets.QTextBrowser(self)
455 self.console.setFocusPolicy(QtCore.Qt.ClickFocus)
456 layout.addWidget(self.console)
457
458 self.encoding = osutils.get_user_encoding()
459 self.stdout = None
460 self.stderr = None
461
462 self.process = QtCore.QProcess()
463 self.process.readyReadStandardOutput.connect(self.readStdout)
464 self.process.readyReadStandardError.connect(self.readStderr)
465 self.process.error[QtCore.QProcess.ProcessError].connect(self.reportProcessError)
466 self.process.finished[int, QtCore.QProcess.ExitStatus].connect(self.onFinished)
467
468 self.defaultWorkingDir = self.process.workingDirectory()
469
470 self.is_finished = False
471 self.aborting = False
472
473 self.messageFormat = QtGui.QTextCharFormat()
474 self.errorFormat = QtGui.QTextCharFormat()
475 self.errorFormat.setForeground(QtGui.QColor('red'))
476 self.cmdlineFormat = QtGui.QTextCharFormat()
477 self.cmdlineFormat.setForeground(QtGui.QColor('blue'))
478
479 if hide_progress:
480 self.hide_progress()
481
482 self.force_passing_args_via_file = False
483 self._args_file = None # temp file to pass arguments to qsubprocess
484 self.error_class = ''
485 self.error_data = {}
486 self.is_conflicted = False
487
488 def hide_progress(self):
489 self.progressMessage.setHidden(True)
490 self.progressBar.setHidden(True)
491
492 def is_running(self):
493 return self.process.state() == QtCore.QProcess.Running or self.process.state() == QtCore.QProcess.Starting
494
495 def do_start(self, workdir, *args):
496 """Launch one bzr command.
497 @param workdir: working directory for command.
498 Could be None to use self.defaultWorkingDir
499 @param args: bzr command and its arguments
500 @type args: all arguments should be unicode strings (or ascii-only).
501 """
502 QtWidgets.QApplication.processEvents() # make sure ui has caught up
503 self.start_multi(((workdir, args),))
504
505 def start_multi(self, commands):
506 self.setProgress(0, [gettext("Starting...")], "")
507 self.console.setFocus(QtCore.Qt.OtherFocusReason)
508 self.commands = list(commands)
509 self._start_next()
510
511 def _start_next(self):
512 """Start first command from self.commands queue."""
513 self._setup_stdout_stderr()
514 self._delete_args_file()
515 directory, args = self.commands.pop(0)
516
517 # Log the command we about to execute
518 # Interestingly, this puts quotes around any strings in r
519 # but this is not done in the body of the kirk, for some reason
520 def format_args_for_log(args):
521 # r = ['bzr']
522 r = ['brz']
523 for a in args:
524 a = str(a).translate({
525 ord('\n'): '\\n',
526 ord('\r'): '\\r',
527 ord('\t'): '\\t',
528 })
529 if " " in a:
530 r.append('"%s"' % a)
531 else:
532 r.append(a)
533 s = ' '.join(r)
534 if len(s) > 128: # XXX make it configurable?
535 s = s[:128] + '...'
536 return s
537 self.logMessageEx("Run command: " + format_args_for_log(args), "cmdline", self.stderr)
538
539 # RJLRJL: these are encoded, just to be decoded again in run_subprocess_command
540 args = bittorrent_b_encode_unicode(args)
541
542 # win32 has command-line length limit about 32K, but it seems
543 # problems with command-line buffer limit occurs not only on windows.
544 # see bug https://bugs.launchpad.net/qbrz/+bug/396165
545 # on Linux I believe command-line is in utf-8,
546 # so we need to have some extra space
547 # when converting unicode -> utf8
548 # XXX make the threshold configurable in qbrz.conf?
549 #
550 # RJL: at this point, args is now a byte string (bencoded)
551 if (len(args) > 10000 or re.search(rb"(?:"
552 rb"\n|\r" # workaround for bug #517420 multi-line comments
553 rb"|\\\\" # workaround for bug #528944 eating backslashes
554 rb")", args) is not None
555 or self.force_passing_args_via_file # workaround for bug #936587 quoted regular expressions
556 ):
557 # save the args to the file
558 fname = self._create_args_file(args)
559 # This:
560 #
561 # args = "@" + fname.replace('\\', '/')
562 #
563 # was bad and caused a bug: args was now no longer a bencoded string... but
564 # the code below would pass it to qsubprocess telling the lie that it was. Tsk.
565 # In Python 2 this sort-of worked: more correctly, nobody noticed the bad behaviour
566 # (bug) for 10 or 12 years.
567 #
568 # Instead, we'll pass a properly constructed, bencoded string
569 #
570 args = "@" + fname.replace('\\', '/')
571 args = bencode.bencode(bytes(args, 'utf-8'))
572
573 if directory is None:
574 directory = self.defaultWorkingDir
575
576 self.error_class = ''
577 self.error_data = {}
578
579 self.process.setWorkingDirectory(directory)
580 if getattr(sys, "frozen", None) is not None:
581 brz_exe = sys.executable
582 if os.path.basename(brz_exe) != "brz.exe":
583 # Was run from bzrw.exe or tbzrcommand.
584 brz_exe = os.path.join(os.path.dirname(sys.executable), "brz.exe")
585 if not os.path.isfile(brz_exe):
586 self.reportProcessError(None, gettext('Could not locate "brz.exe".'))
587 self.process.start(brz_exe, ['qsubprocess', '--bencode', args])
588 else:
589 # otherwise running as python script.
590 # ensure run from bzr, and not others, e.g. tbzrcommand.py
591 script = sys.argv[0]
592 # make absolute, because we may be running in a different
593 # dir.
594 script = os.path.abspath(script)
595 # allow for bzr or brz with optional extension (such as bzr.py)
596 if os.path.splitext(os.path.basename(script))[0] not in ("brz", "bzr"):
597 import breezy
598 # are we running directly from a bzr directory?
599 script = os.path.join(breezy.__path__[0], "..", "brz")
600 if not os.path.isfile(script):
601 # maybe from an installed bzr?
602 script = os.path.join(sys.prefix, "scripts", "brz")
603 if not os.path.isfile(script):
604 self.reportProcessError(None, gettext('Could not locate "brz" script.'))
605 self.process.start(sys.executable, [script, 'qsubprocess', '--bencode', str(args, 'utf-8')])
606
607 def _setup_stdout_stderr(self):
608 if self.stdout is None:
609 writer = codecs.getwriter(osutils.get_terminal_encoding())
610 self.stdout = writer(sys.stdout.buffer, errors='replace')
611 self.stderr = writer(sys.stderr.buffer, errors='replace')
612
613 def abort(self):
614 if self.is_running():
615 self.abort_futher_processes()
616 if not self.aborting:
617 self.aborting = True
618 if MS_WINDOWS:
619 # trying to send signal to our subprocess
620 signal_event(get_child_pid(self.process.pid()))
621 else:
622 # be nice and try to use ^C
623 os.kill(self.process.pid(), signal.SIGINT)
624 self.setProgress(None, [gettext("Aborting...")])
625 else:
626 self.process.terminate()
627
628 def abort_futher_processes(self):
629 self.commands = []
630
631 def setProgress(self, progress, messages, transport_activity=None):
632 if progress is not None:
633 self.progressBar.setValue(progress)
634 if progress == 1000000 and not messages:
635 text = gettext("Finished!")
636 else:
637 text = " / ".join(messages)
638 self.progressMessage.setText(text)
639 if transport_activity is not None:
640 self.transportActivity.setText(transport_activity)
641
642 def readStdout(self):
643 # TODO: This will almost certainly fail - see TestSubprocessProgressView in test_subprocess
644 # ensure we read from subprocess plain string.
645 #
646 # ``run_subprocess_command`` seems to end up here
647 #
648 # ``readAllStandardOutput`` is a PyQt4 routine. The docs state that it returns a QByteArray:
649 # testing shows that it does and that its ``.data()`` method returns bytes
650 #
651 data = self.process.readAllStandardOutput().data().decode(self.encoding)
652
653 for line in data.splitlines():
654 # Note that bdecode needs bytes so we encode() once we've snipped off the leading SUB_PROGRESS or whatever
655 if line.startswith(SUB_PROGRESS):
656 try:
657 progress, transport_activity, task_info = bencode.bdecode(line[len(SUB_PROGRESS):].encode(self.encoding))
658 messages = [b.decode("utf-8") for b in task_info]
659 except ValueError as e:
660 # we got malformed data from qsubprocess (bencode failed to decode)
661 # so just show it in the status console
662 self.logMessageEx("qsubprocess error: " + str(e), "error", self.stderr)
663 self.logMessageEx(line, "error", self.stderr)
664 else:
665 self.setProgress(progress, messages, transport_activity.decode("utf-8"))
666 elif line.startswith(SUB_GETPASS):
667 prompt = bittorrent_b_decode_prompt(line[len(SUB_GETPASS):].encode(self.encoding))
668 passwd, ok = QtWidgets.QInputDialog.getText(self, gettext("Enter Password"), prompt, QtWidgets.QLineEdit.Password)
669 data = str(passwd).encode('utf-8'), int(ok)
670 self.process.write(SUB_GETPASS + bencode.bencode(data) + "\n")
671 if not ok:
672 self.abort_futher_processes()
673 elif line.startswith(SUB_GETUSER):
674 prompt = bittorrent_b_decode_prompt(line[len(SUB_GETUSER):].encode(self.encoding))
675 passwd, ok = QtWidgets.QInputDialog.getText(self, gettext("Enter Username"), prompt)
676 data = str(passwd).encode('utf-8'), int(ok)
677 self.process.write(SUB_GETUSER + bencode.bencode(data) + "\n")
678 if not ok:
679 self.abort_futher_processes()
680 elif line.startswith(SUB_GETBOOL):
681 prompt = bittorrent_b_decode_prompt(line[len(SUB_GETBOOL):].encode(self.encoding))
682 button = QtWidgets.QMessageBox.question(self, "Bazaar", prompt, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
683 data = (button == QtWidgets.QMessageBox.Yes)
684 self.process.write(SUB_GETBOOL + bencode.bencode(data) + "\n")
685 elif line.startswith(SUB_CHOOSE):
686 msg, choices, default = bittorrent_b_decode_choose_args(line[len(SUB_CHOOSE):].encode(self.encoding))
687 mbox = QtWidgets.QMessageBox(parent=self)
688 mbox.setText(msg)
689 mbox.setIcon(QtWidgets.QMessageBox.Question)
690 choices = choices.split('\n')
691 index = 0
692 for c in choices:
693 button = mbox.addButton(c, QtWidgets.QMessageBox.AcceptRole)
694 if index == default:
695 mbox.setDefaultButton(button)
696 index += 1
697 index = mbox.exec_()
698 self.process.write(SUB_CHOOSE + bencode.bencode(index) + "\n")
699 elif line.startswith(SUB_ERROR):
700 self.error_class, self.error_data = bittorrent_b_decode_exception_instance(line[len(SUB_ERROR):].encode(self.encoding))
701 elif line.startswith(SUB_NOTIFY):
702 msg = line[len(SUB_NOTIFY):]
703 if msg.startswith(NOTIFY_CONFLICT):
704 self.is_conflicted = True
705 self.conflict_tree_path = bittorrent_b_decode_prompt(msg[len(NOTIFY_CONFLICT):].encode(self.encoding))
706 else:
707 self.logMessageEx(line, 'plain', self.stdout)
708
709 def readStderr(self):
710 data = bytes(self.process.readAllStandardError()).decode(self.encoding, 'replace')
711 if data:
712 self.error.emit(True)
713
714 for line in data.splitlines():
715 # RJLRJL this should be brz, I think
716 # error = line.startswith("bzr: ERROR:")
717 error = line.startswith("brz: ERROR:")
718 self.logMessage(line, error, self.stderr)
719
720 def logMessage(self, message, error=False, terminal_stream=None):
721 kind = 'plain'
722 if error:
723 kind = 'error'
724 self.logMessageEx(message, kind, terminal_stream)
725
726 def logMessageEx(self, message, kind="plain", terminal_stream=None):
727 """Write message to console area.
728 @param kind: kind of message used for selecting style of formatting.
729 Possible kind values:
730 * plain = usual message, written in default style;
731 * error = error message, written in red;
732 * cmdline = show actual command-line, written in blue.
733 @param terminal_stream: if we working in non --ui-mode
734 the message can be echoed to real terminal via specified
735 terminal_stream (e.g. sys.stdout or sys.stderr)
736 """
737 if kind == 'error':
738 char_format = self.errorFormat
739 elif kind == 'cmdline':
740 char_format = self.cmdlineFormat
741 else:
742 char_format = self.messageFormat
743 self.console.setCurrentCharFormat(char_format)
744 self.console.append(message)
745 scrollbar = self.console.verticalScrollBar()
746 scrollbar.setValue(scrollbar.maximum())
747 if not self.ui_mode and terminal_stream:
748 terminal_stream.write(message)
749 terminal_stream.write('\n')
750
751 def reportProcessError(self, error, message=None):
752 self.aborting = False
753 self.setProgress(1000000, [gettext("Failed!")])
754 if message is None:
755 if error == QtCore.QProcess.FailedToStart:
756 message = gettext("Failed to start brz.")
757 else:
758 message = gettext("Error while running brz. (error code: %d)" % error)
759 self.logMessage(message, True)
760 self.failed.emit(self.error_class)
761
762 def onFinished(self, exitCode, exitStatus):
763 self._delete_args_file()
764 if self.aborting:
765 self.aborting = False
766 self.setProgress(1000000, [gettext("Aborted!")])
767 self.failed.emit('Aborted')
768 elif exitCode < 3:
769 if self.commands and not self.aborting:
770 self._start_next()
771 else:
772 self.is_finished = True
773 self.setProgress(1000000, [gettext("Finished!")])
774 if self.is_conflicted:
775 self.conflicted.emit(self.conflict_tree_path)
776 time.sleep(2)
777 self.finished.emit(True)
778 else:
779 self.setProgress(1000000, [gettext("Failed!")])
780 self.failed.emit(self.error_class)
781
782 def _create_args_file(self, text:bytes):
783 """@param text: text to write into temp file,
784 it should be unicode string
785 """
786 if self._args_file:
787 self._delete_args_file()
788 # RJLRJL check QBzr vs QBrz
789 # qdir = os.path.join(tempfile.gettempdir(), 'QBzr', 'qsubprocess')
790 qdir = os.path.join(tempfile.gettempdir(), 'QBrz', 'qsubprocess')
791 if not os.path.isdir(qdir):
792 os.makedirs(qdir)
793 fd, fname = tempfile.mkstemp(dir=qdir)
794 with os.fdopen(fd, "wb") as f:
795 # f.write(text.decode('utf8'))
796 f.write(text)
797 self._args_file = fname
798 return fname
799
800 def _delete_args_file(self):
801 if self._args_file:
802 try:
803 os.unlink(self._args_file)
804 except (IOError, OSError):
805 pass
806 else:
807 self._args_file = None
808
809
810 class SubprocessProgressView (TextProgressView):
811
812 def __init__(self, term_file):
813 TextProgressView.__init__(self, term_file)
814 # The TextProgressView does not show the transport activity untill
815 # there was a progress update. This changed because showing the
816 # transport activity before a progress update would cause artifacts to
817 # remain on the screen. We don't have to worry about that
818 self._have_output = True
819
820 def _repaint(self):
821 if self._last_task:
822 # Since bzr 2.2 _format_task returns a 2-tuple of unicode
823 text, counter = self._format_task(self._last_task)
824 task_info = (text.encode("utf-8"), counter.encode("utf-8"))
825 progress_frac = self._last_task._overall_completion_fraction()
826 if progress_frac is not None:
827 progress = int(progress_frac * 1000000)
828 else:
829 progress = 1
830 else:
831 task_info = ()
832 progress = 0
833
834 trans = self._last_transport_msg.encode("utf-8")
835
836 bdata = bencode.bencode((progress, trans, task_info))
837 self._term_file.write(SUB_PROGRESS + bdata.decode("utf-8") + '\n')
838 self._term_file.flush()
839
840 def clear(self):
841 pass
842
843
844 class SubprocessUIFactory(TextUIFactory):
845
846 def make_progress_view(self):
847 return SubprocessProgressView(self.stdout)
848
849 # This is to be compatabile with bzr less rev 4558
850 _make_progress_view = make_progress_view
851
852 def clear_term(self):
853 """
854 # Prepare the terminal for output.
855
856 # This will, for example, clear text progress bars, and leave the
857 # cursor at the leftmost position.
858 """
859 pass
860
861 def _get_answer_from_main(self, name, arg):
862 self.stdout.write(name + bittorrent_b_encode_prompt(arg) + '\n')
863 self.stdout.flush()
864 line = self.stdin.readline()
865 if line.startswith(name):
866 return bencode.bdecode(line[len(name):].rstrip('\r\n'))
867 raise Exception("Did not receive a answer from the main process.")
868
869 def _choose_from_main(self, msg, choices, default):
870 name = SUB_CHOOSE
871 self.stdout.write(name + bittorrent_b_encode_choose_args(msg, choices, default) + '\n')
872 self.stdout.flush()
873 line = self.stdin.readline()
874 if line.startswith(name):
875 return bencode.bdecode(line[len(name):].rstrip('\r\n'))
876 raise Exception("Did not receive a answer from the main process.")
877
878 def get_password(self, prompt='', **kwargs):
879 prompt = prompt % kwargs
880 passwd, accepted = self._get_answer_from_main(SUB_GETPASS, prompt)
881 if accepted:
882 return passwd
883 else:
884 raise KeyboardInterrupt()
885
886 def get_username(self, prompt='', **kwargs):
887 prompt = prompt % kwargs
888 username, accepted = self._get_answer_from_main(SUB_GETUSER, prompt)
889 if accepted:
890 return username
891 else:
892 raise KeyboardInterrupt()
893
894 def get_boolean(self, prompt):
895 return self._get_answer_from_main(SUB_GETBOOL, prompt+'?')
896
897 def choose(self, msg, choices, default=None):
898 if default is None:
899 default = -1
900 index = self._choose_from_main(msg, choices, default)
901 return index
902
903
904 # [bialix 2010/02/04] body of cmd_qsubprocess has moved from commands.py
905 # to see annotation of cmd_qsubprocess before move use:
906 #
907 # bzr qannotate commands.py -r1117
908
909 @contextmanager
910 def watch_conflicts(on_conflicted):
911 """
912 Call on_conflicted when conflicts generated in the context.
913 :on_conflicted: callable with 1 argument(abspath of wt).
914 """
915 from uuid import uuid1
916 hook_name = uuid1().hex
917
918 def post_merge(m):
919 if len(m.cooked_conflicts) > 0:
920 try:
921 abspath = m.this_tree.abspath('')
922 except AttributeError:
923 abspath = ""
924 on_conflicted(abspath)
925
926 try:
927 from breezy.merge import Merger
928 Merger.hooks.install_named_hook('post_merge', post_merge, hook_name)
929 yield
930 finally:
931 Merger.hooks.uninstall_named_hook('post_merge', hook_name)
932
933
934 def run_subprocess_command(cmd, bencoded=False):
935 """The actual body of qsubprocess.
936 Running specified bzr command in the subprocess.
937 @param cmd: string with command line to run.
938 @param bencoded: either cmd_str is bencoded list or not.
939
940 (RJL: No, I don't know if the above means that it's always a list that's
941 either bencoded or a list that's not, or it's either a bencoded-list
942 or something else bencoded, or something else not bencoded.)
943
944 NOTE: if cmd starts with @ sign then it used as name of the file
945 where actual command line string is saved (utf-8 encoded)...BUT
946 see below.
947
948 RJLRJL: Because of the joy of python2 -> python3, but more because there
949 is/was no class for bencoded, we have to fool about with bytes
950 and strings - what larks!. So, one day, we'll make bencoded a class.
951 Strictly, bencoded (python3) *should* be bytes, but you never can tell.
952 Particularly in this code. And don't get me started on rev_ids.
953
954 Also, the 'starts with @' means it's **NOT BENCODED** (sometimes).
955 How can you tell?
956 Try passing cmd to bdecode: you'll probably get an error about 'identifier 64'.
957 You *can* strip off the leading '@' but what's left behind might or might not
958 be bencoded. I've fixed some of the passing code so that it
959 actually passes bencoded('@'+filename) not '@'+filename, but don't know if I've
960 found it all.
961
962 Breezy's ``run_bzr`` says we should pass 'valid' strings so we need to
963 get rid of any lurking bytes. Unfortunately, we can no longer trust the
964 bencoded flag as passed. Also, run_bzr is lying: if you read the code it actually calls
965 ``_specified_or_unicode_argv()`` which will:
966
967 raise errors.BzrError("argv should be list of unicode strings.")
968
969 so it *actually wants a list of strings*.
970 """
971 if MS_WINDOWS:
972 thread.start_new_thread(windows_emulate_ctrl_c, ())
973 else:
974 signal.signal(signal.SIGINT, sigabrt_handler)
975 ui.ui_factory = SubprocessUIFactory(stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
976
977 if not isinstance(cmd, str) and not isinstance(cmd, bytes):
978 raise TypeError('Only string or bytes accepted ({0}, {1})'.format(cmd, type(cmd)))
979
980 # Right, here we go, we could be a string or bytes
981 # and bencoded might be actually true (it's bytes) or just
982 # pretending (it's not bytes but is bencoded). Also, the cmd might
983 # result in a list once decoded, even though this is not supposed to
984 # be called with one... or perhaps it is (it seems to vary)
985 # Eventually, we need a list in argv to pass to breezy's run_bzr
986 argv = []
987 if bencoded:
988 # if we are bytes AND bencoded (perhaps), decode properly
989 if isinstance(cmd, bytes):
990 s_cmd = bencode.bdecode(cmd)
991 elif isinstance(cmd, str):
992 # Force to bytes to decode it properly from bencoded format
993 # SOMETIMES it's NOT really bencoded, even when it says it is
994 # in which case we will probably get a ValueError
995 b = bytes(cmd, 'utf-8')
996 s_cmd = bencode.bdecode(b)
997 else:
998 if isinstance(cmd, bytes):
999 s_cmd = cmd.decode('utf-8')
1000 else:
1001 s_cmd = cmd
1002
1003 # Sometimes we get a list, decode each line: note that each LINE might be bencoded too
1004 if isinstance(s_cmd, list):
1005 for i, s in enumerate(s_cmd):
1006 if isinstance(s, bytes):
1007 argv.append(s.decode('utf-8'))
1008 else:
1009 # just put the string into it
1010 argv.append(s_cmd)
1011
1012 # Now we are looking for '@' at the start
1013 if s_cmd[0][0] == '@':
1014 fname = s_cmd[1:]
1015 # Changed this: it's written in 'b' so must be read that way too
1016 with open(fname, 'rb') as f:
1017 s_cmd = f.read()
1018 # We stored a bencoded string like b'l6:ignore18:qbrz-setup-iss.loge', so...:
1019 s_cmd = bencode.bdecode(s_cmd)
1020 # ...and again, sometimes we get a list like [b'ignore', b'qbrz-setup-iss.log'], so...
1021 argv = []
1022 if isinstance(s_cmd, list):
1023 for i, s in enumerate(s_cmd):
1024 if isinstance(s, bytes):
1025 argv.append(s.decode('utf-8'))
1026 else:
1027 # just put the string into it
1028 argv.append(s_cmd)
1029
1030 try:
1031 def on_conflicted(wtpath):
1032 # See comment re: frankenstrings below for why we cast to string
1033 # Yes, that *is* a def... in a try..except block.
1034 print("%s%s%s" % (SUB_NOTIFY, NOTIFY_CONFLICT, str(bittorrent_b_encode_prompt(wtpath), 'utf-8')))
1035 with watch_conflicts(on_conflicted):
1036 # _specified_or_unicode_argv should raise a BzrError here
1037 # if we pass a string
1038 return commands.run_bzr(argv)
1039 except (KeyboardInterrupt, SystemExit):
1040 raise
1041 except errors.BzrError as e:
1042 print("%s%s" % (SUB_ERROR, str(bittorrent_b_encode_exception_instance(e), 'utf-8')))
1043 raise
1044 except Exception as e:
1045 # The problem with the original code is that it sends a Frankenstring, for example:
1046 #
1047 # qbrz:ERROR:b'l18:AlreadyBranchErrordee'
1048 #
1049 # which is a str, but with a byte-marked string (b'...') inside it, so
1050 # force it to be properly bytes OR force the bittorrent to string and let
1051 # the receiver sort it out: strictly speaking, it's not really b-encoded
1052 # if it has a prefix so make it a string
1053 print("%s%s" % (SUB_ERROR, str(bittorrent_b_encode_exception_instance(e), 'utf-8')))
1054 raise
1055
1056
1057 def sigabrt_handler(signum, frame):
1058 raise KeyboardInterrupt()
1059
1060
1061 if MS_WINDOWS:
1062 import ctypes
1063 if getattr(sys, "frozen", None):
1064 # this is needed for custom brz.exe builds (without TortoiseBzr inside)
1065 ctypes.__path__.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '_lib', 'ctypes')))
1066 from ctypes import cast, POINTER, Structure
1067 from ctypes.wintypes import DWORD, HANDLE
1068
1069 class PROCESS_INFORMATION(Structure):
1070 _fields_ = [("hProcess", HANDLE),
1071 ("hThread", HANDLE),
1072 ("dwProcessID", DWORD),
1073 ("dwThreadID", DWORD)]
1074
1075 LPPROCESS_INFORMATION = POINTER(PROCESS_INFORMATION)
1076
1077 def get_child_pid(voidptr):
1078 lp = cast(int(voidptr), LPPROCESS_INFORMATION)
1079 return lp.contents.dwProcessID
1080
1081 def get_event_name(child_pid):
1082 return 'qbrz-qsubprocess-%d' % child_pid
1083
1084 def signal_event(child_pid):
1085 import win32event
1086 ev = win32event.CreateEvent(None, 0, 0, get_event_name(child_pid))
1087 try:
1088 win32event.SetEvent(ev)
1089 finally:
1090 ev.Close()
1091
1092 def windows_emulate_ctrl_c():
1093 """To emulate Ctrl+C on Windows we have to wait some global event,
1094 and once it will trigger we will try to interrupt main thread.
1095 IMPORTANT: This function should be invoked as separate thread!
1096 """
1097 import win32event
1098 ev = win32event.CreateEvent(None, 0, 0, get_event_name(os.getpid()))
1099 try:
1100 win32event.WaitForSingleObject(ev, win32event.INFINITE)
1101 finally:
1102 ev.Close()
1103 thread.interrupt_main()
1104
1105 # === Bncode / Bdecode (B-Encode)
1106
1107 # Bencode (pronounced _B-Encode_, not _Ben Code_) is a serialization encoding format used in torrent files for
1108 # the BitTorrent protocol. It consists of a series of strings, integers, lists, and dictionaries; since
1109 # lists and dictionaries contain multiple elements of the Bencode types, they can be nested hierarchically,
1110 # encapsulating complex data structures.
1111 #
1112 # <https://wiki.theory.org/index.php/BitTorrentSpecification#Bencoding>
1113 #
1114 # The elements are:-
1115 #
1116 # * Strings: coded as a decimal number giving the length of the string, then a colon,
1117 # then the string itself; e.g., ``5:stuff``. The empty string is ``0:``
1118 #
1119 # * Integers: coded as the letter ``i``, then the integer
1120 # as a series of decimal digits), then the letter ``e``. E.g., ``i42e`` is 42.
1121 # Leading zeroes (e.g. ``i-04e``) are invalid, except for zero itself: ``i0e``.
1122 #
1123 # * Lists: coded as the letter ``l`` (lower-case L), then the list elements
1124 # (each encoded as one of the Bencode types, which can include other lists), then the
1125 # letter ``e``. E.g.,
1126 #
1127 # ``li42e5:stuffi666ee``
1128 #
1129 # which contains ``42``, ``stuff`` (strictly ``5:stuff``) and ``666``
1130 # as its elements)
1131 #
1132 # * Dictionaries: pairs of keys and values, where the key is a string
1133 # and the value can be any Bencode type; surrounded by an opening letter ``d``
1134 # and closing letter ``e``; keys must appear in alphabetic order; e.g.,
1135 #
1136 # ``d4:testi42e3:zzz4:junke``
1137 #
1138 # is a dictionary where key ``test`` has value ``42`` and key ``zzz`` has value ``junk``.
1139
1140
1141 def bittorrent_b_encode_unicode(args: list) -> bytes:
1142 """
1143 Bencode list of unicode strings as list of utf-8 strings and converting
1144 resulting string to unicode.
1145 Bencode will only accept bytes
1146 """
1147 if isinstance(args, str) or isinstance(args, bytes):
1148 raise TypeError('bittorrent_b_encode_unicode only accepts an iterable got ', type(args))
1149 args_utf8 = bencode.bencode([a.encode('utf-8') for a in args])
1150 return args_utf8
1151
1152
1153 def bittorrent_b_encode_prompt(utf_string: str or bytes) -> bytes:
1154 # The brz.bencode returns bytes but can be passed
1155 # integer, list, bytes, and dictionaries
1156 # BUT only those (so NO strings, even in dictionaries)
1157 # The problem is that the original code called bencode like so:
1158 #
1159 # ``bencode.bencode(arg.encode('unicode-escape'))``
1160 #
1161 # ...and you can only do encode() with bytes
1162 # What we *can* do is insist we only get strings sent to us
1163 if not isinstance(utf_string, str) and not isinstance(utf_string, bytes):
1164 raise TypeError('bittorrent_b_encode_prompt accepts only strings or bytes')
1165 return bencode.bencode(utf_string.encode('utf-8'))
1166
1167
1168 def bittorrent_b_decode_prompt(bencoded_bytes: bytes) -> str:
1169 # bdecode requires an already bittorrent-encoded bytes
1170 # (it'll give a TypeError for plain strings)
1171 # So we can insist that we have bytes
1172 if not isinstance(bencoded_bytes, bytes):
1173 raise TypeError('bittorrent_b_decode_prompt accepts only bytes')
1174 # However, it can return bytes, integer, list or dictionary, but here we assume
1175 # bytes... and we convert them to a string
1176 return bencode.bdecode(bencoded_bytes).decode('utf-8')
1177
1178
1179 def bittorrent_b_encode_choose_args(msg, choices, default):
1180 if default is None:
1181 default = -1
1182 return bencode.bencode([msg.encode('utf-8'), choices.encode('utf-8'), default])
1183
1184
1185 def bittorrent_b_decode_choose_args(s):
1186 msg, choices, default = bencode.bdecode(s)
1187 msg = msg.decode('utf-8')
1188 choices = choices.decode('utf-8')
1189 return msg, choices, default
1190
1191
1192 def bittorrent_b_encode_exception_instance(e: Exception) -> bytes:
1193 """
1194 Serialise the main information about an exception instance with bencode
1195
1196 For now, nearly all exceptions just give the exception name as a string,
1197 but a dictionary is also given that may contain unicode-escaped attributes.
1198
1199 RJLRJL: actually, one has to pass bytes as both dictionary keys and values.
1200 For example:
1201
1202 ``bencode.bencode((b'something', {b'somekey':b'fred'}))``
1203
1204 gives
1205
1206 ``b'l9:somethingd7:somekey4:fredee'``
1207
1208 but if either is a plain string, bencode will choke. b-encoded keys and values
1209 are accepted too, so:
1210
1211 ``bencode.bencode((b'something', {b'7:somekey':b'4:fred'}))``
1212 ``bencode.bencode((b'something', {b'somekey':b'4:fred'}))``
1213 ``bencode.bencode((b'something', {b'7:somekey':b'fred'}))``
1214
1215 would all work, as does, perhaps unsurprisingly:
1216
1217 ``bencode.bencode((b'9:something', {b'7:somekey':b'4:fred'}))``
1218
1219 """
1220 if not isinstance(e, Exception):
1221 raise TypeError('Passed {0} instead of exception'.format(type(e)))
1222 # GZ 2011-04-15: Could use breezy.trace._qualified_exception_name in 2.4
1223 # Convert to bytes...
1224 ename = e.__class__.__name__.encode('utf-8')
1225 d = {}
1226 # For now be conservative and only serialise attributes that will get used
1227 # RJL: in 2020 nothing has yet been added! However, we'll keep the same code
1228 keys = []
1229 if isinstance(e, errors.UncommittedChanges):
1230 # Keys need to be bytes: however, when we use getattr, we need to use
1231 # a string (not bytes). What larks!
1232 keys.append("display_url")
1233 for key in keys:
1234 # getattr and __repr__ can break in lots of ways, so catch everything
1235 # but exceptions that occur as interrupts, allowing for Python 2.4
1236 try:
1237 # Fetch (presumably) a string
1238 val = getattr(e, key)
1239 # RJL: the following is to get the representation as a string
1240 # the problem is that bytes will get wrapped in ".." which is probably not
1241 # what is wanted.
1242 # ``if not isinstance(val, str):
1243 # val = repr(val)
1244 # val = val.decode("ascii", "replace")``
1245 #
1246 # We only need to convert things other than bytes
1247 if not isinstance(val, bytes):
1248 if not isinstance(val, str):
1249 val = repr(val)
1250 # Now convert to bytes...
1251 val = val.encode('utf-8')
1252 except (KeyboardInterrupt, SystemExit):
1253 raise
1254 except KeyError:
1255 val = b'[Qbrz could not find the key [%s] to serialize this attribute]' % key
1256 except:
1257 val = b"[QBrz could not serialize this attribute]"
1258 # The key needs to be bytes too
1259 d[key.encode('utf-8')] = val
1260 return bencode.bencode((ename, d))
1261
1262
1263 def bittorrent_b_decode_exception_instance(bencoded_bytes: bytes) -> (str, list):
1264 """
1265 Deserialise information about an exception instance with bdecode
1266
1267 Returns a string and a list of strings
1268 """
1269 # We'll have something in b-encoded form, such as, for example:
1270 #
1271 # ``b'l15:PermissionErrordee'``
1272 #
1273 # which is 'PermissionError' string and {} (an empty dictionary)
1274 # b-decode will return bytes so, from the above example, we'd get:
1275 #
1276 # ``[b'PermissionError', {}]``
1277 if not isinstance(bencoded_bytes, bytes):
1278 raise TypeError('Bytes required for bittorrent_b_decode_exception_instance')
1279
1280 ename, d = bencode.bdecode(bencoded_bytes)
1281
1282 #
1283 # The returned list needs to have entries with strings, not bytes.
1284 # **However**, the orignal code didn't try to convert the keys.
1285 # Instead, we now create a new_d of the same type as d.
1286 #
1287 # Get the type via type(d) and then instantiate id via () - hence
1288 # new_d = type(d)()
1289 #
1290 new_d = type(d)()
1291 for k in d:
1292 # Convert the key and the value to a string from bytes
1293 # and put the results into new_d
1294 new_d[k.decode('utf-8')] = d[k].decode('utf-8')
1295 # And convert the exception name to a string too
1296 return ename.decode('utf-8'), new_d