| 1 |
import os |
| 2 |
import re |
| 3 |
|
| 4 |
from ..ft_gettext import current_lang |
| 5 |
from ..message_parser import get_parser |
| 6 |
from ..tb_data import TracebackData |
| 7 |
from ..typing_info import CauseInfo |
| 8 |
from ..utils import get_similar_words |
| 9 |
|
| 10 |
parser = get_parser(FileNotFoundError) |
| 11 |
_ = current_lang.translate |
| 12 |
|
| 13 |
|
| 14 |
@parser._add |
| 15 |
def no_such_file_or_directory( |
| 16 |
value: FileNotFoundError, _tb_data: TracebackData |
| 17 |
) -> CauseInfo: |
| 18 |
pattern = re.compile("No such file or directory: '(.*)'") |
| 19 |
match = re.search(pattern, str(value)) |
| 20 |
if match is None: |
| 21 |
return {} |
| 22 |
|
| 23 |
filepath = match[1] |
| 24 |
dir_, filename = os.path.split(filepath) |
| 25 |
cause = _( |
| 26 |
"In your program, the name of the\n" |
| 27 |
"file that cannot be found is `{filename}`.\n" |
| 28 |
).format(filename=filename) |
| 29 |
if not dir_: |
| 30 |
dir_ = os.getcwd() |
| 31 |
elif not os.path.isdir(dir_): |
| 32 |
cause += _("{directory}\nis not a valid directory.\n").format(directory=dir_) |
| 33 |
return {"cause": cause} |
| 34 |
all_files = os.listdir(dir_) |
| 35 |
all_similar = get_similar_words(filename, all_files) |
| 36 |
cause = _( |
| 37 |
"In your program, the name of the\n" |
| 38 |
"file that cannot be found is `{filename}`.\n" |
| 39 |
).format(filename=filename) |
| 40 |
if dir_: |
| 41 |
cause += _( |
| 42 |
"It was expected to be found in the\n`{directory}` directory.\n" |
| 43 |
).format(directory=dir_) |
| 44 |
if all_similar: |
| 45 |
hint = _("Did you mean `{similar}`?\n").format(similar=all_similar[0]) |
| 46 |
if len(all_similar) == 1: |
| 47 |
cause += _("The file `{similar}` has a similar name.\n").format( |
| 48 |
similar=all_similar[0] |
| 49 |
) |
| 50 |
else: |
| 51 |
cause += ( |
| 52 |
_("Perhaps you meant one of the following files with similar names:\n") |
| 53 |
+ str(all_similar)[1:-1] |
| 54 |
.replace("'", "`") |
| 55 |
.format(all_similar=all_similar) |
| 56 |
+ "\n" |
| 57 |
) |
| 58 |
return {"cause": cause, "suggest": hint} |
| 59 |
return {"cause": cause + _("I have no additional information for you.\n")} |