machineconfig 7.64__py3-none-any.whl → 7.83__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 machineconfig might be problematic. Click here for more details.

Files changed (104) hide show
  1. machineconfig/cluster/sessions_managers/utils/maker.py +4 -2
  2. machineconfig/jobs/installer/custom/yazi.py +120 -0
  3. machineconfig/jobs/installer/custom_dev/nerdfont.py +1 -1
  4. machineconfig/jobs/installer/custom_dev/nerfont_windows_helper.py +26 -12
  5. machineconfig/jobs/installer/custom_dev/sysabc.py +26 -5
  6. machineconfig/jobs/installer/installer_data.json +232 -96
  7. machineconfig/jobs/installer/powershell_scripts/install_fonts.ps1 +129 -34
  8. machineconfig/profile/create_helper.py +0 -12
  9. machineconfig/profile/create_links_export.py +2 -2
  10. machineconfig/profile/mapper.toml +2 -2
  11. machineconfig/scripts/__init__.py +0 -4
  12. machineconfig/scripts/python/agents.py +22 -17
  13. machineconfig/scripts/python/ai/solutions/copilot/instructions/python/dev.instructions.md +4 -0
  14. machineconfig/scripts/python/croshell.py +22 -17
  15. machineconfig/scripts/python/devops.py +1 -1
  16. machineconfig/scripts/python/devops_navigator.py +0 -4
  17. machineconfig/scripts/python/env_manager/env_manager_tui.py +204 -0
  18. machineconfig/scripts/python/env_manager/path_manager_tui.py +1 -1
  19. machineconfig/scripts/python/fire_jobs.py +13 -13
  20. machineconfig/scripts/python/ftpx.py +36 -12
  21. machineconfig/scripts/python/helpers/ast_search.py +74 -0
  22. machineconfig/scripts/python/helpers/qr_code.py +166 -0
  23. machineconfig/scripts/python/helpers/repo_rag.py +325 -0
  24. machineconfig/scripts/python/helpers/symantic_search.py +25 -0
  25. machineconfig/scripts/python/helpers_cloud/cloud_copy.py +28 -21
  26. machineconfig/scripts/python/helpers_cloud/cloud_helpers.py +1 -1
  27. machineconfig/scripts/python/helpers_cloud/cloud_mount.py +19 -17
  28. machineconfig/scripts/python/helpers_cloud/cloud_sync.py +8 -7
  29. machineconfig/scripts/python/helpers_croshell/start_slidev.py +6 -7
  30. machineconfig/scripts/python/helpers_devops/cli_config.py +10 -0
  31. machineconfig/scripts/python/helpers_devops/cli_nw.py +90 -10
  32. machineconfig/scripts/python/helpers_devops/cli_self.py +8 -7
  33. machineconfig/scripts/python/helpers_devops/cli_share_file.py +7 -7
  34. machineconfig/scripts/python/helpers_devops/cli_share_server.py +12 -11
  35. machineconfig/scripts/python/helpers_devops/cli_terminal.py +8 -10
  36. machineconfig/scripts/python/helpers_devops/cli_utils.py +2 -1
  37. machineconfig/scripts/python/helpers_devops/devops_status.py +7 -19
  38. machineconfig/scripts/python/helpers_fire_command/fire_jobs_route_helper.py +20 -9
  39. machineconfig/scripts/python/helpers_msearch/scripts_linux/fzfg +2 -2
  40. machineconfig/scripts/python/helpers_msearch/scripts_windows/fzfg.ps1 +58 -1
  41. machineconfig/scripts/python/helpers_navigator/command_tree.py +50 -18
  42. machineconfig/scripts/python/helpers_repos/cloud_repo_sync.py +5 -3
  43. machineconfig/scripts/python/helpers_repos/count_lines.py +40 -11
  44. machineconfig/scripts/python/helpers_repos/count_lines_frontend.py +1 -1
  45. machineconfig/scripts/python/helpers_utils/download.py +4 -3
  46. machineconfig/scripts/python/helpers_utils/path.py +87 -34
  47. machineconfig/scripts/python/interactive.py +1 -1
  48. machineconfig/scripts/python/{machineconfig.py → mcfg_entry.py} +4 -0
  49. machineconfig/scripts/python/msearch.py +55 -6
  50. machineconfig/scripts/python/nw/address.py +132 -0
  51. machineconfig/scripts/python/nw/devops_add_ssh_key.py +8 -5
  52. machineconfig/scripts/python/terminal.py +2 -2
  53. machineconfig/scripts/python/utils.py +12 -11
  54. machineconfig/scripts/windows/mounts/mount_ssh.ps1 +1 -1
  55. machineconfig/settings/lf/windows/lfcd.ps1 +1 -1
  56. machineconfig/settings/shells/nushell/config.nu +2 -2
  57. machineconfig/settings/shells/nushell/env.nu +45 -6
  58. machineconfig/settings/shells/nushell/init.nu +282 -95
  59. machineconfig/settings/shells/pwsh/init.ps1 +1 -0
  60. machineconfig/settings/yazi/init.lua +4 -0
  61. machineconfig/settings/yazi/keymap_linux.toml +11 -4
  62. machineconfig/settings/yazi/theme.toml +4 -0
  63. machineconfig/settings/yazi/yazi_linux.toml +84 -0
  64. machineconfig/settings/yazi/yazi_windows.toml +58 -0
  65. machineconfig/setup_linux/web_shortcuts/interactive.sh +10 -10
  66. machineconfig/setup_windows/uv.ps1 +8 -1
  67. machineconfig/setup_windows/web_shortcuts/interactive.ps1 +10 -10
  68. machineconfig/setup_windows/web_shortcuts/quick_init.ps1 +3 -2
  69. machineconfig/utils/accessories.py +7 -4
  70. machineconfig/utils/code.py +4 -2
  71. machineconfig/utils/installer_utils/github_release_bulk.py +104 -62
  72. machineconfig/utils/installer_utils/install_from_url.py +200 -0
  73. machineconfig/utils/installer_utils/installer_class.py +25 -74
  74. machineconfig/utils/installer_utils/installer_cli.py +40 -50
  75. machineconfig/utils/installer_utils/installer_helper.py +100 -0
  76. machineconfig/utils/installer_utils/installer_runner.py +5 -8
  77. machineconfig/utils/links.py +2 -2
  78. machineconfig/utils/meta.py +2 -2
  79. machineconfig/utils/options.py +3 -3
  80. machineconfig/utils/path_extended.py +1 -1
  81. machineconfig/utils/path_helper.py +0 -1
  82. machineconfig/utils/ssh.py +143 -409
  83. machineconfig/utils/ssh_utils/abc.py +8 -0
  84. machineconfig/utils/ssh_utils/copy_from_here.py +110 -0
  85. machineconfig/utils/ssh_utils/copy_to_here.py +302 -0
  86. machineconfig/utils/ssh_utils/utils.py +141 -0
  87. machineconfig/utils/ssh_utils/wsl.py +210 -0
  88. machineconfig/utils/upgrade_packages.py +2 -1
  89. machineconfig/utils/ve.py +11 -4
  90. {machineconfig-7.64.dist-info → machineconfig-7.83.dist-info}/METADATA +2 -2
  91. {machineconfig-7.64.dist-info → machineconfig-7.83.dist-info}/RECORD +96 -89
  92. {machineconfig-7.64.dist-info → machineconfig-7.83.dist-info}/entry_points.txt +2 -2
  93. machineconfig/scripts/python/explore.py +0 -49
  94. machineconfig/scripts/python/helpers_msearch/scripts_linux/fzfag +0 -17
  95. machineconfig/scripts/python/helpers_msearch/scripts_linux/fzfrga +0 -21
  96. machineconfig/scripts/python/helpers_msearch/scripts_linux/skrg +0 -4
  97. machineconfig/scripts/python/helpers_msearch/scripts_windows/fzfb.ps1 +0 -3
  98. machineconfig/scripts/python/helpers_msearch/scripts_windows/fzfrga.bat +0 -20
  99. machineconfig/settings/yazi/yazi.toml +0 -17
  100. machineconfig/setup_linux/others/cli_installation.sh +0 -137
  101. /machineconfig/{settings/shells/pwsh/profile.ps1 → scripts/python/helpers_fire_command/f.py} +0 -0
  102. /machineconfig/scripts/{Restore-ThunderbirdProfile.ps1 → windows/mounts/Restore-ThunderbirdProfile.ps1} +0 -0
  103. {machineconfig-7.64.dist-info → machineconfig-7.83.dist-info}/WHEEL +0 -0
  104. {machineconfig-7.64.dist-info → machineconfig-7.83.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,8 @@
1
+
2
+
3
+ import platform
4
+
5
+ UV_RUN_CMD = """ "$HOME/.local/bin/uv" run """ if platform.system() != "Windows" else """& "$env:USERPROFILE/.local/bin/uv" run"""
6
+ MACHINECONFIG_VERSION = "machineconfig>=7.83"
7
+ DEFAULT_PICKLE_SUBDIR = "tmp_results/tmp_scripts/ssh"
8
+
@@ -0,0 +1,110 @@
1
+
2
+
3
+ from typing import Optional
4
+ from pathlib import Path
5
+ from machineconfig.utils.accessories import randstr
6
+ from machineconfig.utils.meta import lambda_to_python_script
7
+ from machineconfig.utils.ssh_utils.abc import UV_RUN_CMD, DEFAULT_PICKLE_SUBDIR
8
+
9
+
10
+ def copy_from_here(
11
+ self: SSH, source_path: str, target_rel2home: Optional[str], compress_with_zip: bool, recursive: bool, overwrite_existing: bool
12
+ ) -> None:
13
+ if self.sftp is None:
14
+ raise RuntimeError(f"SFTP connection not available for {self.hostname}. Cannot transfer files.")
15
+ source_obj = Path(source_path).expanduser().absolute()
16
+ if not source_obj.exists():
17
+ raise RuntimeError(f"SSH Error: source `{source_obj}` does not exist!")
18
+ if target_rel2home is None:
19
+ try:
20
+ target_rel2home = str(source_obj.relative_to(Path.home()))
21
+ except ValueError:
22
+ raise RuntimeError(f"If target is not specified, source must be relative to home directory, but got: {source_obj}")
23
+ if not compress_with_zip and source_obj.is_dir():
24
+ if not recursive:
25
+ raise RuntimeError(
26
+ f"SSH Error: source `{source_obj}` is a directory! Set `recursive=True` for recursive sending or `compress_with_zip=True` to zip it first."
27
+ )
28
+ file_paths_to_upload: list[Path] = [file_path for file_path in source_obj.rglob("*") if file_path.is_file()]
29
+ self.create_parent_dir_and_check_if_exists(path_rel2home=target_rel2home, overwrite_existing=overwrite_existing)
30
+ for idx, file_path in enumerate(file_paths_to_upload):
31
+ print(f" {idx + 1:03d}. {file_path}")
32
+ for file_path in file_paths_to_upload:
33
+ remote_file_target = Path(target_rel2home).joinpath(file_path.relative_to(source_obj))
34
+ self.copy_from_here(
35
+ source_path=str(file_path),
36
+ target_rel2home=str(remote_file_target),
37
+ compress_with_zip=False,
38
+ recursive=False,
39
+ overwrite_existing=overwrite_existing,
40
+ )
41
+ return None
42
+ if compress_with_zip:
43
+ print("🗜️ ZIPPING ...")
44
+ import shutil
45
+
46
+ zip_path = Path(str(source_obj) + "_archive")
47
+ if source_obj.is_dir():
48
+ shutil.make_archive(str(zip_path), "zip", source_obj)
49
+ else:
50
+ shutil.make_archive(str(zip_path), "zip", source_obj.parent, source_obj.name)
51
+ source_obj = Path(str(zip_path) + ".zip")
52
+ if not target_rel2home.endswith(".zip"):
53
+ target_rel2home = target_rel2home + ".zip"
54
+ if Path(target_rel2home).parent.as_posix() not in {"", "."}:
55
+ self.create_parent_dir_and_check_if_exists(path_rel2home=target_rel2home, overwrite_existing=overwrite_existing)
56
+ print(f"""📤 [SFTP UPLOAD] Sending file: {repr(source_obj)} ==> Remote Path: {target_rel2home}""")
57
+ try:
58
+ with self.tqdm_wrap(ascii=True, unit="b", unit_scale=True) as pbar:
59
+ if self.sftp is None: # type: ignore[unreachable]
60
+ raise RuntimeError(f"SFTP connection lost for {self.hostname}")
61
+ print(f"Uploading {source_obj} to\n{Path(self.remote_specs['home_dir']).joinpath(target_rel2home)}")
62
+ self.sftp.put(
63
+ localpath=str(source_obj), remotepath=str(Path(self.remote_specs["home_dir"]).joinpath(target_rel2home)), callback=pbar.view_bar
64
+ )
65
+ except Exception:
66
+ if compress_with_zip and source_obj.exists() and str(source_obj).endswith("_archive.zip"):
67
+ source_obj.unlink()
68
+ raise
69
+
70
+ if compress_with_zip:
71
+
72
+ def unzip_archive(zip_file_path: str, overwrite_flag: bool) -> None:
73
+ from pathlib import Path
74
+ import shutil
75
+ import zipfile
76
+
77
+ archive_path = Path(zip_file_path).expanduser()
78
+ extraction_directory = archive_path.parent / archive_path.stem
79
+ if overwrite_flag and extraction_directory.exists():
80
+ shutil.rmtree(extraction_directory)
81
+ with zipfile.ZipFile(archive_path, "r") as archive_handle:
82
+ archive_handle.extractall(extraction_directory)
83
+ archive_path.unlink()
84
+
85
+ command = lambda_to_python_script(
86
+ lambda: unzip_archive(
87
+ zip_file_path=str(Path(self.remote_specs["home_dir"]).joinpath(target_rel2home)), overwrite_flag=overwrite_existing
88
+ ),
89
+ in_global=True,
90
+ import_module=False,
91
+ )
92
+ tmp_py_file = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/create_target_dir_{randstr()}.py")
93
+ tmp_py_file.parent.mkdir(parents=True, exist_ok=True)
94
+ tmp_py_file.write_text(command, encoding="utf-8")
95
+ remote_tmp_py = tmp_py_file.relative_to(Path.home()).as_posix()
96
+ self.copy_from_here(source_path=str(tmp_py_file), target_rel2home=None, compress_with_zip=False, recursive=False, overwrite_existing=True)
97
+ self.run_shell(
98
+ command=f"""{UV_RUN_CMD} python {remote_tmp_py}""",
99
+ verbose_output=False,
100
+ description=f"UNZIPPING {target_rel2home}",
101
+ strict_stderr=True,
102
+ strict_return_code=True,
103
+ )
104
+ source_obj.unlink()
105
+ tmp_py_file.unlink(missing_ok=True)
106
+ return None
107
+
108
+
109
+ if __name__ == "__main__":
110
+ from machineconfig.utils.ssh import SSH
@@ -0,0 +1,302 @@
1
+
2
+
3
+ from typing import Optional, Union
4
+ from pathlib import Path
5
+ from machineconfig.utils.accessories import randstr
6
+ from machineconfig.utils.meta import lambda_to_python_script
7
+ from machineconfig.utils.ssh_utils.abc import MACHINECONFIG_VERSION, DEFAULT_PICKLE_SUBDIR
8
+
9
+
10
+ def copy_to_here(
11
+ self: SSH,
12
+ source: Union[str, Path],
13
+ target: Optional[Union[str, Path]],
14
+ compress_with_zip: bool = False,
15
+ recursive: bool = False,
16
+ internal_call: bool = False,
17
+ ) -> None:
18
+ if self.sftp is None:
19
+ raise RuntimeError(f"SFTP connection not available for {self.hostname}. Cannot transfer files.")
20
+
21
+ if not internal_call:
22
+ print(f"{'⬇️' * 5} SFTP DOWNLOADING FROM `{source}` TO `{target}`")
23
+
24
+ source_obj = Path(source)
25
+ expanded_source = self.expand_remote_path(source_path=source_obj)
26
+
27
+ if not compress_with_zip:
28
+ is_dir = self.check_remote_is_dir(source_path=expanded_source)
29
+
30
+ if is_dir:
31
+ if not recursive:
32
+ raise RuntimeError(
33
+ f"SSH Error: source `{source_obj}` is a directory! Set recursive=True for recursive transfer or compress_with_zip=True to zip it."
34
+ )
35
+
36
+ def search_files(directory_path: str, json_output_path: str) -> list[str]:
37
+ from pathlib import Path
38
+ import json
39
+
40
+ file_paths_list = [
41
+ file_path.as_posix() for file_path in Path(directory_path).expanduser().absolute().rglob("*") if file_path.is_file()
42
+ ]
43
+ json_result_path = Path(json_output_path)
44
+ json_result_path.parent.mkdir(parents=True, exist_ok=True)
45
+ json_result_path.write_text(json.dumps(file_paths_list, indent=2), encoding="utf-8")
46
+ print(json_result_path.as_posix())
47
+ return file_paths_list
48
+
49
+ remote_json_output = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/return_{randstr()}.json").as_posix()
50
+ command = lambda_to_python_script(
51
+ lambda: search_files(directory_path=expanded_source, json_output_path=remote_json_output),
52
+ in_global=True, import_module=False
53
+ )
54
+ response = self.run_py(
55
+ python_code=command,
56
+ uv_with=[MACHINECONFIG_VERSION],
57
+ uv_project_dir=None,
58
+ description="Searching for files in source",
59
+ verbose_output=False,
60
+ strict_stderr=False,
61
+ strict_return_code=False,
62
+ )
63
+ remote_json_path = response.op.strip()
64
+ if not remote_json_path:
65
+ raise RuntimeError(f"Could not resolve source path {source} - no response from remote")
66
+
67
+ local_json = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/local_{randstr()}.json")
68
+ self.simple_sftp_get(remote_path=remote_json_path, local_path=local_json)
69
+ import json
70
+
71
+ try:
72
+ source_list_str = json.loads(local_json.read_text(encoding="utf-8"))
73
+ except (json.JSONDecodeError, FileNotFoundError) as err:
74
+ raise RuntimeError(f"Could not resolve source path {source} - invalid JSON response: {err}") from err
75
+ finally:
76
+ if local_json.exists():
77
+ local_json.unlink()
78
+ assert isinstance(source_list_str, list), f"Could not resolve source path {source}"
79
+ file_paths_to_download = [Path(file_path_str) for file_path_str in source_list_str]
80
+
81
+ if target is None:
82
+
83
+ def collapse_to_home_dir(absolute_path: str, json_output_path: str) -> str:
84
+ from pathlib import Path
85
+ import json
86
+
87
+ source_absolute_path = Path(absolute_path).expanduser().absolute()
88
+ try:
89
+ relative_to_home = source_absolute_path.relative_to(Path.home())
90
+ collapsed_path_posix = (Path("~") / relative_to_home).as_posix()
91
+ json_result_path = Path(json_output_path)
92
+ json_result_path.parent.mkdir(parents=True, exist_ok=True)
93
+ json_result_path.write_text(json.dumps(collapsed_path_posix, indent=2), encoding="utf-8")
94
+ print(json_result_path.as_posix())
95
+ return collapsed_path_posix
96
+ except ValueError:
97
+ raise RuntimeError(f"Source path must be relative to home directory: {source_absolute_path}")
98
+
99
+ remote_json_output = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/return_{randstr()}.json").as_posix()
100
+ command = lambda_to_python_script(
101
+ lambda: collapse_to_home_dir(absolute_path=expanded_source, json_output_path=remote_json_output),
102
+ in_global=True,
103
+ import_module=False,
104
+ )
105
+ response = self.run_py(
106
+ python_code=command,
107
+ uv_with=[MACHINECONFIG_VERSION],
108
+ uv_project_dir=None,
109
+ description="Finding default target via relative source path",
110
+ verbose_output=False,
111
+ strict_stderr=False,
112
+ strict_return_code=False,
113
+ )
114
+ remote_json_path_dir = response.op.strip()
115
+ if not remote_json_path_dir:
116
+ raise RuntimeError("Could not resolve target path - no response from remote")
117
+
118
+ local_json_dir = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/local_{randstr()}.json")
119
+ self.simple_sftp_get(remote_path=remote_json_path_dir, local_path=local_json_dir)
120
+ import json
121
+
122
+ try:
123
+ target_dir_str = json.loads(local_json_dir.read_text(encoding="utf-8"))
124
+ except (json.JSONDecodeError, FileNotFoundError) as err:
125
+ raise RuntimeError(f"Could not resolve target path - invalid JSON response: {err}") from err
126
+ finally:
127
+ if local_json_dir.exists():
128
+ local_json_dir.unlink()
129
+ assert isinstance(target_dir_str, str), "Could not resolve target path"
130
+ target = Path(target_dir_str)
131
+
132
+ target_dir = Path(target).expanduser().absolute()
133
+
134
+ for idx, file_path in enumerate(file_paths_to_download):
135
+ print(f" {idx + 1:03d}. {file_path}")
136
+
137
+ for file_path in file_paths_to_download:
138
+ local_file_target = target_dir.joinpath(Path(file_path).relative_to(expanded_source))
139
+ self.copy_to_here(source=file_path, target=local_file_target, compress_with_zip=False, recursive=False, internal_call=True)
140
+
141
+ return None
142
+
143
+ if compress_with_zip:
144
+ print("🗜️ ZIPPING ...")
145
+
146
+ def zip_source(path_to_zip: str, json_output_path: str) -> str:
147
+ from pathlib import Path
148
+ import shutil
149
+ import json
150
+
151
+ source_to_compress = Path(path_to_zip).expanduser().absolute()
152
+ archive_base_path = source_to_compress.parent / (source_to_compress.name + "_archive")
153
+ if source_to_compress.is_dir():
154
+ shutil.make_archive(str(archive_base_path), "zip", source_to_compress)
155
+ else:
156
+ shutil.make_archive(str(archive_base_path), "zip", source_to_compress.parent, source_to_compress.name)
157
+ zip_file_path = str(archive_base_path) + ".zip"
158
+ json_result_path = Path(json_output_path)
159
+ json_result_path.parent.mkdir(parents=True, exist_ok=True)
160
+ json_result_path.write_text(json.dumps(zip_file_path, indent=2), encoding="utf-8")
161
+ print(json_result_path.as_posix())
162
+ return zip_file_path
163
+
164
+ remote_json_output = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/return_{randstr()}.json").as_posix()
165
+ command = lambda_to_python_script(
166
+ lambda: zip_source(path_to_zip=expanded_source, json_output_path=remote_json_output),
167
+ in_global=True, import_module=False
168
+ )
169
+ response = self.run_py(
170
+ python_code=command,
171
+ uv_with=[MACHINECONFIG_VERSION],
172
+ uv_project_dir=None,
173
+ description=f"Zipping source file {source}",
174
+ verbose_output=False,
175
+ strict_stderr=False,
176
+ strict_return_code=False,
177
+ )
178
+ remote_json_path = response.op.strip()
179
+ if not remote_json_path:
180
+ raise RuntimeError(f"Could not zip {source} - no response from remote")
181
+
182
+ local_json = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/local_{randstr()}.json")
183
+ self.simple_sftp_get(remote_path=remote_json_path, local_path=local_json)
184
+ import json
185
+
186
+ try:
187
+ zipped_path = json.loads(local_json.read_text(encoding="utf-8"))
188
+ except (json.JSONDecodeError, FileNotFoundError) as err:
189
+ raise RuntimeError(f"Could not zip {source} - invalid JSON response: {err}") from err
190
+ finally:
191
+ if local_json.exists():
192
+ local_json.unlink()
193
+ assert isinstance(zipped_path, str), f"Could not zip {source}"
194
+ source_obj = Path(zipped_path)
195
+ expanded_source = zipped_path
196
+
197
+ if target is None:
198
+
199
+ def collapse_to_home(absolute_path: str, json_output_path: str) -> str:
200
+ from pathlib import Path
201
+ import json
202
+
203
+ source_absolute_path = Path(absolute_path).expanduser().absolute()
204
+ try:
205
+ relative_to_home = source_absolute_path.relative_to(Path.home())
206
+ collapsed_path_posix = (Path("~") / relative_to_home).as_posix()
207
+ json_result_path = Path(json_output_path)
208
+ json_result_path.parent.mkdir(parents=True, exist_ok=True)
209
+ json_result_path.write_text(json.dumps(collapsed_path_posix, indent=2), encoding="utf-8")
210
+ print(json_result_path.as_posix())
211
+ return collapsed_path_posix
212
+ except ValueError:
213
+ raise RuntimeError(f"Source path must be relative to home directory: {source_absolute_path}")
214
+
215
+ remote_json_output = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/return_{randstr()}.json").as_posix()
216
+ command = lambda_to_python_script(
217
+ lambda: collapse_to_home(absolute_path=expanded_source, json_output_path=remote_json_output),
218
+ in_global=True, import_module=False
219
+ )
220
+ response = self.run_py(
221
+ python_code=command,
222
+ uv_with=[MACHINECONFIG_VERSION],
223
+ uv_project_dir=None,
224
+ description="Finding default target via relative source path",
225
+ verbose_output=False,
226
+ strict_stderr=False,
227
+ strict_return_code=False,
228
+ )
229
+ remote_json_path = response.op.strip()
230
+ if not remote_json_path:
231
+ raise RuntimeError("Could not resolve target path - no response from remote")
232
+
233
+ local_json = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/local_{randstr()}.json")
234
+ self.simple_sftp_get(remote_path=remote_json_path, local_path=local_json)
235
+ import json
236
+
237
+ try:
238
+ target_str = json.loads(local_json.read_text(encoding="utf-8"))
239
+ except (json.JSONDecodeError, FileNotFoundError) as err:
240
+ raise RuntimeError(f"Could not resolve target path - invalid JSON response: {err}") from err
241
+ finally:
242
+ if local_json.exists():
243
+ local_json.unlink()
244
+ assert isinstance(target_str, str), "Could not resolve target path"
245
+ target = Path(target_str)
246
+ assert str(target).startswith("~"), f"If target is not specified, source must be relative to home.\n{target=}"
247
+
248
+ target_obj = Path(target).expanduser().absolute()
249
+ target_obj.parent.mkdir(parents=True, exist_ok=True)
250
+
251
+ if compress_with_zip and target_obj.suffix != ".zip":
252
+ target_obj = target_obj.with_suffix(target_obj.suffix + ".zip")
253
+
254
+ print(f"""📥 [DOWNLOAD] Receiving: {expanded_source} ==> Local Path: {target_obj}""")
255
+ try:
256
+ with self.tqdm_wrap(ascii=True, unit="b", unit_scale=True) as pbar:
257
+ if self.sftp is None: # type: ignore[unreachable]
258
+ raise RuntimeError(f"SFTP connection lost for {self.hostname}")
259
+ self.sftp.get(remotepath=expanded_source, localpath=str(target_obj), callback=pbar.view_bar) # type: ignore
260
+ except Exception:
261
+ if target_obj.exists():
262
+ target_obj.unlink()
263
+ raise
264
+
265
+ if compress_with_zip:
266
+ import zipfile
267
+
268
+ extract_to = target_obj.parent / target_obj.stem
269
+ with zipfile.ZipFile(target_obj, "r") as zip_ref:
270
+ zip_ref.extractall(extract_to)
271
+ target_obj.unlink()
272
+ target_obj = extract_to
273
+
274
+ def delete_temp_zip(path_to_delete: str) -> None:
275
+ from pathlib import Path
276
+ import shutil
277
+
278
+ file_or_dir_path = Path(path_to_delete)
279
+ if file_or_dir_path.exists():
280
+ if file_or_dir_path.is_dir():
281
+ shutil.rmtree(file_or_dir_path)
282
+ else:
283
+ file_or_dir_path.unlink()
284
+
285
+ command = lambda_to_python_script(lambda: delete_temp_zip(path_to_delete=expanded_source),
286
+ in_global=True, import_module=False)
287
+ self.run_py(
288
+ python_code=command,
289
+ uv_with=[MACHINECONFIG_VERSION],
290
+ uv_project_dir=None,
291
+ description="Cleaning temp zip files @ remote.",
292
+ verbose_output=False,
293
+ strict_stderr=True,
294
+ strict_return_code=True,
295
+ )
296
+
297
+ print("\n")
298
+ return None
299
+
300
+
301
+ if __name__ == "__main__":
302
+ from machineconfig.utils.ssh import SSH
@@ -0,0 +1,141 @@
1
+
2
+ from pathlib import Path
3
+ from machineconfig.utils.accessories import randstr
4
+ from machineconfig.utils.meta import lambda_to_python_script
5
+ from machineconfig.utils.ssh_utils.abc import MACHINECONFIG_VERSION, UV_RUN_CMD, DEFAULT_PICKLE_SUBDIR
6
+ from typing import Union
7
+
8
+
9
+ def create_dir_and_check_if_exists(self: SSH, path_rel2home: str, overwrite_existing: bool) -> None:
10
+ """Helper to create a directory on remote machine and return its path."""
11
+
12
+ def create_target_dir(target_rel2home: str, overwrite: bool):
13
+ from pathlib import Path
14
+ import shutil
15
+ target_path_abs = Path(target_rel2home).expanduser()
16
+ if not target_path_abs.is_absolute():
17
+ target_path_abs = Path.home().joinpath(target_path_abs)
18
+ if overwrite and target_path_abs.exists():
19
+ if str(target_path_abs) == str(Path.home()):
20
+ raise RuntimeError("Refusing to overwrite home directory!")
21
+ if target_path_abs.is_dir():
22
+ shutil.rmtree(target_path_abs)
23
+ else:
24
+ target_path_abs.unlink()
25
+ print(f"Creating directory for path: {target_path_abs}")
26
+ target_path_abs.parent.mkdir(parents=True, exist_ok=True)
27
+ command = lambda_to_python_script(
28
+ lambda: create_target_dir(target_rel2home=path_rel2home, overwrite=overwrite_existing),
29
+ in_global=True, import_module=False
30
+ )
31
+ tmp_py_file = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/create_target_dir_{randstr()}.py")
32
+ tmp_py_file.parent.mkdir(parents=True, exist_ok=True)
33
+ tmp_py_file.write_text(command, encoding="utf-8")
34
+ assert self.sftp is not None
35
+ tmp_remote_path = ".tmp_pyfile.py"
36
+ self.sftp.put(localpath=str(tmp_py_file), remotepath=str(Path(self.remote_specs["home_dir"]).joinpath(tmp_remote_path)))
37
+ resp = self.run_shell(
38
+ command=f"""{UV_RUN_CMD} python {tmp_remote_path}""",
39
+ verbose_output=False,
40
+ description=f"Creating target dir {path_rel2home}",
41
+ strict_stderr=True,
42
+ strict_return_code=True,
43
+ )
44
+ resp.print(desc=f"Created target dir {path_rel2home}")
45
+
46
+
47
+ def check_remote_is_dir(self: SSH, source_path: Union[str, Path]) -> bool:
48
+ """Helper to check if a remote path is a directory."""
49
+
50
+ def check_is_dir(path_to_check: str, json_output_path: str) -> bool:
51
+ from pathlib import Path
52
+ import json
53
+
54
+ is_directory = Path(path_to_check).expanduser().absolute().is_dir()
55
+ json_result_path = Path(json_output_path)
56
+ json_result_path.parent.mkdir(parents=True, exist_ok=True)
57
+ json_result_path.write_text(json.dumps(is_directory, indent=2), encoding="utf-8")
58
+ print(json_result_path.as_posix())
59
+ return is_directory
60
+
61
+ remote_json_output = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/return_{randstr()}.json").as_posix()
62
+ command = lambda_to_python_script(
63
+ lambda: check_is_dir(path_to_check=str(source_path), json_output_path=remote_json_output),
64
+ in_global=True, import_module=False
65
+ )
66
+ response = self.run_py(
67
+ python_code=command,
68
+ uv_with=[MACHINECONFIG_VERSION],
69
+ uv_project_dir=None,
70
+ description=f"Check if source `{source_path}` is a dir",
71
+ verbose_output=False,
72
+ strict_stderr=False,
73
+ strict_return_code=False,
74
+ )
75
+ remote_json_path = response.op.strip()
76
+ if not remote_json_path:
77
+ raise RuntimeError(f"Failed to check if {source_path} is directory - no response from remote")
78
+
79
+ local_json = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/local_{randstr()}.json")
80
+ self.simple_sftp_get(remote_path=remote_json_path, local_path=local_json)
81
+ import json
82
+
83
+ try:
84
+ result = json.loads(local_json.read_text(encoding="utf-8"))
85
+ except (json.JSONDecodeError, FileNotFoundError) as err:
86
+ raise RuntimeError(f"Failed to check if {source_path} is directory - invalid JSON response: {err}") from err
87
+ finally:
88
+ if local_json.exists():
89
+ local_json.unlink()
90
+ assert isinstance(result, bool), f"Failed to check if {source_path} is directory"
91
+ return result
92
+
93
+ def expand_remote_path(self: SSH, source_path: Union[str, Path]) -> str:
94
+ """Helper to expand a path on the remote machine."""
95
+
96
+ def expand_source(path_to_expand: str, json_output_path: str) -> str:
97
+ from pathlib import Path
98
+ import json
99
+
100
+ expanded_path_posix = Path(path_to_expand).expanduser().absolute().as_posix()
101
+ json_result_path = Path(json_output_path)
102
+ json_result_path.parent.mkdir(parents=True, exist_ok=True)
103
+ json_result_path.write_text(json.dumps(expanded_path_posix, indent=2), encoding="utf-8")
104
+ print(json_result_path.as_posix())
105
+ return expanded_path_posix
106
+
107
+ remote_json_output = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/return_{randstr()}.json").as_posix()
108
+ command = lambda_to_python_script(
109
+ lambda: expand_source(path_to_expand=str(source_path), json_output_path=remote_json_output),
110
+ in_global=True, import_module=False
111
+ )
112
+ response = self.run_py(
113
+ python_code=command,
114
+ uv_with=[MACHINECONFIG_VERSION],
115
+ uv_project_dir=None,
116
+ description="Resolving source path by expanding user",
117
+ verbose_output=False,
118
+ strict_stderr=False,
119
+ strict_return_code=False,
120
+ )
121
+ remote_json_path = response.op.strip()
122
+ if not remote_json_path:
123
+ raise RuntimeError(f"Could not resolve source path {source_path} - no response from remote")
124
+
125
+ local_json = Path.home().joinpath(f"{DEFAULT_PICKLE_SUBDIR}/local_{randstr()}.json")
126
+ self.simple_sftp_get(remote_path=remote_json_path, local_path=local_json)
127
+ import json
128
+
129
+ try:
130
+ result = json.loads(local_json.read_text(encoding="utf-8"))
131
+ except (json.JSONDecodeError, FileNotFoundError) as err:
132
+ raise RuntimeError(f"Could not resolve source path {source_path} - invalid JSON response: {err}") from err
133
+ finally:
134
+ if local_json.exists():
135
+ local_json.unlink()
136
+ assert isinstance(result, str), f"Could not resolve source path {source_path}"
137
+ return result
138
+
139
+
140
+ if __name__ == "__main__":
141
+ from machineconfig.utils.ssh import SSH