Skip to content

Commit

Permalink
feat: show source lines in the traceback
Browse files Browse the repository at this point in the history
  • Loading branch information
CNSeniorious000 committed Jun 28, 2024
1 parent fe21fad commit 2625e1e
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/python/app/console.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import builtins
import sys
from collections import ChainMap
from contextlib import suppress
from functools import cached_property
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING

from pyodide.console import ConsoleFuture, PyodideConsole

from .utils.bridge import js_api
from .utils.patches import patch_linecache


class ConsoleGlobals(ChainMap, dict): # type: ignore
Expand All @@ -30,6 +35,34 @@ async def get_repr(self):
return repr(res)


class EnhancedConsole(PyodideConsole):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

with TemporaryDirectory(delete=False) as tempdir:
sys.path.append(tempdir)
self.fake_file = Path(tempdir) / self.filename

self.line_offset = 0

def __del__(self):
with suppress(Exception):
sys.path.remove(str(self.fake_file.parent))

def _append_source_file(self, source: str):
source += "\n"
self.line_offset += source.count("\n")
with self.fake_file.open("a+", encoding="utf-8") as file:
file.write(source)

def runsource(self, source: str, filename="<console>"):
patch_linecache()

fake_source = "\n" * self.line_offset + source
self._append_source_file(source)
return super().runsource(fake_source, filename)


class Console:
@cached_property
def builtins_layer(self):
Expand All @@ -55,7 +88,7 @@ def __getitem__(self, key: str):

context.maps.append(Proxy())

return PyodideConsole(context)
return EnhancedConsole(context)

@js_api
def complete(self, source: str):
Expand Down
9 changes: 9 additions & 0 deletions src/python/app/utils/patches.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
from functools import cache
from inspect import getsource

from .lock import with_lock


@cache
def patch_linecache():
import linecache

source = getsource(linecache).replace(" or (filename.startswith('<') and filename.endswith('>'))", "", 1)
exec(source, linecache.__dict__)


@cache
def patch_console():
from pyodide.console import PyodideConsole
Expand Down

0 comments on commit 2625e1e

Please sign in to comment.