Debian Codegraph @

friendly_traceback/path_info.py

raw symbols SCIP
1 """path_info.py
2
3 In many places, by default we exclude the files from this package,
4 thus restricting tracebacks to code written by the users.
5
6 If Friendly-traceback is used by some other program,
7 it might be desirable to exclude additional files.
8 """
9
10 import os
11 import sys
12 from typing import Set, TypeVar
13
14 import asttokens # Only use it as a representative to find site-packages
15
16 from .ft_gettext import current_lang
17 from .typing_info import StrPath
18
19 EXCLUDED_FILE_PATH: Set[str] = set()
20 EXCLUDED_DIR_NAMES: Set[str] = set()
21 SITE_PACKAGES = os.path.abspath(os.path.join(os.path.dirname(asttokens.__file__), ".."))
22 PYTHON_LIB = os.path.abspath(os.path.dirname(os.__file__))
23 FRIENDLY = os.path.abspath(os.path.dirname(__file__))
24 TESTS = os.path.abspath(os.path.join(FRIENDLY, "..", "tests"))
25
26
27 def exclude_file_from_traceback(full_path: StrPath) -> None:
28 """Exclude a file from appearing in a traceback generated by
29 Friendly-traceback. Note that this does not apply to
30 the true Python traceback obtained using "debug_tb".
31 """
32 # full_path could be a pathlib.Path instance
33 full_path = str(full_path)
34 if full_path.startswith("<"):
35 # https://github.com/friendly-traceback/friendly-traceback/issues/107
36 EXCLUDED_FILE_PATH.add(full_path)
37 return
38 # full_path could be a relative path; see issue #81
39 full_path = os.path.abspath(full_path)
40 if not os.path.isfile(full_path):
41 raise RuntimeError(
42 f"{full_path} is not a valid file path; it cannot be excluded."
43 )
44 EXCLUDED_FILE_PATH.add(full_path)
45
46
47 def exclude_directory_from_traceback(dir_name: StrPath) -> None:
48 """Exclude all files found in a given directory, including sub-directories,
49 from appearing in a traceback generated by Friendly.
50 Note that this does not apply to the true Python traceback
51 obtained using "debug_tb".
52 """
53 if not os.path.isdir(dir_name):
54 raise RuntimeError(f"{dir_name} is not a directory; it cannot be excluded.")
55 # dir_name could be a pathlib.Path instance.
56 dir_name = str(dir_name)
57 # Suppose we have dir_name = "this/path" instead of "this/path/".
58 # Later, when we want to exclude a directory, we get the following file path:
59 # "this/path2/name.py". If we don't append the ending "/", we would exclude
60 # this file by error in is_excluded_file below.
61 if dir_name[-1] != os.path.sep:
62 dir_name += os.path.sep
63 EXCLUDED_DIR_NAMES.add(dir_name)
64
65
66 dirname = os.path.abspath(os.path.dirname(__file__))
67 exclude_directory_from_traceback(dirname)
68
69
70 def is_excluded_file(full_path: StrPath, python_excluded: bool = True) -> bool:
71 """Determines if the file belongs to the group that is excluded from tracebacks."""
72 # full_path could be a pathlib.Path instance
73 full_path = str(full_path)
74 if full_path.startswith("<") and full_path in EXCLUDED_FILE_PATH:
75 return True
76 if full_path.startswith("<frozen "):
77 return True
78
79 full_path = os.path.abspath(full_path)
80 for dirs in EXCLUDED_DIR_NAMES:
81 if full_path.startswith(dirs):
82 return True
83 # Design choice: we exclude all files from the Python standard library
84 # but not those that have been installed by the user if python_excluded is True.
85 if (
86 full_path.startswith(PYTHON_LIB)
87 and not full_path.startswith(SITE_PACKAGES)
88 and python_excluded
89 ):
90 return True
91 return full_path in EXCLUDED_FILE_PATH
92
93
94 def include_file_in_traceback(full_path: str) -> None:
95 """Reverses the effect of ``exclude_file_from_traceback()`` so that
96 the file can potentially appear in later tracebacks generated
97 by Friendly-traceback.
98
99 A typical pattern might be something like::
100
101 import some_module
102
103 reverted = not is_excluded_file(some_module.__file__)
104 if reverted:
105 exclude_file_from_traceback(some_module.__file__)
106
107 try:
108 some_module.do_something(...)
109 except Exception:
110 friendly_traceback.explain_traceback()
111 finally:
112 if reverted:
113 include_file_in_traceback(some_module.__file__)
114
115 """
116 full_path = str(full_path)
117 full_path = os.path.abspath(full_path)
118 EXCLUDED_FILE_PATH.discard(full_path)
119
120
121 class PathUtil:
122 def __init__(self) -> None:
123 self.home = os.path.expanduser("~")
124
125 MaybeText = TypeVar("MaybeText", str, None)
126
127 def shorten_path(self, path: MaybeText) -> MaybeText: # pragma: no cover
128 from .config import session
129
130 if path is None: # can happen in some rare cases
131 return path
132 if path in ["<stdin>", "<string>"]:
133 return path
134 orig_path = path
135 path = path.replace("'", "") # We might get passed a path repr
136 path = os.path.abspath(path)
137 path_lower = path.casefold()
138
139 if "ipykernel" in path:
140 new_path = shorten_jupyter_kernel(orig_path)
141 if new_path:
142 return new_path
143 elif "<pyshell#" in path:
144 path = "<pyshell#" + path.split("<pyshell#")[1]
145 elif "<ipython-input-" in path:
146 parts = path.split("<ipython")
147 parts = parts[1].split("-")
148 path = "[" + parts[-2] + "]"
149 elif "<friendly-console:" in path:
150 split_path = path.split("<friendly-console:")[1]
151 if session.ipython_prompt:
152 path = "[" + split_path[:-1] + "]"
153 else:
154 path = "<friendly-console:" + split_path
155 elif path_lower.startswith(SITE_PACKAGES.casefold()):
156 path = "LOCAL:" + path[len(SITE_PACKAGES) :]
157 elif path_lower.startswith(PYTHON_LIB.casefold()):
158 path = "PYTHON_LIB:" + path[len(PYTHON_LIB) :]
159 elif path_lower.startswith(FRIENDLY.casefold()):
160 path = "FRIENDLY:" + path[len(FRIENDLY) :]
161 elif path_lower.startswith(TESTS.casefold()):
162 path = "TESTS:" + path[len(TESTS) :]
163 elif path_lower.startswith(self.home.casefold()):
164 if not os.path.exists(path):
165 return orig_path
166 path = "HOME:" + path[len(self.home) :]
167 return path
168
169
170 def shorten_jupyter_kernel(path: str) -> str: # pragma: no cover
171 from .source_cache import cache
172
173 if "__main__" in sys.modules:
174 main = sys.modules["__main__"]
175 if "In" in dir(main):
176 ipython_inputs = getattr(main, "In")
177 else:
178 return ""
179 else:
180 return ""
181
182 lines = cache.get_source_lines(path)
183 source = "".join(lines)
184 source = source.strip().replace("\r", "")
185 if not source:
186 return ""
187 found = 0
188 new_path = ""
189 for index, inp in enumerate(ipython_inputs):
190 inp = inp.strip().replace("\r", "")
191 if source == inp:
192 new_path = f"[{index}]"
193 found += 1
194 if found > 1:
195 new_path = new_path + "?"
196 return new_path
197
198
199 path_utils = PathUtil()
200
201
202 def show_paths() -> None: # pragma: no cover
203 """To avoid displaying very long file paths to the user,
204 Friendly-traceback tries to shorten them using some easily
205 recognized synonyms. This function shows the path synonyms
206 currently used.
207 """
208 _ = current_lang.translate
209 print("HOME =", path_utils.home)
210 print("LOCAL =", SITE_PACKAGES)
211 print("PYTHON_LIB =", PYTHON_LIB)
212 if FRIENDLY != SITE_PACKAGES:
213 print("FRIENDLY = ", FRIENDLY)
214 print(_("The default directory is {dirname}.").format(dirname=os.getcwd()))