# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/03_utils.capture_trace.ipynb.

# %% auto 0
__all__ = ['strip_junk', 'SaveTraceback']

# %% ../../nbs/03_utils.capture_trace.ipynb 2
import re
from IPython import get_ipython
from .misc import nict

# %% ../../nbs/03_utils.capture_trace.ipynb 3
def strip_junk(text):
    # This line just easts up tokens. We don't need it.
    text = text.replace("---------------------------------------------------------------------------", "")
    ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
    return ansi_escape.sub('', text)


# %% ../../nbs/03_utils.capture_trace.ipynb 5
class SaveTraceback:
    def __init__(self, saved):
        self._saved_showtraceback = saved
        self.tracebacks = []

    def _showtraceback(self, etype, value, stb):
        self.tracebacks.append( nict(
            ename=etype,
            evalue=", ".join(value.args),
            traceback= stb # ["\n".join([ strip_junk(s) for s in stb]) if isinstance(stb, list) else stb]
        ))
        self._saved_showtraceback(etype, value, stb)

    def register(self):
        get_ipython()._showtraceback = self._showtraceback

    def unregister(self):
        get_ipython()._showtraceback = self._saved_showtraceback

