-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.py
264 lines (199 loc) · 5.75 KB
/
base.py
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# base.py
import sys
import inspect
import importlib
import subprocess
import contextlib
import warnings
import logging
import ctypes
import os
from pathlib import Path
import threading
from typing import Any
__all__ = [
"terminate_thread",
"suppress",
"run_silent_command",
"validate_requirement",
"retrieve_name",
"documentation",
"document",
"virtualenv_interpreter_location",
"activate_virtualenv_command",
"root",
"source",
"assets",
"dependencies"
]
def root() -> str:
"""
Returns the root of the source program.
:return: The path to the source.
"""
try:
if os.getcwd() in os.environ['VIRTUAL_ENV']:
path = Path(__file__).parent
else:
raise KeyError
except KeyError:
if os.getcwd() not in (
path := str(Path(__file__).parent)
):
path = os.getcwd()
return str(path)
def source() -> str:
"""
Returns the root of the source program.
:return: The path to the source.
"""
return str(Path(root()) / Path("source"))
def assets() -> str:
"""
Returns the root of the source program.
:return: The path to the source.
"""
return str(Path(source()) / Path("assets"))
def dependencies() -> str:
"""
Returns the root of the source program.
:return: The path to the source.
"""
return str(Path(source()) / Path("dependencies"))
def terminate_thread(thread: threading.Thread) -> None:
"""
Terminates a thread from another thread.
:param thread: The thread instance.
"""
logging.disable(logging.FATAL)
thread_id = thread.ident
if ctypes.pythonapi.PyThreadState_SetAsyncExc(
thread_id, ctypes.py_object(SystemExit)
) > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
logging.getLogger().setLevel(logging.FATAL)
def suppress(silence: bool = True) -> contextlib.AbstractContextManager:
"""
Suppresses the output.
:param silence: The value to silence.
:return: The output suppressor.
"""
if not silence:
return contextlib.nullcontext()
with warnings.catch_warnings(record=True):
return contextlib.redirect_stdout(None)
def run_silent_command(command: str) -> None:
"""
Runs a command with no output.
:param command: The command to run.
"""
subprocess.run(list(command.split(" ")), capture_output=True)
def virtualenv_interpreter_location() -> str:
"""
Returns the location of the interpreter in the venv.
:return: The location of the interpreter.
"""
return os.path.split(sys.executable)[0]
def activate_virtualenv_command() -> str:
"""
Returns the command to activate the virtual env.
:return: The command to activate the venv.
"""
python_startup = (
virtualenv_interpreter_location() /
Path('activate')
)
return (
f"{'' if 'win' in sys.platform else 'source '}"
f"{python_startup}"
)
def validate_requirement(
name: str,
path: str = None,
version: str = None,
quiet: bool = True,
silence: bool = False
) -> None:
"""
Installs the required package.
:param name: The name of the package.
:param path: The path to the package.
:param version: The version to install.
:param quiet: The value to show the installation process.
:param silence: The value to silence.
"""
if version is None:
version = ""
elif isinstance(version, str) and ("=" not in version):
version = f"~{version}"
else:
version = ""
try:
importlib.import_module(name)
except ImportError:
arguments = [
'install',
f'{(path if path is not None else name) + version}'
]
if quiet:
arguments.append("--quiet")
command = (
f"{activate_virtualenv_command()} && "
f"{Path(virtualenv_interpreter_location()) / Path('python')} -m pip "
f"{' '.join(arguments)}"
)
if silence:
with suppress():
os.system(command)
else:
os.system(command)
try:
importlib.import_module(name)
except ImportError:
raise ImportError(f"{name} module is not found.")
def retrieve_name(variable: Any, level: int = 1) -> str:
"""
Gets the name of the source variable of the parameter.
:param variable: The variable to get its source name.
:param level: The level of outer frame to search for.
:return: The source name of the variable.
"""
src = inspect.currentframe()
for _ in range(level):
src = src.f_back
return [
var_name for var_name, var_val in
src.f_locals.items()
if var_val is variable
][0]
def documentation(module: str) -> dict[str, str]:
"""
Documents a module with its content objects documentation.
:param module: The name of the module.
:return: The documentation of the module.
"""
documents = {
f"{value.__module__}.{value.__name__}": value
for name, value in sorted(
list(sys.modules[module].__dict__.items()),
key=lambda item: item[0]
)
if (
hasattr(value, '__module__') and
hasattr(value, '__name__') and
hasattr(value, '__doc__') and
hasattr(value, '__init__')
)
}
return {
key: f'`{key}`\n{value.__doc__}'
for key, value in documents.items()
}
def document(obj: Any) -> None:
"""
Documents a module with its content objects documentation.
:param obj: The obj to document.
"""
obj.__doc__ += """\n\n""".join(
documentation(obj.__module__).values()
)