summaryrefslogtreecommitdiff
path: root/server/continuedev/libs/util/traceback/traceback_parsers.py
blob: 58a4f728fa1b87b3439087852eb1d7d2b0edb7b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from boltons import tbutils

from ....models.main import Traceback

PYTHON_TRACEBACK_PREFIX = "Traceback (most recent call last):"


def get_python_traceback(output: str) -> str:
    if PYTHON_TRACEBACK_PREFIX in output:
        tb_string = output.split(PYTHON_TRACEBACK_PREFIX)[-1]

        # Then need to remove any lines below the traceback. Do this by noticing that
        # the last line of the traceback is the first (other than they prefix) that doesn't begin with whitespace
        lines = list(filter(lambda x: x.strip() != "", tb_string.splitlines()))
        for i in range(len(lines) - 1):
            if not lines[i].startswith(" "):
                tb_string = "\n".join(lines[: i + 1])
                break

        return PYTHON_TRACEBACK_PREFIX + "\n" + tb_string
    elif "SyntaxError" in output:
        return "SyntaxError" + output.split("SyntaxError")[-1]
    else:
        return None


def get_javascript_traceback(output: str) -> str:
    lines = output.splitlines()
    first_line = None
    for i in range(len(lines) - 1):
        segs = lines[i].split(":")
        if (
            len(segs) > 1
            and segs[0] != ""
            and segs[1].startswith(" ")
            and lines[i + 1].strip().startswith("at")
        ):
            first_line = lines[i]
            break

    if first_line is not None:
        return "\n".join(lines[lines.index(first_line) :])
    else:
        return None


def parse_python_traceback(tb_string: str) -> Traceback:
    # Remove anchor lines - tbutils doesn't always get them right
    tb_string = "\n".join(
        filter(
            lambda x: x.strip().replace("~", "").replace("^", "") != "",
            tb_string.splitlines(),
        )
    )
    exc = tbutils.ParsedException.from_string(tb_string)
    return Traceback.from_tbutil_parsed_exc(exc)