File: file_not_found_error.py

package info (click to toggle)
python-friendly-traceback 0.7.62%2Bgit20240811.d7dbff6-1.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 9,264 kB
  • sloc: python: 21,500; makefile: 4
file content (59 lines) | stat: -rw-r--r-- 2,060 bytes parent folder | download
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
57
58
59
import os
import re

from ..ft_gettext import current_lang
from ..message_parser import get_parser
from ..tb_data import TracebackData  # for type checking only
from ..typing_info import CauseInfo  # for type checking only
from ..utils import get_similar_words

parser = get_parser(FileNotFoundError)
_ = current_lang.translate


@parser._add
def no_such_file_or_directory(
    value: FileNotFoundError, _tb_data: TracebackData
) -> CauseInfo:
    pattern = re.compile("No such file or directory: '(.*)'")
    match = re.search(pattern, str(value))
    if match is None:
        return {}

    filepath = match[1]
    dir_, filename = os.path.split(filepath)
    cause = _(
        "In your program, the name of the\n"
        "file that cannot be found is `{filename}`.\n"
    ).format(filename=filename)
    if not dir_:
        dir_ = os.getcwd()
    elif not os.path.isdir(dir_):
        cause += _("{directory}\nis not a valid directory.\n").format(directory=dir_)
        return {"cause": cause}
    all_files = os.listdir(dir_)
    all_similar = get_similar_words(filename, all_files)
    cause = _(
        "In your program, the name of the\n"
        "file that cannot be found is `{filename}`.\n"
    ).format(filename=filename)
    if dir_:
        cause += _(
            "It was expected to be found in the\n`{directory}` directory.\n"
        ).format(directory=dir_)
    if all_similar:
        hint = _("Did you mean `{similar}`?\n").format(similar=all_similar[0])
        if len(all_similar) == 1:
            cause += _("The file `{similar}` has a similar name.\n").format(
                similar=all_similar[0]
            )
        else:
            cause += (
                _("Perhaps you meant one of the following files with similar names:\n")
                + str(all_similar)[1:-1]
                .replace("'", "`")
                .format(all_similar=all_similar)
                + "\n"
            )
        return {"cause": cause, "suggest": hint}
    return {"cause": cause + _("I have no additional information for you.\n")}