2019-12-02 21:46:54 +00:00
|
|
|
import codecs
|
|
|
|
import inspect
|
|
|
|
import os
|
|
|
|
import re
|
|
|
|
import sys
|
|
|
|
import sysconfig
|
|
|
|
import traceback
|
2022-01-24 04:07:52 +00:00
|
|
|
import typing as t
|
|
|
|
from html import escape
|
2019-12-02 21:46:54 +00:00
|
|
|
from tokenize import TokenError
|
2022-01-24 04:07:52 +00:00
|
|
|
from types import CodeType
|
|
|
|
from types import TracebackType
|
2019-12-02 21:46:54 +00:00
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
from .._internal import _to_str
|
2019-12-02 21:46:54 +00:00
|
|
|
from ..filesystem import get_filesystem_encoding
|
|
|
|
from ..utils import cached_property
|
|
|
|
from .console import Console
|
|
|
|
|
|
|
|
_coding_re = re.compile(br"coding[:=]\s*([-\w.]+)")
|
|
|
|
_line_re = re.compile(br"^(.*?)$", re.MULTILINE)
|
|
|
|
_funcdef_re = re.compile(r"^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)")
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
HEADER = """\
|
2019-12-02 21:46:54 +00:00
|
|
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
|
|
|
|
"http://www.w3.org/TR/html4/loose.dtd">
|
|
|
|
<html>
|
|
|
|
<head>
|
|
|
|
<title>%(title)s // Werkzeug Debugger</title>
|
|
|
|
<link rel="stylesheet" href="?__debugger__=yes&cmd=resource&f=style.css"
|
|
|
|
type="text/css">
|
|
|
|
<!-- We need to make sure this has a favicon so that the debugger does
|
2022-01-24 04:07:52 +00:00
|
|
|
not accidentally trigger a request to /favicon.ico which might
|
|
|
|
change the application's state. -->
|
2019-12-02 21:46:54 +00:00
|
|
|
<link rel="shortcut icon"
|
|
|
|
href="?__debugger__=yes&cmd=resource&f=console.png">
|
|
|
|
<script src="?__debugger__=yes&cmd=resource&f=debugger.js"></script>
|
|
|
|
<script type="text/javascript">
|
|
|
|
var TRACEBACK = %(traceback_id)d,
|
|
|
|
CONSOLE_MODE = %(console)s,
|
|
|
|
EVALEX = %(evalex)s,
|
|
|
|
EVALEX_TRUSTED = %(evalex_trusted)s,
|
|
|
|
SECRET = "%(secret)s";
|
|
|
|
</script>
|
|
|
|
</head>
|
|
|
|
<body style="background-color: #fff">
|
|
|
|
<div class="debugger">
|
|
|
|
"""
|
2022-01-24 04:07:52 +00:00
|
|
|
FOOTER = """\
|
2019-12-02 21:46:54 +00:00
|
|
|
<div class="footer">
|
|
|
|
Brought to you by <strong class="arthur">DON'T PANIC</strong>, your
|
|
|
|
friendly Werkzeug powered traceback interpreter.
|
|
|
|
</div>
|
|
|
|
</div>
|
|
|
|
|
|
|
|
<div class="pin-prompt">
|
|
|
|
<div class="inner">
|
|
|
|
<h3>Console Locked</h3>
|
|
|
|
<p>
|
|
|
|
The console is locked and needs to be unlocked by entering the PIN.
|
|
|
|
You can find the PIN printed out on the standard output of your
|
|
|
|
shell that runs the server.
|
|
|
|
<form>
|
|
|
|
<p>PIN:
|
|
|
|
<input type=text name=pin size=14>
|
|
|
|
<input type=submit name=btn value="Confirm Pin">
|
|
|
|
</form>
|
|
|
|
</div>
|
|
|
|
</div>
|
|
|
|
</body>
|
|
|
|
</html>
|
|
|
|
"""
|
|
|
|
|
|
|
|
PAGE_HTML = (
|
|
|
|
HEADER
|
2022-01-24 04:07:52 +00:00
|
|
|
+ """\
|
2019-12-02 21:46:54 +00:00
|
|
|
<h1>%(exception_type)s</h1>
|
|
|
|
<div class="detail">
|
|
|
|
<p class="errormsg">%(exception)s</p>
|
|
|
|
</div>
|
|
|
|
<h2 class="traceback">Traceback <em>(most recent call last)</em></h2>
|
|
|
|
%(summary)s
|
|
|
|
<div class="plain">
|
|
|
|
<p>
|
2022-01-24 04:07:52 +00:00
|
|
|
This is the Copy/Paste friendly version of the traceback.
|
2019-12-02 21:46:54 +00:00
|
|
|
</p>
|
|
|
|
<textarea cols="50" rows="10" name="code" readonly>%(plaintext)s</textarea>
|
|
|
|
</div>
|
|
|
|
<div class="explanation">
|
|
|
|
The debugger caught an exception in your WSGI application. You can now
|
|
|
|
look at the traceback which led to the error. <span class="nojavascript">
|
|
|
|
If you enable JavaScript you can also use additional features such as code
|
|
|
|
execution (if the evalex feature is enabled), automatic pasting of the
|
|
|
|
exceptions and much more.</span>
|
|
|
|
</div>
|
|
|
|
"""
|
|
|
|
+ FOOTER
|
|
|
|
+ """
|
|
|
|
<!--
|
|
|
|
|
|
|
|
%(plaintext_cs)s
|
|
|
|
|
|
|
|
-->
|
|
|
|
"""
|
|
|
|
)
|
|
|
|
|
|
|
|
CONSOLE_HTML = (
|
|
|
|
HEADER
|
2022-01-24 04:07:52 +00:00
|
|
|
+ """\
|
2019-12-02 21:46:54 +00:00
|
|
|
<h1>Interactive Console</h1>
|
|
|
|
<div class="explanation">
|
|
|
|
In this console you can execute Python expressions in the context of the
|
|
|
|
application. The initial namespace was created by the debugger automatically.
|
|
|
|
</div>
|
|
|
|
<div class="console"><div class="inner">The Console requires JavaScript.</div></div>
|
|
|
|
"""
|
|
|
|
+ FOOTER
|
|
|
|
)
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
SUMMARY_HTML = """\
|
2019-12-02 21:46:54 +00:00
|
|
|
<div class="%(classes)s">
|
|
|
|
%(title)s
|
|
|
|
<ul>%(frames)s</ul>
|
|
|
|
%(description)s
|
|
|
|
</div>
|
|
|
|
"""
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
FRAME_HTML = """\
|
2019-12-02 21:46:54 +00:00
|
|
|
<div class="frame" id="frame-%(id)d">
|
|
|
|
<h4>File <cite class="filename">"%(filename)s"</cite>,
|
|
|
|
line <em class="line">%(lineno)s</em>,
|
|
|
|
in <code class="function">%(function_name)s</code></h4>
|
|
|
|
<div class="source %(library)s">%(lines)s</div>
|
|
|
|
</div>
|
|
|
|
"""
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
SOURCE_LINE_HTML = """\
|
2019-12-02 21:46:54 +00:00
|
|
|
<tr class="%(classes)s">
|
|
|
|
<td class=lineno>%(lineno)s</td>
|
|
|
|
<td>%(code)s</td>
|
|
|
|
</tr>
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def render_console_html(secret: str, evalex_trusted: bool = True) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
return CONSOLE_HTML % {
|
|
|
|
"evalex": "true",
|
|
|
|
"evalex_trusted": "true" if evalex_trusted else "false",
|
|
|
|
"console": "true",
|
|
|
|
"title": "Console",
|
|
|
|
"secret": secret,
|
|
|
|
"traceback_id": -1,
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def get_current_traceback(
|
2022-01-24 04:07:52 +00:00
|
|
|
ignore_system_exceptions: bool = False,
|
|
|
|
show_hidden_frames: bool = False,
|
|
|
|
skip: int = 0,
|
|
|
|
) -> "Traceback":
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Get the current exception info as `Traceback` object. Per default
|
|
|
|
calling this method will reraise system exceptions such as generator exit,
|
|
|
|
system exit or others. This behavior can be disabled by passing `False`
|
|
|
|
to the function as first parameter.
|
|
|
|
"""
|
2022-01-24 04:07:52 +00:00
|
|
|
info = t.cast(
|
|
|
|
t.Tuple[t.Type[BaseException], BaseException, TracebackType], sys.exc_info()
|
|
|
|
)
|
|
|
|
exc_type, exc_value, tb = info
|
|
|
|
|
|
|
|
if ignore_system_exceptions and exc_type in {
|
|
|
|
SystemExit,
|
|
|
|
KeyboardInterrupt,
|
|
|
|
GeneratorExit,
|
|
|
|
}:
|
|
|
|
raise
|
|
|
|
for _ in range(skip):
|
2019-12-02 21:46:54 +00:00
|
|
|
if tb.tb_next is None:
|
|
|
|
break
|
|
|
|
tb = tb.tb_next
|
|
|
|
tb = Traceback(exc_type, exc_value, tb)
|
|
|
|
if not show_hidden_frames:
|
|
|
|
tb.filter_hidden_frames()
|
|
|
|
return tb
|
|
|
|
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
class Line:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Helper for the source renderer."""
|
|
|
|
|
|
|
|
__slots__ = ("lineno", "code", "in_frame", "current")
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def __init__(self, lineno: int, code: str) -> None:
|
2019-12-02 21:46:54 +00:00
|
|
|
self.lineno = lineno
|
|
|
|
self.code = code
|
|
|
|
self.in_frame = False
|
|
|
|
self.current = False
|
|
|
|
|
|
|
|
@property
|
2022-01-24 04:07:52 +00:00
|
|
|
def classes(self) -> t.List[str]:
|
2019-12-02 21:46:54 +00:00
|
|
|
rv = ["line"]
|
|
|
|
if self.in_frame:
|
|
|
|
rv.append("in-frame")
|
|
|
|
if self.current:
|
|
|
|
rv.append("current")
|
|
|
|
return rv
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def render(self) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
return SOURCE_LINE_HTML % {
|
2022-01-24 04:07:52 +00:00
|
|
|
"classes": " ".join(self.classes),
|
2019-12-02 21:46:54 +00:00
|
|
|
"lineno": self.lineno,
|
|
|
|
"code": escape(self.code),
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
class Traceback:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Wraps a traceback."""
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
exc_type: t.Type[BaseException],
|
|
|
|
exc_value: BaseException,
|
|
|
|
tb: TracebackType,
|
|
|
|
) -> None:
|
2019-12-02 21:46:54 +00:00
|
|
|
self.exc_type = exc_type
|
|
|
|
self.exc_value = exc_value
|
|
|
|
self.tb = tb
|
|
|
|
|
|
|
|
exception_type = exc_type.__name__
|
|
|
|
if exc_type.__module__ not in {"builtins", "__builtin__", "exceptions"}:
|
2022-01-24 04:07:52 +00:00
|
|
|
exception_type = f"{exc_type.__module__}.{exception_type}"
|
2019-12-02 21:46:54 +00:00
|
|
|
self.exception_type = exception_type
|
|
|
|
|
|
|
|
self.groups = []
|
|
|
|
memo = set()
|
|
|
|
while True:
|
|
|
|
self.groups.append(Group(exc_type, exc_value, tb))
|
|
|
|
memo.add(id(exc_value))
|
2022-01-24 04:07:52 +00:00
|
|
|
exc_value = exc_value.__cause__ or exc_value.__context__ # type: ignore
|
2019-12-02 21:46:54 +00:00
|
|
|
if exc_value is None or id(exc_value) in memo:
|
|
|
|
break
|
|
|
|
exc_type = type(exc_value)
|
2022-01-24 04:07:52 +00:00
|
|
|
tb = exc_value.__traceback__ # type: ignore
|
2019-12-02 21:46:54 +00:00
|
|
|
self.groups.reverse()
|
|
|
|
self.frames = [frame for group in self.groups for frame in group.frames]
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def filter_hidden_frames(self) -> None:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Remove the frames according to the paste spec."""
|
|
|
|
for group in self.groups:
|
|
|
|
group.filter_hidden_frames()
|
|
|
|
|
|
|
|
self.frames[:] = [frame for group in self.groups for frame in group.frames]
|
|
|
|
|
|
|
|
@property
|
2022-01-24 04:07:52 +00:00
|
|
|
def is_syntax_error(self) -> bool:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Is it a syntax error?"""
|
|
|
|
return isinstance(self.exc_value, SyntaxError)
|
|
|
|
|
|
|
|
@property
|
2022-01-24 04:07:52 +00:00
|
|
|
def exception(self) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""String representation of the final exception."""
|
|
|
|
return self.groups[-1].exception
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def log(self, logfile: t.Optional[t.IO[str]] = None) -> None:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Log the ASCII traceback into a file object."""
|
|
|
|
if logfile is None:
|
|
|
|
logfile = sys.stderr
|
2022-01-24 04:07:52 +00:00
|
|
|
tb = f"{self.plaintext.rstrip()}\n"
|
|
|
|
logfile.write(tb)
|
|
|
|
|
|
|
|
def render_summary(self, include_title: bool = True) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Render the traceback for the interactive console."""
|
|
|
|
title = ""
|
|
|
|
classes = ["traceback"]
|
|
|
|
if not self.frames:
|
|
|
|
classes.append("noframe-traceback")
|
|
|
|
frames = []
|
|
|
|
else:
|
|
|
|
library_frames = sum(frame.is_library for frame in self.frames)
|
|
|
|
mark_lib = 0 < library_frames < len(self.frames)
|
|
|
|
frames = [group.render(mark_lib=mark_lib) for group in self.groups]
|
|
|
|
|
|
|
|
if include_title:
|
|
|
|
if self.is_syntax_error:
|
2022-01-24 04:07:52 +00:00
|
|
|
title = "Syntax Error"
|
2019-12-02 21:46:54 +00:00
|
|
|
else:
|
2022-01-24 04:07:52 +00:00
|
|
|
title = "Traceback <em>(most recent call last)</em>:"
|
2019-12-02 21:46:54 +00:00
|
|
|
|
|
|
|
if self.is_syntax_error:
|
2022-01-24 04:07:52 +00:00
|
|
|
description = f"<pre class=syntaxerror>{escape(self.exception)}</pre>"
|
2019-12-02 21:46:54 +00:00
|
|
|
else:
|
2022-01-24 04:07:52 +00:00
|
|
|
description = f"<blockquote>{escape(self.exception)}</blockquote>"
|
2019-12-02 21:46:54 +00:00
|
|
|
|
|
|
|
return SUMMARY_HTML % {
|
2022-01-24 04:07:52 +00:00
|
|
|
"classes": " ".join(classes),
|
|
|
|
"title": f"<h3>{title if title else ''}</h3>",
|
|
|
|
"frames": "\n".join(frames),
|
|
|
|
"description": description,
|
2019-12-02 21:46:54 +00:00
|
|
|
}
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def render_full(
|
|
|
|
self,
|
|
|
|
evalex: bool = False,
|
|
|
|
secret: t.Optional[str] = None,
|
|
|
|
evalex_trusted: bool = True,
|
|
|
|
) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Render the Full HTML page with the traceback info."""
|
|
|
|
exc = escape(self.exception)
|
|
|
|
return PAGE_HTML % {
|
|
|
|
"evalex": "true" if evalex else "false",
|
|
|
|
"evalex_trusted": "true" if evalex_trusted else "false",
|
|
|
|
"console": "false",
|
|
|
|
"title": exc,
|
|
|
|
"exception": exc,
|
|
|
|
"exception_type": escape(self.exception_type),
|
|
|
|
"summary": self.render_summary(include_title=False),
|
|
|
|
"plaintext": escape(self.plaintext),
|
|
|
|
"plaintext_cs": re.sub("-{2,}", "-", self.plaintext),
|
|
|
|
"traceback_id": self.id,
|
|
|
|
"secret": secret,
|
|
|
|
}
|
|
|
|
|
|
|
|
@cached_property
|
2022-01-24 04:07:52 +00:00
|
|
|
def plaintext(self) -> str:
|
|
|
|
return "\n".join([group.render_text() for group in self.groups])
|
2019-12-02 21:46:54 +00:00
|
|
|
|
|
|
|
@property
|
2022-01-24 04:07:52 +00:00
|
|
|
def id(self) -> int:
|
2019-12-02 21:46:54 +00:00
|
|
|
return id(self)
|
|
|
|
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
class Group:
|
|
|
|
"""A group of frames for an exception in a traceback. If the
|
|
|
|
exception has a ``__cause__`` or ``__context__``, there are multiple
|
|
|
|
exception groups.
|
2019-12-02 21:46:54 +00:00
|
|
|
"""
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
exc_type: t.Type[BaseException],
|
|
|
|
exc_value: BaseException,
|
|
|
|
tb: TracebackType,
|
|
|
|
) -> None:
|
2019-12-02 21:46:54 +00:00
|
|
|
self.exc_type = exc_type
|
|
|
|
self.exc_value = exc_value
|
|
|
|
self.info = None
|
2022-01-24 04:07:52 +00:00
|
|
|
if exc_value.__cause__ is not None:
|
|
|
|
self.info = (
|
|
|
|
"The above exception was the direct cause of the following exception"
|
|
|
|
)
|
|
|
|
elif exc_value.__context__ is not None:
|
|
|
|
self.info = (
|
|
|
|
"During handling of the above exception, another exception occurred"
|
|
|
|
)
|
2019-12-02 21:46:54 +00:00
|
|
|
|
|
|
|
self.frames = []
|
|
|
|
while tb is not None:
|
|
|
|
self.frames.append(Frame(exc_type, exc_value, tb))
|
2022-01-24 04:07:52 +00:00
|
|
|
tb = tb.tb_next # type: ignore
|
2019-12-02 21:46:54 +00:00
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def filter_hidden_frames(self) -> None:
|
|
|
|
# An exception may not have a traceback to filter frames, such
|
|
|
|
# as one re-raised from ProcessPoolExecutor.
|
|
|
|
if not self.frames:
|
|
|
|
return
|
|
|
|
|
|
|
|
new_frames: t.List[Frame] = []
|
2019-12-02 21:46:54 +00:00
|
|
|
hidden = False
|
|
|
|
|
|
|
|
for frame in self.frames:
|
|
|
|
hide = frame.hide
|
|
|
|
if hide in ("before", "before_and_this"):
|
|
|
|
new_frames = []
|
|
|
|
hidden = False
|
|
|
|
if hide == "before_and_this":
|
|
|
|
continue
|
|
|
|
elif hide in ("reset", "reset_and_this"):
|
|
|
|
hidden = False
|
|
|
|
if hide == "reset_and_this":
|
|
|
|
continue
|
|
|
|
elif hide in ("after", "after_and_this"):
|
|
|
|
hidden = True
|
|
|
|
if hide == "after_and_this":
|
|
|
|
continue
|
|
|
|
elif hide or hidden:
|
|
|
|
continue
|
|
|
|
new_frames.append(frame)
|
|
|
|
|
|
|
|
# if we only have one frame and that frame is from the codeop
|
|
|
|
# module, remove it.
|
|
|
|
if len(new_frames) == 1 and self.frames[0].module == "codeop":
|
|
|
|
del self.frames[:]
|
|
|
|
|
|
|
|
# if the last frame is missing something went terrible wrong :(
|
|
|
|
elif self.frames[-1] in new_frames:
|
|
|
|
self.frames[:] = new_frames
|
|
|
|
|
|
|
|
@property
|
2022-01-24 04:07:52 +00:00
|
|
|
def exception(self) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""String representation of the exception."""
|
|
|
|
buf = traceback.format_exception_only(self.exc_type, self.exc_value)
|
|
|
|
rv = "".join(buf).strip()
|
2022-01-24 04:07:52 +00:00
|
|
|
return _to_str(rv, "utf-8", "replace")
|
2019-12-02 21:46:54 +00:00
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def render(self, mark_lib: bool = True) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
out = []
|
|
|
|
if self.info is not None:
|
2022-01-24 04:07:52 +00:00
|
|
|
out.append(f'<li><div class="exc-divider">{self.info}:</div>')
|
2019-12-02 21:46:54 +00:00
|
|
|
for frame in self.frames:
|
2022-01-24 04:07:52 +00:00
|
|
|
title = f' title="{escape(frame.info)}"' if frame.info else ""
|
|
|
|
out.append(f"<li{title}>{frame.render(mark_lib=mark_lib)}")
|
|
|
|
return "\n".join(out)
|
2019-12-02 21:46:54 +00:00
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def render_text(self) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
out = []
|
|
|
|
if self.info is not None:
|
2022-01-24 04:07:52 +00:00
|
|
|
out.append(f"\n{self.info}:\n")
|
|
|
|
out.append("Traceback (most recent call last):")
|
2019-12-02 21:46:54 +00:00
|
|
|
for frame in self.frames:
|
|
|
|
out.append(frame.render_text())
|
|
|
|
out.append(self.exception)
|
2022-01-24 04:07:52 +00:00
|
|
|
return "\n".join(out)
|
2019-12-02 21:46:54 +00:00
|
|
|
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
class Frame:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""A single frame in a traceback."""
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
exc_type: t.Type[BaseException],
|
|
|
|
exc_value: BaseException,
|
|
|
|
tb: TracebackType,
|
|
|
|
) -> None:
|
2019-12-02 21:46:54 +00:00
|
|
|
self.lineno = tb.tb_lineno
|
|
|
|
self.function_name = tb.tb_frame.f_code.co_name
|
|
|
|
self.locals = tb.tb_frame.f_locals
|
|
|
|
self.globals = tb.tb_frame.f_globals
|
|
|
|
|
|
|
|
fn = inspect.getsourcefile(tb) or inspect.getfile(tb)
|
|
|
|
if fn[-4:] in (".pyo", ".pyc"):
|
|
|
|
fn = fn[:-1]
|
|
|
|
# if it's a file on the file system resolve the real filename.
|
|
|
|
if os.path.isfile(fn):
|
|
|
|
fn = os.path.realpath(fn)
|
2022-01-24 04:07:52 +00:00
|
|
|
self.filename = _to_str(fn, get_filesystem_encoding())
|
|
|
|
self.module = self.globals.get("__name__", self.locals.get("__name__"))
|
|
|
|
self.loader = self.globals.get("__loader__", self.locals.get("__loader__"))
|
2019-12-02 21:46:54 +00:00
|
|
|
self.code = tb.tb_frame.f_code
|
|
|
|
|
|
|
|
# support for paste's traceback extensions
|
|
|
|
self.hide = self.locals.get("__traceback_hide__", False)
|
|
|
|
info = self.locals.get("__traceback_info__")
|
|
|
|
if info is not None:
|
2022-01-24 04:07:52 +00:00
|
|
|
info = _to_str(info, "utf-8", "replace")
|
2019-12-02 21:46:54 +00:00
|
|
|
self.info = info
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def render(self, mark_lib: bool = True) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Render a single frame in a traceback."""
|
|
|
|
return FRAME_HTML % {
|
|
|
|
"id": self.id,
|
|
|
|
"filename": escape(self.filename),
|
|
|
|
"lineno": self.lineno,
|
|
|
|
"function_name": escape(self.function_name),
|
|
|
|
"lines": self.render_line_context(),
|
|
|
|
"library": "library" if mark_lib and self.is_library else "",
|
|
|
|
}
|
|
|
|
|
|
|
|
@cached_property
|
2022-01-24 04:07:52 +00:00
|
|
|
def is_library(self) -> bool:
|
2019-12-02 21:46:54 +00:00
|
|
|
return any(
|
2022-01-24 04:07:52 +00:00
|
|
|
self.filename.startswith(os.path.realpath(path))
|
|
|
|
for path in sysconfig.get_paths().values()
|
2019-12-02 21:46:54 +00:00
|
|
|
)
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def render_text(self) -> str:
|
|
|
|
return (
|
|
|
|
f' File "{self.filename}", line {self.lineno}, in {self.function_name}\n'
|
|
|
|
f" {self.current_line.strip()}"
|
2019-12-02 21:46:54 +00:00
|
|
|
)
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def render_line_context(self) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
before, current, after = self.get_context_lines()
|
|
|
|
rv = []
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def render_line(line: str, cls: str) -> None:
|
2019-12-02 21:46:54 +00:00
|
|
|
line = line.expandtabs().rstrip()
|
|
|
|
stripped_line = line.strip()
|
|
|
|
prefix = len(line) - len(stripped_line)
|
|
|
|
rv.append(
|
2022-01-24 04:07:52 +00:00
|
|
|
f'<pre class="line {cls}"><span class="ws">{" " * prefix}</span>'
|
|
|
|
f"{escape(stripped_line) if stripped_line else ' '}</pre>"
|
2019-12-02 21:46:54 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
for line in before:
|
|
|
|
render_line(line, "before")
|
|
|
|
render_line(current, "current")
|
|
|
|
for line in after:
|
|
|
|
render_line(line, "after")
|
|
|
|
|
|
|
|
return "\n".join(rv)
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def get_annotated_lines(self) -> t.List[Line]:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Helper function that returns lines with extra information."""
|
|
|
|
lines = [Line(idx + 1, x) for idx, x in enumerate(self.sourcelines)]
|
|
|
|
|
|
|
|
# find function definition and mark lines
|
|
|
|
if hasattr(self.code, "co_firstlineno"):
|
|
|
|
lineno = self.code.co_firstlineno - 1
|
|
|
|
while lineno > 0:
|
|
|
|
if _funcdef_re.match(lines[lineno].code):
|
|
|
|
break
|
|
|
|
lineno -= 1
|
|
|
|
try:
|
2022-01-24 04:07:52 +00:00
|
|
|
offset = len(inspect.getblock([f"{x.code}\n" for x in lines[lineno:]]))
|
2019-12-02 21:46:54 +00:00
|
|
|
except TokenError:
|
|
|
|
offset = 0
|
|
|
|
for line in lines[lineno : lineno + offset]:
|
|
|
|
line.in_frame = True
|
|
|
|
|
|
|
|
# mark current line
|
|
|
|
try:
|
|
|
|
lines[self.lineno - 1].current = True
|
|
|
|
except IndexError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return lines
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def eval(self, code: t.Union[str, CodeType], mode: str = "single") -> t.Any:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Evaluate code in the context of the frame."""
|
2022-01-24 04:07:52 +00:00
|
|
|
if isinstance(code, str):
|
2019-12-02 21:46:54 +00:00
|
|
|
code = compile(code, "<interactive>", mode)
|
|
|
|
return eval(code, self.globals, self.locals)
|
|
|
|
|
|
|
|
@cached_property
|
2022-01-24 04:07:52 +00:00
|
|
|
def sourcelines(self) -> t.List[str]:
|
|
|
|
"""The sourcecode of the file as list of strings."""
|
2019-12-02 21:46:54 +00:00
|
|
|
# get sourcecode from loader or file
|
|
|
|
source = None
|
|
|
|
if self.loader is not None:
|
|
|
|
try:
|
|
|
|
if hasattr(self.loader, "get_source"):
|
|
|
|
source = self.loader.get_source(self.module)
|
|
|
|
elif hasattr(self.loader, "get_source_by_code"):
|
|
|
|
source = self.loader.get_source_by_code(self.code)
|
|
|
|
except Exception:
|
|
|
|
# we munch the exception so that we don't cause troubles
|
|
|
|
# if the loader is broken.
|
|
|
|
pass
|
|
|
|
|
|
|
|
if source is None:
|
|
|
|
try:
|
2022-01-24 04:07:52 +00:00
|
|
|
with open(self.filename, mode="rb") as f:
|
|
|
|
source = f.read()
|
|
|
|
except OSError:
|
2019-12-02 21:46:54 +00:00
|
|
|
return []
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
# already str? return right away
|
|
|
|
if isinstance(source, str):
|
2019-12-02 21:46:54 +00:00
|
|
|
return source.splitlines()
|
|
|
|
|
|
|
|
charset = "utf-8"
|
2022-01-24 04:07:52 +00:00
|
|
|
if source.startswith(codecs.BOM_UTF8):
|
2019-12-02 21:46:54 +00:00
|
|
|
source = source[3:]
|
|
|
|
else:
|
|
|
|
for idx, match in enumerate(_line_re.finditer(source)):
|
2022-01-24 04:07:52 +00:00
|
|
|
coding_match = _coding_re.search(match.group())
|
|
|
|
if coding_match is not None:
|
|
|
|
charset = coding_match.group(1).decode("utf-8")
|
2019-12-02 21:46:54 +00:00
|
|
|
break
|
|
|
|
if idx > 1:
|
|
|
|
break
|
|
|
|
|
|
|
|
# on broken cookies we fall back to utf-8 too
|
2022-01-24 04:07:52 +00:00
|
|
|
charset = _to_str(charset)
|
2019-12-02 21:46:54 +00:00
|
|
|
try:
|
|
|
|
codecs.lookup(charset)
|
|
|
|
except LookupError:
|
|
|
|
charset = "utf-8"
|
|
|
|
|
|
|
|
return source.decode(charset, "replace").splitlines()
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def get_context_lines(
|
|
|
|
self, context: int = 5
|
|
|
|
) -> t.Tuple[t.List[str], str, t.List[str]]:
|
2019-12-02 21:46:54 +00:00
|
|
|
before = self.sourcelines[self.lineno - context - 1 : self.lineno - 1]
|
|
|
|
past = self.sourcelines[self.lineno : self.lineno + context]
|
|
|
|
return (before, self.current_line, past)
|
|
|
|
|
|
|
|
@property
|
2022-01-24 04:07:52 +00:00
|
|
|
def current_line(self) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
try:
|
|
|
|
return self.sourcelines[self.lineno - 1]
|
|
|
|
except IndexError:
|
2022-01-24 04:07:52 +00:00
|
|
|
return ""
|
2019-12-02 21:46:54 +00:00
|
|
|
|
|
|
|
@cached_property
|
2022-01-24 04:07:52 +00:00
|
|
|
def console(self) -> Console:
|
2019-12-02 21:46:54 +00:00
|
|
|
return Console(self.globals, self.locals)
|
|
|
|
|
|
|
|
@property
|
2022-01-24 04:07:52 +00:00
|
|
|
def id(self) -> int:
|
2019-12-02 21:46:54 +00:00
|
|
|
return id(self)
|