Debian Codegraph @

lib/trace.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # QBrz - Qt frontend to Breezy commands
4 # Copyright (C) 2009 Mark Hammond <[email protected]>
5 # Copyright (C) 2009 Gary van der Merwe <[email protected]>
6 #
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License
9 # as published by the Free Software Foundation; either version 2
10 # of the License, or (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
21 """Exception handeling and reporting.
22
23 Please see docs/exception_reporting.txt for info on how to use this.
24 """
25
26 import sys
27 import os
28 from io import StringIO
29 import traceback
30
31 from PyQt5 import QtCore, QtGui, QtWidgets
32
33 import breezy
34 from breezy import (
35 errors,
36 osutils,
37 plugin,
38 )
39 from breezy.trace import (
40 mutter,
41 note,
42 print_exception as _breezy_print_exception,
43 report_exception as _breezy_report_exception,
44 )
45 from breezy.plugins.qbrz.lib.i18n import gettext
46 import breezy.plugins.qbrz.lib.resources
47
48
49 class StopException(Exception):
50 """A exception that is ignored in our error reporting, which can be used
51 to stop a process due to user action. (Similar to KeyInterupt)
52 """
53 pass
54
55 MAIN_LOAD_METHOD = 0
56 """The exception is beening reported from the main loading method.
57 Causes the window to be closed.
58 """
59 SUB_LOAD_METHOD = 1
60 """The exception is beening reported from the sub loading method.
61 Does not cause the window to me closed. This is typicaly used when a user
62 enters a branch location on one of our forms, and we try load that branch.
63 """
64 ITEM_OR_EVENT_METHOD = 2
65 """The exception is beening reported from a method that is called per item.
66 The user is allowed to ignore the error, or close the window.
67 """
68
69 _file_bugs_url = "https://bugs.launchpad.net/qbrz/+filebug"
70
71 def set_file_bugs_url(url):
72 global _file_bugs_url
73 _file_bugs_url = url
74
75 closing_due_to_error = False
76
77 def create_lockerror_dialog(type, window=None):
78 msgbox = QtWidgets.QMessageBox(parent=window)
79 msgbox.setIcon(QtWidgets.QMessageBox.Warning)
80 msgbox.setText(gettext("Could not acquire lock. Please retry later."))
81 if type == MAIN_LOAD_METHOD:
82 msgbox.addButton(QtWidgets.QMessageBox.Close)
83 else:
84 msgbox.addButton(QtWidgets.QMessageBox.Ok)
85 return msgbox
86
87 def report_exception(exc_info=None, type=MAIN_LOAD_METHOD, window=None, ui_mode=False):
88 """Report an exception.
89
90 The error is reported to the console or a message box, depending on the type.
91 """
92
93 # We only want one error to show if the user chose Close
94 global closing_due_to_error
95 # 0.20 special: We check hasattr() first to work around
96 # <http://bugs.python.org/issue4230>
97 if closing_due_to_error or (hasattr(window, 'closing_due_to_error') and window.closing_due_to_error):
98 return
99
100 if exc_info is None:
101 exc_info = sys.exc_info()
102
103 exc_type, exc_object, exc_tb = exc_info
104
105 # Don't show error for StopException
106 if isinstance(exc_object, StopException):
107 # Do we maybe want to log this?
108 return
109 # RJLRJL check for bzr / brz issues
110 msg_box = ((type == MAIN_LOAD_METHOD and (window and window.ui_mode or ui_mode)) or not type == MAIN_LOAD_METHOD)
111 pdb = os.environ.get('BZR_PDB')
112 if pdb:
113 msg_box = False
114
115 if msg_box:
116 err_file = StringIO()
117 else:
118 err_file = sys.stderr
119
120 # always tell bzr to report it, so it ends up in the log.
121 # See https://bugs.launchpad.net/bzr/+bug/785695
122 error_type = _breezy_report_exception(exc_info, err_file)
123 backtrace = traceback.format_exception(*exc_info)
124 mutter(''.join(backtrace))
125
126 if (type == MAIN_LOAD_METHOD and window):
127 window.ret_code = error_type
128
129 # XXX This is very similar to breezy.commands.exception_to_return_code.
130 # We shoud get bzr to refactor so that that this is reuseable.
131 if pdb:
132 # With out this - pyQt shows lot of warnings. see:
133 # http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#using-pyqt-from-the-python-shell
134 QtCore.pyqtRemoveInputHook()
135
136 print('**** entering debugger')
137 tb = exc_info[2]
138 import pdb
139 if sys.version_info[:2] < (2, 6):
140 # XXX: we want to do
141 # pdb.post_mortem(tb)
142 # but because pdb.post_mortem gives bad results for tracebacks
143 # from inside generators, we do it manually.
144 # (http://bugs.python.org/issue4150, fixed in Python 2.6)
145
146 # Setup pdb on the traceback
147 p = pdb.Pdb()
148 p.reset()
149 p.setup(tb.tb_frame, tb)
150 # Point the debugger at the deepest frame of the stack
151 p.curindex = len(p.stack) - 1
152 p.curframe = p.stack[p.curindex][0]
153 # Start the pdb prompt.
154 p.print_stack_entry(p.stack[p.curindex])
155 p.execRcLines()
156 p.cmdloop()
157 else:
158 pdb.post_mortem(tb)
159
160 close = True
161 if msg_box:
162 if isinstance(exc_object, errors.LockContention):
163 msg_box = create_lockerror_dialog(error_type, window)
164
165 elif error_type == errors.EXIT_INTERNAL_ERROR:
166 # this is a copy of breezy.trace.report_bug
167 # but we seperate the message, and the trace back,
168 # and addes a hyper link to the filebug page.
169 traceback_file = StringIO()
170 _breezy_print_exception(exc_info, traceback_file)
171 traceback_file.write('\n')
172 traceback_file.write('brz %s on python %s (%s)\n' % (breezy.__version__,
173 breezy._format_version_tuple(sys.version_info),
174 sys.platform))
175 traceback_file.write('arguments: %r\n' % sys.argv)
176 traceback_file.write(
177 'encoding: %r, fsenc: %r, lang: %r\n' % (
178 osutils.get_user_encoding(), sys.getfilesystemencoding(),
179 os.environ.get('LANG')))
180 traceback_file.write("plugins:\n")
181 for name, a_plugin in sorted(plugin.plugins().items()):
182 traceback_file.write(" %-20s %s [%s]\n" % (name, a_plugin.path(), a_plugin.__version__))
183
184
185 msg_box = ErrorReport(gettext("Error"),
186 True,
187 traceback_file.getvalue(),
188 exc_info,
189 type,
190 window)
191 else:
192 msg_box = ErrorReport(gettext("Error"),
193 False,
194 err_file.getvalue(),
195 exc_info,
196 type,
197 window)
198 # RJLRJL check for bzr / brz issues
199 if window is None:
200 icon = QtGui.QIcon()
201 icon.addFile(":/bzr-16.png", QtCore.QSize(16, 16))
202 icon.addFile(":/bzr-32.png", QtCore.QSize(32, 32))
203 icon.addFile(":/bzr-48.png", QtCore.QSize(48, 48))
204 msg_box.setWindowIcon(icon)
205
206 msg_box.exec_()
207
208 if not msg_box.result() == QtWidgets.QMessageBox.Close:
209 close = False
210
211 if close:
212 if window is None:
213 closing_due_to_error = True
214 QtCore.QCoreApplication.instance().quit()
215 else:
216 window.closing_due_to_error = True
217 window.close()
218 return error_type
219
220 class ErrorReport(QtWidgets.QDialog):
221 """A dialogue box for displaying and optionally reporting crashes in bzr/qbrz/bzr explorer."""
222 def __init__(self, title, message_internal, trace_back, exc_info, type=MAIN_LOAD_METHOD,
223 parent=None):
224
225 QtWidgets.QDialog.__init__ (self, parent)
226
227 self.buttonbox = QtWidgets.QDialogButtonBox()
228
229 if parent:
230 win_title = None
231 if hasattr(parent, 'title'):
232 if isinstance(parent.title, str):
233 win_title = parent.title
234 elif isinstance(title, (list, tuple)):
235 # just the first item is more usefull.
236 win_title = parent.title[0]
237 else:
238 if hasattr(parent, 'windowTitle'):
239 win_title = parent.windowTitle()
240
241 if win_title:
242 close_label = gettext("Close %s Window") % win_title
243 else:
244 close_label = gettext("Close Window")
245 else:
246 close_label = gettext("Close Application")
247
248 # PyQt is stupid and thinks QMessageBox.StandardButton and
249 # QDialogButtonBox.StandardButton are different, so we have to
250 # duplicate this :-(
251 if type == MAIN_LOAD_METHOD:
252 button = self.buttonbox.addButton(QtWidgets.QDialogButtonBox.Close)
253 button.setText(close_label)
254 elif type == SUB_LOAD_METHOD:
255 button = self.buttonbox.addButton(QtWidgets.QDialogButtonBox.Ok)
256 button.setText(gettext("Close Error Dialog"))
257 elif type == ITEM_OR_EVENT_METHOD:
258 button = self.buttonbox.addButton(QtWidgets.QDialogButtonBox.Close)
259 button.setText(close_label)
260 button = self.buttonbox.addButton(QtWidgets.QDialogButtonBox.Ignore)
261 button.setText(gettext("Ignore Error"))
262
263 def report_bug():
264 from breezy import crash
265 #Using private method because breezy.crash is not currently intended for reuse from GUIs
266 #see https://bugs.launchpad.net/bzr/+bug/785696
267 crash_filename = crash._write_apport_report_to_file(exc_info)
268
269 try:
270 import apport
271 except ImportError as e:
272 mutter("No Apport available to Bazaar")
273 if message_internal:
274 message = ('Bazaar has encountered an internal error. Please '
275 'report a bug at <a href="%s">%s</a> including this '
276 'traceback, and a description of what you were doing '
277 'when the error occurred.'
278 % (_file_bugs_url, _file_bugs_url))
279 else:
280 message = ('Bazaar has encountered an environmental error. Please '
281 'report a bug if this is not the result of a local problem '
282 'at <a href="%s">%s</a> including this '
283 'traceback, and a description of what you were doing '
284 'when the error occurred.'
285 % (_file_bugs_url, _file_bugs_url))
286 else:
287 report_bug_button = self.buttonbox.addButton(gettext("Report Bazaar Error"), QtWidgets.QDialogButtonBox.ActionRole)
288 report_bug_button.clicked.connect(report_bug)
289 if message_internal:
290 message = ("Bazaar has encountered an internal error. Please report a"
291 " bug.")
292 else:
293 message = ("Bazaar has encountered an environmental error. Please report a"
294 " bug if this is not the result of a local problem.")
295 message = "<big>%s</big>" % (message)
296
297 label = QtWidgets.QLabel(message)
298 label.setWordWrap(True)
299 label.setAlignment(QtCore.Qt.AlignVCenter|QtCore.Qt.AlignLeft)
300 label.linkActivated['QString'].connect(self.link_clicked)
301
302 icon_label = QtWidgets.QLabel()
303 icon_label.setPixmap(self.style().standardPixmap(
304 QtWidgets.QStyle.SP_MessageBoxCritical))
305
306 self.show_trace_back_button = QtWidgets.QPushButton(gettext("Show Error Details >>>"))
307 self.show_trace_back_button.clicked.connect(self.show_trace_back)
308 self.trace_back_label = QtWidgets.QTextEdit()
309 self.trace_back_label.setPlainText (trace_back)
310 self.trace_back_label.setReadOnly(True)
311 self.trace_back_label.hide()
312
313 self.buttonbox.clicked [QtWidgets.QAbstractButton].connect(self.clicked)
314
315 vbox = QtWidgets.QVBoxLayout()
316
317 hbox = QtWidgets.QHBoxLayout()
318 hbox.addWidget(icon_label)
319 hbox.addWidget(label, 10)
320 vbox.addLayout(hbox)
321
322 hbox = QtWidgets.QHBoxLayout()
323 hbox.addWidget(self.show_trace_back_button)
324 hbox.addStretch()
325 vbox.addLayout(hbox)
326 vbox.addWidget(self.trace_back_label)
327
328 hbox = QtWidgets.QHBoxLayout()
329 hbox.addWidget(self.buttonbox)
330 vbox.addLayout(hbox)
331
332 self.setLayout(vbox)
333
334 self.setWindowTitle(title)
335
336 icon = QtGui.QIcon()
337 icon.addFile(":/bzr-16.png", QtCore.QSize(16, 16))
338 icon.addFile(":/bzr-32.png", QtCore.QSize(32, 32))
339 icon.addFile(":/bzr-48.png", QtCore.QSize(48, 48))
340 self.setWindowIcon(icon)
341
342 def show_trace_back(self):
343 """toggle the text box containing the full exception details"""
344 self.trace_back_label.setVisible(not self.trace_back_label.isVisible())
345 if self.trace_back_label.isVisible():
346 self.show_trace_back_button.setText(gettext("<<< Hide Error Details"))
347 else:
348 self.show_trace_back_button.setText(gettext("Show Error Details >>>"))
349 self.resize(self.sizeHint())
350
351 def clicked(self, button):
352 self.done(int(self.buttonbox.standardButton(button)))
353
354 def link_clicked(self, url):
355 # We can't import this at the top of the file because util imports
356 # this file. XXX - The is probably a sign that util is to big, and
357 # we need to split it up.
358 from breezy.plugins.qbrz.lib.util import open_browser
359 open_browser(str(url))
360
361 def reports_exception(type=MAIN_LOAD_METHOD):
362 """Decorator to report Exceptions raised from the called method
363 """
364 def reports_exception_decorator(f):
365
366 def reports_exception_decorate(*args, **kargs):
367 try:
368 return f(*args, **kargs)
369 except Exception:
370 # args[0] - typycaly self, may be a QWidget. Pass it's window
371 if isinstance(args[0], QtWidgets.QWidget):
372 report_exception(type=type, window=args[0].window())
373 else:
374 report_exception(type=type)
375
376 return reports_exception_decorate
377
378 return reports_exception_decorator
379
380 def excepthook(type, value, traceback):
381 exc_info = (type, value, traceback)
382 report_exception(exc_info=exc_info,
383 type=ITEM_OR_EVENT_METHOD)