Debian Codegraph @

friendly_traceback/editors_helpers.py

raw symbols SCIP
1 """
2 editors_helpers.py
3 ------------------
4
5 The functions in this module have been created so that user editors/IDEs
6 could use Friendly without having to change the content of
7 their own programs.
8
9 None of these are part of the public API.
10
11 If you make use of any other function here, please file an issue so
12 it can be determined if it should be added to the public API.
13 """
14
15 import sys
16 from typing import Any, Dict, Tuple, Union
17
18 from .config import session
19 from .ft_gettext import current_lang
20 from .source_cache import cache
21
22
23 def check_syntax(
24 *, source=None, filename="Fake_filename", path=None, include=None, lang=None
25 ) -> Union[bool, Tuple[Any, str]]:
26 """This uses Python's ``compile()`` builtin which does some analysis of
27 its code argument and will raise an exception if it identifies
28 some syntax errors, but also some less common "overflow" and "value"
29 errors.
30
31 Note that there are a few syntax errors that are not caught by this,
32 as they are identified by Python very late in its execution
33 process. See for example
34 `this blog post <https://aroberge.blogspot.com/2019/12/a-tiny-python-exception-oddity.html>`_
35
36 This function can either be used on a file, using the ``path`` argument, or
37 on some code passed as a string, using the ``source`` argument.
38 For the latter case, one can also specify a corresponding ``filename``:
39 this could be useful if this function is invoked from a GUI-based
40 editor.
41
42 Note that the ``path`` argument, if provided, takes precedence
43 over the ``source`` argument.
44
45 Two additional named arguments, ``include`` and ``lang``, can be
46 provided to temporarily set the values to be used during this function
47 call. The original values are restored at the end.
48
49 If friendly exception hook has not been set up prior
50 to calling check_syntax, it will only be used for the duration
51 of this function call.
52
53 Returns a tuple containing a code object and a filename if no exception
54 has been raised, False otherwise.
55
56 """
57 _ = current_lang.translate
58
59 saved_except_hook, saved_include = _save_settings()
60 saved_lang = _temp_set_lang(lang)
61
62 if path is not None:
63 try:
64 with open(path, encoding="utf8") as f:
65 source = f.read()
66 filename = path
67 except Exception: # noqa
68 # Do not show the Python traceback which would include
69 # the call to open() in the traceback
70 if include is None:
71 session.set_include("no_tb")
72 else:
73 session.set_include(include)
74 session.explain_traceback()
75 _reset(saved_except_hook, saved_lang, saved_include)
76 return False
77
78 cache.add(filename, source)
79 try:
80 code = compile(source, filename, "exec")
81 except Exception: # noqa
82 if include is None:
83 session.set_include("explain") # our default
84 else:
85 session.set_include(include)
86 session.explain_traceback()
87 _reset(saved_except_hook, saved_lang, saved_include)
88 return ""
89
90 _reset(saved_except_hook, saved_lang, saved_include)
91 return code
92
93
94 def exec_code(*, source=None, path=None, include=None, lang=None) -> Dict:
95 """This uses check_syntax to see if the code is valid and, if so,
96 executes it into a globals dict containing only
97 ``{"__name__": "__main__"}``.
98 If no ``SyntaxError`` exception is raised, this dict is returned;
99 otherwise, an empty dict is returned.
100
101 It can either be used on a file, using the ``path`` argument, or
102 on some code passed as a string, using the ``source`` argument.
103
104 Note that the ``path`` argument, if provided, takes precedence
105 over the ``source`` argument.
106
107 Two additional named arguments, ``include`` and ``lang``, can be
108 provided to temporarily set the values to be used during this function
109 call. The original values are restored at the end.
110
111 If friendly exception hook has not been set up prior
112 to calling check_syntax, it will only be used for the duration
113 of this function call.
114 """
115 code = check_syntax(source=source, path=path, include=include, lang=lang)
116 if not code:
117 return {}
118
119 saved_except_hook, saved_include = _save_settings()
120 saved_lang = _temp_set_lang(lang)
121
122 module_globals = {"__name__": "__main__"}
123 try:
124 exec(code, module_globals)
125 except Exception: # noqa
126 if include is None:
127 session.set_include("explain") # our default
128 else:
129 session.set_include(include)
130 session.explain_traceback()
131 _reset(saved_except_hook, saved_lang, saved_include)
132 return module_globals
133
134 _reset(saved_except_hook, saved_lang, saved_include)
135 return module_globals
136
137
138 def _temp_set_lang(lang: str) -> str:
139 """If lang is not none, temporarily set session.lang to the provided
140 value. Keep track of the original lang setting and return it.
141
142 A value of None for saved_lang indicates that no resetting will
143 be required.
144 """
145 saved_lang = None
146 if lang is not None:
147 saved_lang = session.lang
148 if saved_lang != lang:
149 session.install_gettext(lang)
150 else:
151 saved_lang = None
152 return saved_lang
153
154
155 def _save_settings():
156 current_except_hook = sys.excepthook
157 current_include = session.include
158
159 return current_except_hook, current_include
160
161
162 def _reset(saved_except_hook, saved_lang, saved_include):
163 """Resets both include and lang to their original values"""
164 if saved_lang is not None:
165 session.install_gettext(saved_lang)
166 session.set_include(saved_include)
167 # set_include(0) restores sys.excepthook to sys.__excepthook__
168 # which might not be what is wanted. So, we reset sys.excepthook last
169 sys.excepthook = saved_except_hook