abstract-utilities 0.2.2.449__py3-none-any.whl → 0.2.2.476__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 +18 -44
- abstract_utilities/abstract_classes.py +49 -0
- abstract_utilities/class_utils.py +38 -3
- 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/compare_utils/__init__.py +3 -0
- abstract_utilities/compare_utils/best_match.py +150 -0
- abstract_utilities/{compare_utils.py → compare_utils/compare_utils.py} +1 -1
- abstract_utilities/compare_utils/find_value.py +105 -0
- abstract_utilities/dynimport.py +7 -15
- 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/file_utils/__init__.py +3 -0
- abstract_utilities/file_utils/file_utils/__init__.py +8 -0
- abstract_utilities/file_utils/file_utils/file_filters.py +104 -0
- abstract_utilities/{robust_reader → file_utils/file_utils}/file_reader.py +5 -19
- abstract_utilities/{robust_readers/file_filters.py → file_utils/file_utils/file_utils.py} +5 -4
- abstract_utilities/{robust_readers → file_utils/file_utils}/filter_params.py +1 -38
- abstract_utilities/file_utils/file_utils/find_collect.py +154 -0
- abstract_utilities/file_utils/file_utils/imports/__init__.py +3 -0
- abstract_utilities/file_utils/file_utils/imports/constants.py +39 -0
- abstract_utilities/file_utils/file_utils/imports/file_functions.py +10 -0
- abstract_utilities/file_utils/file_utils/imports/imports.py +39 -0
- abstract_utilities/file_utils/file_utils/imports/module_imports.py +13 -0
- abstract_utilities/file_utils/file_utils/imports.py +10 -0
- abstract_utilities/file_utils/file_utils/map_utils.py +29 -0
- abstract_utilities/{robust_reader → file_utils/file_utils}/pdf_utils.py +1 -9
- abstract_utilities/file_utils/file_utils/type_checks.py +82 -0
- abstract_utilities/file_utils/imports/__init__.py +4 -0
- abstract_utilities/file_utils/imports/classes.py +381 -0
- abstract_utilities/file_utils/imports/clean_imps.py +158 -0
- abstract_utilities/file_utils/imports/constants.py +39 -0
- abstract_utilities/file_utils/imports/file_functions.py +10 -0
- abstract_utilities/file_utils/imports/imports.py +65 -0
- abstract_utilities/file_utils/imports/module_imports.py +13 -0
- abstract_utilities/file_utils/req.py +329 -0
- abstract_utilities/json_utils.py +35 -0
- abstract_utilities/log_utils.py +14 -3
- abstract_utilities/path_utils.py +90 -6
- abstract_utilities/read_write_utils.py +176 -154
- abstract_utilities/robust_reader/__init__.py +1 -1
- abstract_utilities/robust_reader/imports/__init__.py +1 -0
- abstract_utilities/robust_reader/imports/imports.py +3 -0
- abstract_utilities/robust_readers/__init__.py +0 -1
- abstract_utilities/robust_readers/import_utils/__init__.py +1 -0
- abstract_utilities/robust_readers/import_utils/clean_imports.py +175 -0
- abstract_utilities/robust_readers/imports.py +8 -0
- abstract_utilities/robust_readers/initFuncGen.py +92 -76
- abstract_utilities/safe_utils.py +133 -0
- abstract_utilities/ssh_utils/__init__.py +3 -0
- abstract_utilities/ssh_utils/classes.py +127 -0
- abstract_utilities/ssh_utils/imports.py +10 -0
- abstract_utilities/ssh_utils/pexpect_utils.py +315 -0
- abstract_utilities/ssh_utils/utils.py +188 -0
- abstract_utilities/string_clean.py +40 -1
- abstract_utilities/string_utils.py +48 -0
- abstract_utilities/type_utils.py +25 -2
- {abstract_utilities-0.2.2.449.dist-info → abstract_utilities-0.2.2.476.dist-info}/METADATA +15 -4
- abstract_utilities-0.2.2.476.dist-info/RECORD +92 -0
- {abstract_utilities-0.2.2.449.dist-info → abstract_utilities-0.2.2.476.dist-info}/WHEEL +1 -1
- abstract_utilities-0.2.2.449.dist-info/RECORD +0 -49
- {abstract_utilities-0.2.2.449.dist-info → abstract_utilities-0.2.2.476.dist-info}/top_level.txt +0 -0
abstract_utilities/__init__.py
CHANGED
|
@@ -3,8 +3,9 @@ from datetime import timedelta
|
|
|
3
3
|
from datetime import datetime
|
|
4
4
|
from typing import *
|
|
5
5
|
from .hash_utils import *
|
|
6
|
-
from .dynimport import get_abstract_import,import_symbols_to_parent,call_for_all_tabs
|
|
7
|
-
|
|
6
|
+
##from .dynimport import get_abstract_import,import_symbols_to_parent,call_for_all_tabs
|
|
7
|
+
from .robust_readers import *
|
|
8
|
+
from .dynimport import get_abstract_import
|
|
8
9
|
from .json_utils import (unified_json_loader,
|
|
9
10
|
find_keys,
|
|
10
11
|
get_key_values_from_path,
|
|
@@ -40,42 +41,8 @@ from .json_utils import (unified_json_loader,
|
|
|
40
41
|
)
|
|
41
42
|
from .read_write_utils import (read_from_file,
|
|
42
43
|
write_to_file)
|
|
43
|
-
from .path_utils import
|
|
44
|
-
|
|
45
|
-
get_folders,
|
|
46
|
-
path_join,
|
|
47
|
-
mkdirs,
|
|
48
|
-
split_text,
|
|
49
|
-
get_all_item_paths,
|
|
50
|
-
get_directory_items,
|
|
51
|
-
get_files,
|
|
52
|
-
get_folders,
|
|
53
|
-
break_down_find_existing,
|
|
54
|
-
get_directory_items,
|
|
55
|
-
get_directory_files,
|
|
56
|
-
get_all_item_paths,
|
|
57
|
-
get_all_file_paths,
|
|
58
|
-
get_directory,
|
|
59
|
-
create_directory,
|
|
60
|
-
initialize_file,
|
|
61
|
-
join_path,
|
|
62
|
-
is_last_itter,
|
|
63
|
-
path_join,
|
|
64
|
-
is_file,
|
|
65
|
-
is_dir,
|
|
66
|
-
is_path,
|
|
67
|
-
get_all_directories,
|
|
68
|
-
get_all_files,
|
|
69
|
-
get_all_items,
|
|
70
|
-
collate_text_docs,
|
|
71
|
-
get_dirlist,
|
|
72
|
-
get_content,
|
|
73
|
-
is_directory_in_paths,
|
|
74
|
-
make_dirs,
|
|
75
|
-
remove_directory,
|
|
76
|
-
remove_path,
|
|
77
|
-
get_file_parts
|
|
78
|
-
)
|
|
44
|
+
from .path_utils import *
|
|
45
|
+
from .file_utils import *
|
|
79
46
|
from .list_utils import (get_highest_value_obj,
|
|
80
47
|
make_list,
|
|
81
48
|
safe_list_return,
|
|
@@ -120,7 +87,8 @@ from .type_utils import (make_bool,
|
|
|
120
87
|
get_numbers,
|
|
121
88
|
get_numbers_comp,
|
|
122
89
|
is_any_instance,
|
|
123
|
-
break_string
|
|
90
|
+
break_string,
|
|
91
|
+
MIME_TYPES
|
|
124
92
|
)
|
|
125
93
|
get_media_types = get_all_types = get_all_file_types
|
|
126
94
|
from .math_utils import (convert_to_percentage,
|
|
@@ -132,7 +100,10 @@ from .math_utils import (convert_to_percentage,
|
|
|
132
100
|
return_0)
|
|
133
101
|
from .compare_utils import (create_new_name,
|
|
134
102
|
get_last_comp_list,
|
|
135
|
-
get_closest_match_from_list
|
|
103
|
+
get_closest_match_from_list,
|
|
104
|
+
get_first_match,
|
|
105
|
+
get_all_match,
|
|
106
|
+
best_match)
|
|
136
107
|
from .thread_utils import ThreadManager
|
|
137
108
|
from .history_utils import HistoryManager
|
|
138
109
|
from .abstract_classes import *
|
|
@@ -145,7 +116,10 @@ from .parse_utils import (num_tokens_from_string,
|
|
|
145
116
|
|
|
146
117
|
from .log_utils import get_caller_info,get_logFile,print_or_log,get_json_call_response,initialize_call_log
|
|
147
118
|
from .error_utils import try_func
|
|
148
|
-
from .
|
|
149
|
-
from .
|
|
150
|
-
from .
|
|
151
|
-
|
|
119
|
+
from .ssh_utils import *
|
|
120
|
+
from .env_utils import *
|
|
121
|
+
from .path_utils import *
|
|
122
|
+
from .file_utils import *
|
|
123
|
+
from .file_utils import call_for_all_tabs
|
|
124
|
+
from .string_utils import *
|
|
125
|
+
from .class_utils import alias,get_class_inputs,get_set_attr,get_caller_path,get_caller_dir
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import inspect
|
|
1
2
|
class SingletonMeta(type):
|
|
2
3
|
_instances = {}
|
|
3
4
|
def __call__(cls, *args, **kwargs):
|
|
@@ -22,3 +23,51 @@ def get_inputs(cls, *args, **kwargs):
|
|
|
22
23
|
values[field] = getattr(cls(), field) # default from dataclass
|
|
23
24
|
|
|
24
25
|
return cls(**values)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def prune_inputs(func, *args, **kwargs):
|
|
29
|
+
"""
|
|
30
|
+
Adapt the provided args/kwargs to fit the signature of func.
|
|
31
|
+
Returns (args, kwargs) suitable for calling func.
|
|
32
|
+
"""
|
|
33
|
+
sig = inspect.signature(func)
|
|
34
|
+
params = sig.parameters
|
|
35
|
+
|
|
36
|
+
# Handle positional arguments
|
|
37
|
+
new_args = []
|
|
38
|
+
args_iter = iter(args)
|
|
39
|
+
for name, param in params.items():
|
|
40
|
+
if param.kind in (inspect.Parameter.POSITIONAL_ONLY,
|
|
41
|
+
inspect.Parameter.POSITIONAL_OR_KEYWORD):
|
|
42
|
+
try:
|
|
43
|
+
new_args.append(next(args_iter))
|
|
44
|
+
except StopIteration:
|
|
45
|
+
break
|
|
46
|
+
elif param.kind == inspect.Parameter.VAR_POSITIONAL:
|
|
47
|
+
# collect all remaining args
|
|
48
|
+
new_args.extend(args_iter)
|
|
49
|
+
break
|
|
50
|
+
else:
|
|
51
|
+
break
|
|
52
|
+
|
|
53
|
+
# Handle keyword arguments
|
|
54
|
+
new_kwargs = {}
|
|
55
|
+
for name, param in params.items():
|
|
56
|
+
if name in kwargs:
|
|
57
|
+
new_kwargs[name] = kwargs[name]
|
|
58
|
+
elif param.default is inspect.Parameter.empty and param.kind == inspect.Parameter.KEYWORD_ONLY:
|
|
59
|
+
# Required keyword not provided
|
|
60
|
+
raise TypeError(f"Missing required keyword argument: {name}")
|
|
61
|
+
|
|
62
|
+
# Only include keywords func accepts
|
|
63
|
+
accepted_names = {
|
|
64
|
+
name for name, p in params.items()
|
|
65
|
+
if p.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
|
66
|
+
inspect.Parameter.KEYWORD_ONLY)
|
|
67
|
+
}
|
|
68
|
+
new_kwargs = {k: v for k, v in new_kwargs.items() if k in accepted_names}
|
|
69
|
+
|
|
70
|
+
return tuple(new_args), new_kwargs
|
|
71
|
+
def run_pruned_func(func, *args, **kwargs):
|
|
72
|
+
args,kwargs = prune_inputs(func, *args, **kwargs)
|
|
73
|
+
return func(*args, **kwargs)
|
|
@@ -44,9 +44,9 @@ Dependencies:
|
|
|
44
44
|
Each function is furnished with its own docstring that elaborates on its purpose, expected inputs, and outputs.
|
|
45
45
|
|
|
46
46
|
"""
|
|
47
|
-
import inspect
|
|
48
|
-
import
|
|
49
|
-
|
|
47
|
+
import os,json,functools,inspect
|
|
48
|
+
from typing import *
|
|
49
|
+
|
|
50
50
|
def get_type_list() -> list:
|
|
51
51
|
"""Get a list of common Python types."""
|
|
52
52
|
return ['None','str','int','float','bool','list','tuple','set','dict','frozenset','bytearray','bytes','memoryview','range','enumerate','zip','filter','map','property','slice','super','type','Exception','object']
|
|
@@ -370,3 +370,38 @@ def get_class_inputs(cls, *args, **kwargs):
|
|
|
370
370
|
else:
|
|
371
371
|
values[field] = getattr(cls(), field)
|
|
372
372
|
return cls(**values)
|
|
373
|
+
def get_caller(i: Optional[int] = None) -> str:
|
|
374
|
+
"""
|
|
375
|
+
Return the filename of the calling frame.
|
|
376
|
+
|
|
377
|
+
Args:
|
|
378
|
+
i: Optional stack depth offset.
|
|
379
|
+
None = immediate caller (depth 1).
|
|
380
|
+
|
|
381
|
+
Returns:
|
|
382
|
+
Absolute path of the file for the stack frame.
|
|
383
|
+
"""
|
|
384
|
+
depth = 1 if i is None else int(i)
|
|
385
|
+
stack = inspect.stack()
|
|
386
|
+
if depth >= len(stack):
|
|
387
|
+
depth = len(stack) - 1
|
|
388
|
+
return stack[depth].filename
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def get_caller_path(i: Optional[int] = None) -> str:
|
|
392
|
+
"""
|
|
393
|
+
Return the absolute path of the caller's file.
|
|
394
|
+
"""
|
|
395
|
+
depth = 1 if i is None else int(i)
|
|
396
|
+
file_path = get_caller(depth + 1)
|
|
397
|
+
return os.path.realpath(file_path)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def get_caller_dir(i: Optional[int] = None) -> str:
|
|
401
|
+
"""
|
|
402
|
+
Return the absolute directory of the caller's file.
|
|
403
|
+
"""
|
|
404
|
+
depth = 1 if i is None else int(i)
|
|
405
|
+
abspath = get_caller_path(depth + 1)
|
|
406
|
+
return os.path.dirname(abspath)
|
|
407
|
+
|
|
@@ -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,150 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from typing import Any, Iterable, Iterator, Tuple, Union, Dict, List, Optional
|
|
3
|
+
import re
|
|
4
|
+
from difflib import SequenceMatcher
|
|
5
|
+
|
|
6
|
+
JSONLike = Union[dict, list, tuple, set, str, int, float, bool, None]
|
|
7
|
+
PathType = Tuple[Union[str, int], ...]
|
|
8
|
+
|
|
9
|
+
def iter_values(obj: JSONLike, path: PathType = ()) -> Iterator[Tuple[PathType, Any]]:
|
|
10
|
+
if isinstance(obj, dict):
|
|
11
|
+
for k, v in obj.items():
|
|
12
|
+
yield from iter_values(v, path + (k,))
|
|
13
|
+
elif isinstance(obj, (list, tuple)):
|
|
14
|
+
for i, v in enumerate(obj):
|
|
15
|
+
yield from iter_values(v, path + (i,))
|
|
16
|
+
elif isinstance(obj, set):
|
|
17
|
+
for v in obj:
|
|
18
|
+
yield from iter_values(v, path + ('<setitem>',))
|
|
19
|
+
else:
|
|
20
|
+
yield path, obj
|
|
21
|
+
|
|
22
|
+
def _norm(s: str, case_insensitive: bool) -> str:
|
|
23
|
+
return s.lower() if case_insensitive else s
|
|
24
|
+
|
|
25
|
+
def _word_boundary_regex(term: str, case_insensitive: bool) -> re.Pattern:
|
|
26
|
+
flags = re.IGNORECASE if case_insensitive else 0
|
|
27
|
+
# word boundary around the whole term; escape term for literal
|
|
28
|
+
return re.compile(rf"\b{re.escape(term)}\b", flags)
|
|
29
|
+
|
|
30
|
+
def _score_string(
|
|
31
|
+
value: str,
|
|
32
|
+
terms: Iterable[str],
|
|
33
|
+
*,
|
|
34
|
+
case_insensitive: bool = True,
|
|
35
|
+
min_ratio: float = 0.6,
|
|
36
|
+
) -> Tuple[float, Dict[str, float]]:
|
|
37
|
+
"""
|
|
38
|
+
Score a *string* against the list of terms. Returns (score, per_term_scores).
|
|
39
|
+
Weights:
|
|
40
|
+
exact=+3, word-boundary=+2, substring=+1, fuzzy=+0.5*ratio (if ratio>=min_ratio).
|
|
41
|
+
+0.2 bonus per extra unique term matched (beyond the first).
|
|
42
|
+
"""
|
|
43
|
+
if not isinstance(value, str):
|
|
44
|
+
return 0.0, {}
|
|
45
|
+
v = _norm(value, case_insensitive)
|
|
46
|
+
per_term: Dict[str, float] = {}
|
|
47
|
+
matched_terms = 0
|
|
48
|
+
|
|
49
|
+
for term in terms:
|
|
50
|
+
t = _norm(term, case_insensitive)
|
|
51
|
+
term_score = 0.0
|
|
52
|
+
|
|
53
|
+
if v == t:
|
|
54
|
+
term_score = max(term_score, 3.0)
|
|
55
|
+
|
|
56
|
+
# word boundary
|
|
57
|
+
if _word_boundary_regex(term, case_insensitive).search(value):
|
|
58
|
+
term_score = max(term_score, 2.0)
|
|
59
|
+
|
|
60
|
+
# substring
|
|
61
|
+
if t in v:
|
|
62
|
+
term_score = max(term_score, 1.0)
|
|
63
|
+
|
|
64
|
+
# fuzzy similarity
|
|
65
|
+
ratio = SequenceMatcher(None, v, t).ratio() # 0..1
|
|
66
|
+
if ratio >= min_ratio:
|
|
67
|
+
term_score = max(term_score, 0.5 * ratio)
|
|
68
|
+
|
|
69
|
+
if term_score > 0:
|
|
70
|
+
matched_terms += 1
|
|
71
|
+
per_term[term] = term_score
|
|
72
|
+
|
|
73
|
+
# Bonus for covering more than one term
|
|
74
|
+
bonus = 0.2 * max(0, matched_terms - 1)
|
|
75
|
+
total = sum(per_term.values()) + bonus
|
|
76
|
+
return total, per_term
|
|
77
|
+
|
|
78
|
+
def best_match(
|
|
79
|
+
obj: JSONLike,
|
|
80
|
+
*,
|
|
81
|
+
terms: Iterable[str],
|
|
82
|
+
case_insensitive: bool = True,
|
|
83
|
+
min_ratio: float = 0.6,
|
|
84
|
+
key_weight: Dict[str, float] | None = None, # e.g. {'window_title': 1.5}
|
|
85
|
+
coerce_non_strings: bool = False,
|
|
86
|
+
) -> Optional[Dict[str, Any]]:
|
|
87
|
+
"""
|
|
88
|
+
Return the single best leaf string:
|
|
89
|
+
{ 'value': str, 'path': PathType, 'score': float, 'per_term': {term:score} }
|
|
90
|
+
"""
|
|
91
|
+
key_weight = key_weight or {}
|
|
92
|
+
best: Optional[Dict[str, Any]] = None
|
|
93
|
+
|
|
94
|
+
for path, val in iter_values(obj):
|
|
95
|
+
s = val
|
|
96
|
+
if not isinstance(s, str):
|
|
97
|
+
if coerce_non_strings:
|
|
98
|
+
s = str(val)
|
|
99
|
+
else:
|
|
100
|
+
continue
|
|
101
|
+
|
|
102
|
+
score, per_term = _score_string(s, terms, case_insensitive=case_insensitive, min_ratio=min_ratio)
|
|
103
|
+
if score <= 0:
|
|
104
|
+
continue
|
|
105
|
+
|
|
106
|
+
# Apply path-based weight if any path segment matches a key in key_weight
|
|
107
|
+
weight = 1.0
|
|
108
|
+
for seg in path:
|
|
109
|
+
if isinstance(seg, str) and seg in key_weight:
|
|
110
|
+
weight *= key_weight[seg]
|
|
111
|
+
weighted = score * weight
|
|
112
|
+
|
|
113
|
+
cand = {'value': s, 'path': path, 'score': weighted, 'per_term': per_term}
|
|
114
|
+
if best is None or weighted > best['score']:
|
|
115
|
+
best = cand
|
|
116
|
+
# Optional tie-breakers (prefer more terms matched, then shorter value)
|
|
117
|
+
elif best is not None and abs(weighted - best['score']) < 1e-9:
|
|
118
|
+
if len(per_term) > len(best['per_term']):
|
|
119
|
+
best = cand
|
|
120
|
+
elif len(per_term) == len(best['per_term']) and len(s) < len(best['value']):
|
|
121
|
+
best = cand
|
|
122
|
+
|
|
123
|
+
return best
|
|
124
|
+
|
|
125
|
+
def top_k_matches(
|
|
126
|
+
obj: JSONLike,
|
|
127
|
+
*,
|
|
128
|
+
terms: Iterable[str],
|
|
129
|
+
k: int = 5,
|
|
130
|
+
**kwargs
|
|
131
|
+
) -> List[Dict[str, Any]]:
|
|
132
|
+
"""Return top-k matches sorted by score desc."""
|
|
133
|
+
items: List[Dict[str, Any]] = []
|
|
134
|
+
for path, val in iter_values(obj):
|
|
135
|
+
s = val if isinstance(val, str) else (str(val) if kwargs.get('coerce_non_strings') else None)
|
|
136
|
+
if s is None:
|
|
137
|
+
continue
|
|
138
|
+
score, per_term = _score_string(s, terms,
|
|
139
|
+
case_insensitive=kwargs.get('case_insensitive', True),
|
|
140
|
+
min_ratio=kwargs.get('min_ratio', 0.6))
|
|
141
|
+
if score <= 0:
|
|
142
|
+
continue
|
|
143
|
+
weight = 1.0
|
|
144
|
+
for seg in path:
|
|
145
|
+
if isinstance(seg, str) and kwargs.get('key_weight', {}).get(seg):
|
|
146
|
+
weight *= kwargs['key_weight'][seg]
|
|
147
|
+
items.append({'value': s, 'path': path, 'score': score * weight, 'per_term': per_term})
|
|
148
|
+
|
|
149
|
+
items.sort(key=lambda d: d['score'], reverse=True)
|
|
150
|
+
return items[:k]
|