abstract-utilities 0.2.2.412__py3-none-any.whl → 0.2.2.414__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of abstract-utilities might be problematic. Click here for more details.
- abstract_utilities/__init__.py +12 -8
- abstract_utilities/cmd_utils/imports/__init__.py +1 -0
- abstract_utilities/cmd_utils/imports/imports.py +10 -0
- abstract_utilities/cmd_utils/pexpect_utils.py +310 -0
- abstract_utilities/cmd_utils/user_utils.py +1 -1
- abstract_utilities/env_utils/__init__.py +3 -0
- abstract_utilities/env_utils/abstractEnv.py +129 -0
- abstract_utilities/env_utils/envy_it.py +33 -0
- abstract_utilities/env_utils/imports/__init__.py +2 -0
- abstract_utilities/env_utils/imports/imports.py +8 -0
- abstract_utilities/env_utils/imports/utils.py +122 -0
- abstract_utilities/{path_utils → file_utils}/__init__.py +0 -3
- abstract_utilities/file_utils/file_utils/__init__.py +4 -0
- abstract_utilities/file_utils/file_utils/file_filters.py +104 -0
- abstract_utilities/file_utils/file_utils/file_utils.py +194 -0
- abstract_utilities/file_utils/file_utils/imports.py +1 -0
- abstract_utilities/{path_utils → file_utils}/imports/__init__.py +1 -0
- abstract_utilities/file_utils/imports/classes.py +125 -0
- abstract_utilities/file_utils/imports/imports.py +11 -0
- abstract_utilities/{path_utils → file_utils}/imports/module_imports.py +3 -1
- abstract_utilities/{path_utils → file_utils}/req.py +2 -5
- abstract_utilities/{path_utils/path_utils.py → path_utils.py} +4 -1
- abstract_utilities/robust_readers/__init__.py +1 -0
- abstract_utilities/robust_readers/imports.py +1 -1
- abstract_utilities/ssh_utils/__init__.py +3 -0
- abstract_utilities/ssh_utils/classes.py +127 -0
- abstract_utilities/ssh_utils/imports.py +11 -0
- abstract_utilities/ssh_utils/pexpect_utils.py +315 -0
- abstract_utilities/ssh_utils/utils.py +122 -0
- {abstract_utilities-0.2.2.412.dist-info → abstract_utilities-0.2.2.414.dist-info}/METADATA +1 -1
- {abstract_utilities-0.2.2.412.dist-info → abstract_utilities-0.2.2.414.dist-info}/RECORD +36 -18
- abstract_utilities/path_utils/file_filters.py +0 -213
- abstract_utilities/path_utils/imports/imports.py +0 -6
- /abstract_utilities/{path_utils → file_utils/file_utils}/filter_params.py +0 -0
- /abstract_utilities/{path_utils/file_utils.py → file_utils/file_utils/map_utils.py} +0 -0
- /abstract_utilities/{path_utils → file_utils}/imports/constants.py +0 -0
- {abstract_utilities-0.2.2.412.dist-info → abstract_utilities-0.2.2.414.dist-info}/WHEEL +0 -0
- {abstract_utilities-0.2.2.412.dist-info → abstract_utilities-0.2.2.414.dist-info}/top_level.txt +0 -0
abstract_utilities/__init__.py
CHANGED
|
@@ -74,13 +74,17 @@ from .path_utils import (get_file_create_time,
|
|
|
74
74
|
make_dirs,
|
|
75
75
|
remove_directory,
|
|
76
76
|
remove_path,
|
|
77
|
-
|
|
78
|
-
get_file_map,
|
|
79
|
-
get_file_type,
|
|
80
|
-
call_for_all_tabs,
|
|
81
|
-
get_files_and_dirs,
|
|
82
|
-
define_defaults
|
|
77
|
+
|
|
83
78
|
)
|
|
79
|
+
from .file_utils import (
|
|
80
|
+
get_file_parts,
|
|
81
|
+
get_file_map,
|
|
82
|
+
get_file_type,
|
|
83
|
+
call_for_all_tabs,
|
|
84
|
+
get_files_and_dirs,
|
|
85
|
+
define_defaults,
|
|
86
|
+
ScanConfig
|
|
87
|
+
)
|
|
84
88
|
from .list_utils import (get_highest_value_obj,
|
|
85
89
|
make_list,
|
|
86
90
|
safe_list_return,
|
|
@@ -156,5 +160,5 @@ from .log_utils import get_caller_info,get_logFile,print_or_log,get_json_call_re
|
|
|
156
160
|
from .error_utils import try_func
|
|
157
161
|
from .class_utils import alias,get_class_inputs,get_set_attr
|
|
158
162
|
from .robust_reader import *
|
|
159
|
-
|
|
160
|
-
|
|
163
|
+
from .robust_readers import *
|
|
164
|
+
from .ssh_utils import *
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .imports import *
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# remote_fs.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from typing import *
|
|
4
|
+
import subprocess, shlex, os, fnmatch, glob, posixpath, re
|
|
5
|
+
# ---- import your existing pieces ----
|
|
6
|
+
from ...type_utils import make_list # whatever you already have
|
|
7
|
+
from ...time_utils import get_sleep
|
|
8
|
+
from ...ssh_utils import *
|
|
9
|
+
from ...env_utils import *
|
|
10
|
+
from ...string_clean import eatOuter
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
|
|
2
|
+
from .ssh_utils import *
|
|
3
|
+
from ..env_utils import *
|
|
4
|
+
# pexpect is optional; import lazily if you prefer
|
|
5
|
+
|
|
6
|
+
# keep your execute_cmd; add a thin wrapper that supports stdin text cleanly
|
|
7
|
+
def execute_cmd_input(
|
|
8
|
+
*args,
|
|
9
|
+
input_text: str | None = None,
|
|
10
|
+
outfile: str | None = None,
|
|
11
|
+
**kwargs
|
|
12
|
+
) -> str:
|
|
13
|
+
"""
|
|
14
|
+
Like execute_cmd, but lets you pass text to stdin (subprocess.run(input=...)).
|
|
15
|
+
"""
|
|
16
|
+
if input_text is not None:
|
|
17
|
+
kwargs["input"] = input_text
|
|
18
|
+
# ensure text mode so Python passes str not bytes
|
|
19
|
+
kwargs.setdefault("text", True)
|
|
20
|
+
return execute_cmd(*args, outfile=outfile, **kwargs)
|
|
21
|
+
|
|
22
|
+
# -------------------------
|
|
23
|
+
# Core: capture + printing
|
|
24
|
+
# -------------------------
|
|
25
|
+
def exec_sudo_capture(
|
|
26
|
+
cmd: str,
|
|
27
|
+
*,
|
|
28
|
+
password: str | None = None,
|
|
29
|
+
key: str | None = None,
|
|
30
|
+
user_at_host: str | None = None,
|
|
31
|
+
cwd: str | None = None,
|
|
32
|
+
print_output: bool = False,
|
|
33
|
+
) -> str:
|
|
34
|
+
"""
|
|
35
|
+
Run a sudo command and return its output (no temp file).
|
|
36
|
+
"""
|
|
37
|
+
if password is None:
|
|
38
|
+
password = get_env_value(key=key) if key else get_sudo_password()
|
|
39
|
+
|
|
40
|
+
sudo_cmd = f"sudo -S -k {cmd}"
|
|
41
|
+
|
|
42
|
+
if user_at_host:
|
|
43
|
+
# build the remote command (bash -lc + optional cd)
|
|
44
|
+
remote = get_remote_cmd(cmd=sudo_cmd, user_at_host=user_at_host, cwd=cwd)
|
|
45
|
+
# feed password to remote's stdin (ssh forwards stdin)
|
|
46
|
+
out = execute_cmd_input(remote, input_text=password + "\n",
|
|
47
|
+
shell=True, text=True, capture_output=True)
|
|
48
|
+
else:
|
|
49
|
+
out = execute_cmd_input(sudo_cmd, input_text=password + "\n",
|
|
50
|
+
shell=True, text=True, capture_output=True, cwd=cwd)
|
|
51
|
+
|
|
52
|
+
if print_output:
|
|
53
|
+
print_cmd(cmd, out or "")
|
|
54
|
+
return out or ""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# ---------------------------------------------------
|
|
59
|
+
# SUDO helpers (local + SSH) with env/password options
|
|
60
|
+
# ---------------------------------------------------
|
|
61
|
+
def exec_sudo(
|
|
62
|
+
cmd: str,
|
|
63
|
+
*,
|
|
64
|
+
password: Optional[str] = None,
|
|
65
|
+
key: Optional[str] = None,
|
|
66
|
+
user_at_host: Optional[str] = None,
|
|
67
|
+
cwd: Optional[str] = None,
|
|
68
|
+
outfile: Optional[str] = None,
|
|
69
|
+
print_output: bool = False,
|
|
70
|
+
) -> str:
|
|
71
|
+
"""
|
|
72
|
+
Execute `cmd` via sudo either locally or on remote.
|
|
73
|
+
Password order of precedence:
|
|
74
|
+
1) `password` arg
|
|
75
|
+
2) `key` -> get_env_value(key)
|
|
76
|
+
3) get_sudo_password()
|
|
77
|
+
|
|
78
|
+
Uses: sudo -S -k (-S read password from stdin, -k invalidate cached timestamp)
|
|
79
|
+
"""
|
|
80
|
+
if password is None:
|
|
81
|
+
if key:
|
|
82
|
+
password = get_env_value(key=key)
|
|
83
|
+
else:
|
|
84
|
+
password = get_sudo_password()
|
|
85
|
+
|
|
86
|
+
# Compose the sudo command that reads from stdin
|
|
87
|
+
sudo_cmd = f"sudo -S -k {cmd}"
|
|
88
|
+
|
|
89
|
+
if user_at_host:
|
|
90
|
+
# For remote: the password is piped to SSH stdin, which flows to remote sudo's stdin.
|
|
91
|
+
remote = get_remote_cmd(cmd=sudo_cmd, user_at_host=user_at_host, cwd=cwd)
|
|
92
|
+
full = f"printf %s {shlex.quote(password)} | {remote}"
|
|
93
|
+
out = execute_cmd(full, shell=True, text=True, capture_output=True, outfile=outfile)
|
|
94
|
+
else:
|
|
95
|
+
# Local
|
|
96
|
+
full = f"printf %s {shlex.quote(password)} | {sudo_cmd}"
|
|
97
|
+
out = execute_cmd(full, shell=True, text=True, capture_output=True, outfile=outfile)
|
|
98
|
+
|
|
99
|
+
if print_output:
|
|
100
|
+
print_cmd(cmd, out or "")
|
|
101
|
+
return out or ""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# -------------------------------------------------
|
|
105
|
+
# Fire-and-forget (file-backed) compatible runner
|
|
106
|
+
# -------------------------------------------------
|
|
107
|
+
def cmd_run(
|
|
108
|
+
cmd: str,
|
|
109
|
+
output_text: str | None = None,
|
|
110
|
+
print_output: bool = False,
|
|
111
|
+
*,
|
|
112
|
+
user_at_host: str | None = None,
|
|
113
|
+
cwd: str | None = None,
|
|
114
|
+
) -> str | None:
|
|
115
|
+
"""
|
|
116
|
+
If output_text is None → capture+return output (no file).
|
|
117
|
+
If output_text is provided → legacy file-backed behavior.
|
|
118
|
+
"""
|
|
119
|
+
if output_text is None:
|
|
120
|
+
# capture mode
|
|
121
|
+
if user_at_host:
|
|
122
|
+
remote = get_remote_cmd(cmd=cmd, user_at_host=user_at_host, cwd=cwd)
|
|
123
|
+
out = execute_cmd(remote, shell=True, text=True, capture_output=True)
|
|
124
|
+
else:
|
|
125
|
+
out = execute_cmd(cmd, shell=True, text=True, capture_output=True, cwd=cwd)
|
|
126
|
+
if print_output:
|
|
127
|
+
print_cmd(cmd, out or "")
|
|
128
|
+
return out or ""
|
|
129
|
+
|
|
130
|
+
# ---- legacy file-backed path (unchanged in spirit) ----
|
|
131
|
+
# Clear output file
|
|
132
|
+
with open(output_text, 'w'):
|
|
133
|
+
pass
|
|
134
|
+
|
|
135
|
+
# Append redirection + sentinel
|
|
136
|
+
full_cmd = f'{cmd} >> {output_text}; echo END_OF_CMD >> {output_text}'
|
|
137
|
+
|
|
138
|
+
# Execute local/remote
|
|
139
|
+
if user_at_host:
|
|
140
|
+
remote_line = get_remote_cmd(cmd=full_cmd, user_at_host=user_at_host, cwd=cwd)
|
|
141
|
+
subprocess.call(remote_line, shell=True)
|
|
142
|
+
else:
|
|
143
|
+
subprocess.call(full_cmd, shell=True, cwd=cwd)
|
|
144
|
+
|
|
145
|
+
# Wait for sentinel
|
|
146
|
+
while True:
|
|
147
|
+
get_sleep(sleep_timer=0.5)
|
|
148
|
+
with open(output_text, 'r') as f:
|
|
149
|
+
lines = f.readlines()
|
|
150
|
+
if lines and lines[-1].strip() == 'END_OF_CMD':
|
|
151
|
+
break
|
|
152
|
+
|
|
153
|
+
if print_output:
|
|
154
|
+
with open(output_text, 'r') as f:
|
|
155
|
+
print_cmd(full_cmd, f.read().strip())
|
|
156
|
+
|
|
157
|
+
try:
|
|
158
|
+
os.remove(output_text)
|
|
159
|
+
except OSError:
|
|
160
|
+
pass
|
|
161
|
+
|
|
162
|
+
return None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
# ----------------------------------------------------
|
|
166
|
+
# pexpect wrappers (local + SSH) for interactive flows
|
|
167
|
+
# ----------------------------------------------------
|
|
168
|
+
def exec_expect(
|
|
169
|
+
command: str,
|
|
170
|
+
child_runs: List[Dict[str, Any]],
|
|
171
|
+
*,
|
|
172
|
+
user_at_host: Optional[str] = None,
|
|
173
|
+
cwd: Optional[str] = None,
|
|
174
|
+
print_output: bool = False,
|
|
175
|
+
) -> int:
|
|
176
|
+
"""
|
|
177
|
+
Run `command` and answer interactive prompts.
|
|
178
|
+
|
|
179
|
+
child_runs: list of dicts like:
|
|
180
|
+
{ "prompt": r"Password:", "pass": "xyz" }
|
|
181
|
+
{ "prompt": r"Enter passphrase:", "key": "MY_KEY", "env_path": "/path/for/.env" }
|
|
182
|
+
If "pass" is None, we resolve via get_env_value(key=..., start_path=env_path).
|
|
183
|
+
|
|
184
|
+
Returns exitstatus (0=success).
|
|
185
|
+
"""
|
|
186
|
+
if user_at_host:
|
|
187
|
+
# Wrap command for remote execution
|
|
188
|
+
remote_line = get_remote_cmd(cmd=command, user_at_host=user_at_host, cwd=cwd)
|
|
189
|
+
spawn_cmd = f"{remote_line}"
|
|
190
|
+
else:
|
|
191
|
+
spawn_cmd = f"bash -lc {shlex.quote((f'cd {shlex.quote(cwd)} && {command}') if cwd else command)}"
|
|
192
|
+
|
|
193
|
+
child = pexpect.spawn(spawn_cmd)
|
|
194
|
+
|
|
195
|
+
for each in child_runs:
|
|
196
|
+
child.expect(each["prompt"])
|
|
197
|
+
|
|
198
|
+
if each.get("pass") is not None:
|
|
199
|
+
pass_phrase = each["pass"]
|
|
200
|
+
else:
|
|
201
|
+
args = {}
|
|
202
|
+
if "key" in each and each["key"] is not None:
|
|
203
|
+
args["key"] = each["key"]
|
|
204
|
+
if "env_path" in each and each["env_path"] is not None:
|
|
205
|
+
args["start_path"] = each["env_path"]
|
|
206
|
+
pass_phrase = get_env_value(**args)
|
|
207
|
+
|
|
208
|
+
child.sendline(pass_phrase)
|
|
209
|
+
if print_output:
|
|
210
|
+
print("Answered prompt:", each["prompt"])
|
|
211
|
+
|
|
212
|
+
child.expect(pexpect.EOF)
|
|
213
|
+
out = child.before.decode("utf-8", errors="ignore")
|
|
214
|
+
if print_output:
|
|
215
|
+
print_cmd(command, out)
|
|
216
|
+
|
|
217
|
+
return child.exitstatus if child.exitstatus is not None else 0
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
# ---------------------------------------
|
|
221
|
+
# Convenience shims to mirror your names
|
|
222
|
+
# ---------------------------------------
|
|
223
|
+
def cmd_run_sudo(
|
|
224
|
+
cmd: str,
|
|
225
|
+
password: str | None = None,
|
|
226
|
+
key: str | None = None,
|
|
227
|
+
output_text: str | None = None,
|
|
228
|
+
*,
|
|
229
|
+
user_at_host: str | None = None,
|
|
230
|
+
cwd: str | None = None,
|
|
231
|
+
print_output: bool = False,
|
|
232
|
+
) -> str | None:
|
|
233
|
+
"""
|
|
234
|
+
If output_text is None → capture sudo output and return it.
|
|
235
|
+
If output_text is provided → legacy file-backed behavior feeding sudo via stdin.
|
|
236
|
+
"""
|
|
237
|
+
if output_text is None:
|
|
238
|
+
return exec_sudo_capture(
|
|
239
|
+
cmd,
|
|
240
|
+
password=password,
|
|
241
|
+
key=key,
|
|
242
|
+
user_at_host=user_at_host,
|
|
243
|
+
cwd=cwd,
|
|
244
|
+
print_output=print_output,
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
# ---- legacy file-backed path ----
|
|
248
|
+
# build the underlying sudo command
|
|
249
|
+
sudo_cmd = f"sudo -S -k {cmd}"
|
|
250
|
+
pw = password if password is not None else (get_env_value(key=key) if key else get_sudo_password())
|
|
251
|
+
|
|
252
|
+
# We need to feed password to stdin in the same shell that runs sudo.
|
|
253
|
+
# For file-backed mode we’ll inline a small shell that reads from a here-string.
|
|
254
|
+
# Local:
|
|
255
|
+
if not user_at_host:
|
|
256
|
+
full = f'bash -lc {shlex.quote((f"cd {shlex.quote(cwd)} && " if cwd else "") + f"printf %s {shlex.quote(pw)} | {sudo_cmd}")}'
|
|
257
|
+
return cmd_run(full, output_text=output_text, print_output=print_output)
|
|
258
|
+
# Remote:
|
|
259
|
+
# On remote, do the same in the remote bash -lc
|
|
260
|
+
remote_sudo_line = f'printf %s {shlex.quote(pw)} | {sudo_cmd}'
|
|
261
|
+
remote_full = get_remote_cmd(cmd=remote_sudo_line, user_at_host=user_at_host, cwd=cwd)
|
|
262
|
+
return cmd_run(remote_full, output_text=output_text, print_output=print_output)
|
|
263
|
+
def pexpect_cmd_with_args(
|
|
264
|
+
command: str,
|
|
265
|
+
child_runs: list,
|
|
266
|
+
output_text: str | None = None,
|
|
267
|
+
*,
|
|
268
|
+
user_at_host: str | None = None,
|
|
269
|
+
cwd: str | None = None,
|
|
270
|
+
print_output: bool = False
|
|
271
|
+
) -> int:
|
|
272
|
+
"""
|
|
273
|
+
If output_text is None → return output string via print_output, else write to file then remove (legacy).
|
|
274
|
+
"""
|
|
275
|
+
if user_at_host:
|
|
276
|
+
spawn_cmd = get_remote_cmd(cmd=command, user_at_host=user_at_host, cwd=cwd)
|
|
277
|
+
else:
|
|
278
|
+
spawn_cmd = f"bash -lc {shlex.quote((f'cd {shlex.quote(cwd)} && {command}') if cwd else command)}"
|
|
279
|
+
|
|
280
|
+
child = pexpect.spawn(spawn_cmd)
|
|
281
|
+
|
|
282
|
+
for each in child_runs:
|
|
283
|
+
child.expect(each["prompt"])
|
|
284
|
+
if each.get("pass") is not None:
|
|
285
|
+
pass_phrase = each["pass"]
|
|
286
|
+
else:
|
|
287
|
+
args = {}
|
|
288
|
+
if "key" in each and each["key"] is not None:
|
|
289
|
+
args["key"] = each["key"]
|
|
290
|
+
if "env_path" in each and each["env_path"] is not None:
|
|
291
|
+
args["start_path"] = each["env_path"]
|
|
292
|
+
pass_phrase = get_env_value(**args)
|
|
293
|
+
child.sendline(pass_phrase)
|
|
294
|
+
if print_output:
|
|
295
|
+
print("Answered prompt:", each["prompt"])
|
|
296
|
+
|
|
297
|
+
child.expect(pexpect.EOF)
|
|
298
|
+
out = child.before.decode("utf-8", errors="ignore")
|
|
299
|
+
|
|
300
|
+
if output_text:
|
|
301
|
+
with open(output_text, "w") as f:
|
|
302
|
+
f.write(out)
|
|
303
|
+
if print_output:
|
|
304
|
+
print_cmd(command, out)
|
|
305
|
+
# keep legacy? your old code removed the file; here we’ll keep it (safer).
|
|
306
|
+
# If you want the old behavior, uncomment:
|
|
307
|
+
# os.remove(output_text)
|
|
308
|
+
else:
|
|
309
|
+
if print_output:
|
|
310
|
+
print_cmd(command, out)
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
from .imports import *
|
|
2
|
+
class abstractEnv:
|
|
3
|
+
def __init__(self,key='MY_PASSWORD',file_name=None,path=os.getcwd(),deep_scan=False):
|
|
4
|
+
file_name = file_name or '.env'
|
|
5
|
+
self.re_initialize(file_name=file_name,key=key,path=path,deep_scan=deep_scan)
|
|
6
|
+
def re_initialize(self,key='MY_PASSWORD',file_name='.env',path=os.getcwd(),deep_scan=False):
|
|
7
|
+
"""
|
|
8
|
+
Initializes an AbstractEnv object to manage environment variables.
|
|
9
|
+
|
|
10
|
+
Args:
|
|
11
|
+
key (str, optional): The key to search for in the .env file. Defaults to 'MY_PASSWORD'.
|
|
12
|
+
file_name (str, optional): The name of the .env file. Defaults to '.env'.
|
|
13
|
+
path (str, optional): The path where the .env file is located. Defaults to the current working directory.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
self.key = key or 'MY_PASSWORD'
|
|
17
|
+
|
|
18
|
+
file_name = file_name or '.env'
|
|
19
|
+
self.key = key or 'MY_PASSWORD'
|
|
20
|
+
self.deep_scan=deep_scan
|
|
21
|
+
self.current_folder = os.getcwd()
|
|
22
|
+
if path and os.path.isfile(path):
|
|
23
|
+
self.file_name = os.path.basename(path)
|
|
24
|
+
self.path = os.path.dirname(path)
|
|
25
|
+
else:
|
|
26
|
+
self.path = path or self.current_folder
|
|
27
|
+
self.file_name = file_name or '.env'
|
|
28
|
+
self.start_path_env = os.path.join(self.path,self.file_name)
|
|
29
|
+
self.home_folder = os.path.expanduser("~")
|
|
30
|
+
self.envy_all = os.path.join(self.home_folder,'.envy_all')
|
|
31
|
+
self.directories = self.get_directories()
|
|
32
|
+
self.env_value = self.find_and_read_env_file(key=self.key,file_name=self.file_name, path=self.path,initialize=False)
|
|
33
|
+
|
|
34
|
+
def find_and_read_env_file(self,key:str=None, file_name:str=None, path=None,initialize=True,deep_scan=False):
|
|
35
|
+
"""
|
|
36
|
+
Search for an environment file and read a specific key from it.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
file_name (str): Name of the .env file to be searched. Defaults to '.env'.
|
|
40
|
+
key (str): Key to be retrieved from the .env file. Defaults to 'MY_PASSWORD'.
|
|
41
|
+
start_path (str): Directory path to start the search from. If None, search starts from current directory.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
str: The value corresponding to the key if found, otherwise None.
|
|
45
|
+
"""
|
|
46
|
+
# Set the default start_path to the current directory if it's None
|
|
47
|
+
# Try to find the file in the start_path
|
|
48
|
+
key = key or self.key
|
|
49
|
+
path = path or self.start_path_env
|
|
50
|
+
file_name = file_name or self.file_name
|
|
51
|
+
if initialize:
|
|
52
|
+
self.re_initialize(key=key,file_name=file_name,path=path)
|
|
53
|
+
for directory in self.directories:
|
|
54
|
+
if directory and os.path.isdir(directory) and self.file_name:
|
|
55
|
+
env_path = os.path.join(directory,self.file_name)
|
|
56
|
+
if os.path.isfile(env_path):
|
|
57
|
+
value = self.search_for_env_key(key=key,path=env_path)
|
|
58
|
+
self.env_path = os.path.join(directory,self.file_name)
|
|
59
|
+
if os.path.isfile(self.env_path):
|
|
60
|
+
value = self.search_for_env_key(key=key,path=self.env_path,deep_scan=deep_scan)
|
|
61
|
+
if value:
|
|
62
|
+
return value
|
|
63
|
+
def get_directories(self):
|
|
64
|
+
"""
|
|
65
|
+
Retrieves a list of directories to search for the .env file.
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
list: A list of directories including the specified path, current folder, home folder, and '.envy_all' directory.
|
|
69
|
+
"""
|
|
70
|
+
directories=[]
|
|
71
|
+
for directory in [self.path,self.current_folder,self.home_folder,self.envy_all]:
|
|
72
|
+
if os.path.isdir(directory) and directory not in directories:
|
|
73
|
+
directories.append(directory)
|
|
74
|
+
return directories
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def search_for_env_key(self,key:str=None,path:str=None,deep_scan=False):
|
|
78
|
+
|
|
79
|
+
"""
|
|
80
|
+
Retrieves the value of a specified environment variable from a .env file.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
key (str, optional): The key to search for in the .env file. Defaults to None.
|
|
84
|
+
path (str, optional): The path to the .env file. Defaults to None.
|
|
85
|
+
file_name (str, optional): The name of the .env file. Defaults to None.
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
str: The value of the environment variable if found, otherwise None.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
highest = [None,0,0.0]
|
|
92
|
+
key = key or self.default_env_key
|
|
93
|
+
path = path or self.start_path_env
|
|
94
|
+
if path and os.path.isfile(path):
|
|
95
|
+
with open(path, "r") as f:
|
|
96
|
+
for line in f:
|
|
97
|
+
line_key,line_value = split_eq(line)
|
|
98
|
+
# If the line contains the key, return the value after stripping extra characters
|
|
99
|
+
if line_key == key:
|
|
100
|
+
return line_value
|
|
101
|
+
if deep_scan:
|
|
102
|
+
line_keys = []
|
|
103
|
+
key_parts=0
|
|
104
|
+
for key_part in key.split('_'):
|
|
105
|
+
line_keys.append([])
|
|
106
|
+
if key_part in line_key:
|
|
107
|
+
line_keys[-1].append(line_key)
|
|
108
|
+
key_parts+=len(key_part)
|
|
109
|
+
if float(key_parts/len(key))>=0.5 and key_parts >highest[1]:
|
|
110
|
+
highest = [line_value,key_parts]
|
|
111
|
+
if deep_scan and highest[0] != None:
|
|
112
|
+
return line_value
|
|
113
|
+
def get_env_value(key:str=None,path:str=os.getcwd(),file_name:str=None):
|
|
114
|
+
"""
|
|
115
|
+
Retrieves the value of the specified environment variable.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
path (str): The path to the environment file. Defaults to None.
|
|
119
|
+
file_name (str): The name of the environment file. Defaults to '.env'.
|
|
120
|
+
key (str): The key to search for in the .env file. Defaults to 'MY_PASSWORD'.
|
|
121
|
+
|
|
122
|
+
Returns:
|
|
123
|
+
str: The value of the environment variable if found, otherwise None.
|
|
124
|
+
"""
|
|
125
|
+
if safe_env_load(path):
|
|
126
|
+
return os.getenv(key)
|
|
127
|
+
return find_and_read_env_file(file_name=file_name, key=key, path=path_ls)
|
|
128
|
+
|
|
129
|
+
AbstractEnv = abstractEnv
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from .imports import *
|
|
2
|
+
from .abstractEnv import abstractEnv
|
|
3
|
+
def get_env_value(key:str=None,path:str=None,file_name:str=None,deep_scan=False):
|
|
4
|
+
abstract_env = abstractEnv(key=key, file_name=file_name, path=path,deep_scan=deep_scan)
|
|
5
|
+
|
|
6
|
+
"""
|
|
7
|
+
Retrieves the value of a specified environment variable from a .env file.
|
|
8
|
+
|
|
9
|
+
Args:
|
|
10
|
+
key (str, optional): The key to search for in the .env file. Defaults to None.
|
|
11
|
+
path (str, optional): The path to the .env file. Defaults to None.
|
|
12
|
+
file_name (str, optional): The name of the .env file. Defaults to None.
|
|
13
|
+
|
|
14
|
+
Returns:
|
|
15
|
+
str: The value of the environment variable if found, otherwise None.
|
|
16
|
+
"""
|
|
17
|
+
return abstract_env.env_value
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def get_env_path(key:str=None,path:str=None,file_name:str=None,deep_scan=False):
|
|
21
|
+
abstract_env = abstractEnv(key=key, file_name=file_name, path=path,deep_scan=deep_scan)
|
|
22
|
+
"""
|
|
23
|
+
Retrieves the value of a specified environment variable from a .env file.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
key (str, optional): The key to search for in the .env file. Defaults to None.
|
|
27
|
+
path (str, optional): The path to the .env file. Defaults to None.
|
|
28
|
+
file_name (str, optional): The name of the .env file. Defaults to None.
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
str: The value of the environment variable if found, otherwise None.
|
|
32
|
+
"""
|
|
33
|
+
return abstract_env.env_path
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from dotenv import load_dotenv
|
|
3
|
+
from ...string_clean import eatAll,eatInner,eatOuter,safe_split
|
|
4
|
+
from ...compare_utils import line_contains
|
|
5
|
+
from ...type_utils import is_list,is_bool
|
|
6
|
+
from ...path_utils import get_slash,path_join,if_not_last_child_join,get_home_folder,simple_path_join,is_file
|
|
7
|
+
DEFAULT_FILE_NAME = '.env'
|
|
8
|
+
DEFAULT_KEY = 'MY_PASSWORD'
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
from .imports import *
|
|
2
|
+
def find_and_read_env_file(key:str=DEFAULT_KEY,file_name:str=DEFAULT_FILE_NAME, start_path:str=None):
|
|
3
|
+
"""
|
|
4
|
+
Search for an environment file and read a specific key from it.
|
|
5
|
+
|
|
6
|
+
Args:
|
|
7
|
+
file_name (str): Name of the .env file to be searched. Defaults to '.env'.
|
|
8
|
+
key (str): Key to be retrieved from the .env file. Defaults to 'MY_PASSWORD'.
|
|
9
|
+
start_path (str): Directory path to start the search from. If None, search starts from current directory.
|
|
10
|
+
|
|
11
|
+
Returns:
|
|
12
|
+
str: The value corresponding to the key if found, otherwise None.
|
|
13
|
+
"""
|
|
14
|
+
# Set the default start_path to the current directory if it's None
|
|
15
|
+
directories = [start_path, os.getcwd(), get_home_folder(), simple_path_join(get_home_folder(),'.envy_all'),simple_path_join(get_home_folder(),'envy_all')]
|
|
16
|
+
if start_path in [None, os.getcwd()]:
|
|
17
|
+
directories = directories[1:]
|
|
18
|
+
|
|
19
|
+
# Try to find the file in the start_path
|
|
20
|
+
for k in range(0,len(directories)):
|
|
21
|
+
env_path = check_env_file(path=directories[k],file_name=file_name)
|
|
22
|
+
if not is_bool(env_path):
|
|
23
|
+
value = search_for_env_key(path=env_path,key=key)
|
|
24
|
+
if value != None:
|
|
25
|
+
return value
|
|
26
|
+
|
|
27
|
+
def search_for_env_key(key:str,path:str):
|
|
28
|
+
"""
|
|
29
|
+
Search for a specific key in a .env file.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
path (str): The path to the .env file.
|
|
33
|
+
key (str): The key to search for in the .env file.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
str: The value of the key if found, otherwise None.
|
|
37
|
+
"""
|
|
38
|
+
with open(path, "r") as f:
|
|
39
|
+
for line in f:
|
|
40
|
+
eq_split = safe_split(line,['=',0])
|
|
41
|
+
# If the line contains the key, return the value after stripping extra characters
|
|
42
|
+
if line_contains(string=eq_split, compare=key):
|
|
43
|
+
return eatAll(line[len(eq_split):],[' ','','=']).strip()
|
|
44
|
+
|
|
45
|
+
def check_env_file(path:str,file_name:str=DEFAULT_FILE_NAME):
|
|
46
|
+
"""
|
|
47
|
+
Check if the environment file exists in a specified path.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
path (str): The path to check for the .env file.
|
|
51
|
+
file_name (str): The name of the .env file. Defaults to '.env'.
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
str: The path of the .env file if it exists, otherwise False.
|
|
55
|
+
"""
|
|
56
|
+
path = if_not_last_child_join(path=path, child=DEFAULT_FILE_NAME)
|
|
57
|
+
# Return the path if file exists, otherwise return False
|
|
58
|
+
if is_file(path):
|
|
59
|
+
return path
|
|
60
|
+
return False
|
|
61
|
+
|
|
62
|
+
def safe_env_load(path:str=None):
|
|
63
|
+
"""
|
|
64
|
+
Safely load the .env file if it exists at a specified path.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
path (str): The path to load the .env file from. If None, no operation is performed.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
bool: True if the .env file is successfully loaded, otherwise False.
|
|
71
|
+
"""
|
|
72
|
+
if path == None:
|
|
73
|
+
return False
|
|
74
|
+
if is_file(path):
|
|
75
|
+
if str(safe_split(path,[get_slash(),-1]))[0] == '.':
|
|
76
|
+
load_dotenv(path)
|
|
77
|
+
return True
|
|
78
|
+
return False
|
|
79
|
+
|
|
80
|
+
def get_env_value(key:str=DEFAULT_KEY,path:str=None,file_name:str=DEFAULT_FILE_NAME):
|
|
81
|
+
"""
|
|
82
|
+
Retrieves the value of the specified environment variable.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
path (str): The path to the environment file. Defaults to None.
|
|
86
|
+
file_name (str): The name of the environment file. Defaults to '.env'.
|
|
87
|
+
key (str): The key to search for in the .env file. Defaults to 'MY_PASSWORD'.
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
str: The value of the environment variable if found, otherwise None.
|
|
91
|
+
"""
|
|
92
|
+
if safe_env_load(path):
|
|
93
|
+
return os.getenv(key)
|
|
94
|
+
return find_and_read_env_file(file_name=file_name, key=key, start_path=os.getcwd())
|
|
95
|
+
def split_eq(line):
|
|
96
|
+
"""
|
|
97
|
+
Splits a string at the first equals sign '=' and cleans up the key and value.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
line (str): The string to be split.
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
list: A list containing the cleaned key and value. If '=' is not found, returns [line, None].
|
|
104
|
+
"""
|
|
105
|
+
if '=' in line:
|
|
106
|
+
key_side = line.split('=')[0]
|
|
107
|
+
value_side = line[len(key_side+'='):]
|
|
108
|
+
return [eatOuter(key_side,[' ','','\t']),eatAll(value_side,[' ','','\t','\n'])]
|
|
109
|
+
return [line,None]
|
|
110
|
+
def dotenv_load(path:str=None):
|
|
111
|
+
"""
|
|
112
|
+
Safely load the .env file if it exists at a specified path.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
path (str): The path to load the .env file from. If None, no operation is performed.
|
|
116
|
+
|
|
117
|
+
Returns:
|
|
118
|
+
bool: True if the .env file is successfully loaded, otherwise False.
|
|
119
|
+
"""
|
|
120
|
+
if path and os.path.isfile(path) and os.path.basename(path)[0] == '.':
|
|
121
|
+
load_dotenv(path)
|
|
122
|
+
return True
|