womm-cli 4.0.0__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.
- womm/__init__.py +53 -0
- womm/__main__.py +48 -0
- womm/_version.py +10 -0
- womm/assets/copier/meta/copier.yml +15 -0
- womm/assets/copier/meta/template/README.md.jinja +32 -0
- womm/assets/copier/meta/template/copier.yml.jinja +13 -0
- womm/assets/copier/meta/template/template/.gitkeep +0 -0
- womm/assets/copier/official/javascript/copier.yml +104 -0
- womm/assets/copier/official/javascript/template/.gitignore.jinja +35 -0
- womm/assets/copier/official/javascript/template/.nvmrc.jinja +1 -0
- womm/assets/copier/official/javascript/template/.prettierignore.jinja +10 -0
- womm/assets/copier/official/javascript/template/README.md.jinja +81 -0
- womm/assets/copier/official/javascript/template/biome.json.jinja +54 -0
- womm/assets/copier/official/javascript/template/eslint.config.mjs.jinja +51 -0
- womm/assets/copier/official/javascript/template/index.html.jinja +12 -0
- womm/assets/copier/official/javascript/template/package.json.jinja +88 -0
- womm/assets/copier/official/javascript/template/prettier.config.mjs.jinja +8 -0
- womm/assets/copier/official/javascript/template/src/App.jsx.jinja +10 -0
- womm/assets/copier/official/javascript/template/src/App.tsx.jinja +10 -0
- womm/assets/copier/official/javascript/template/src/App.vue.jinja +18 -0
- womm/assets/copier/official/javascript/template/src/index.jsx.jinja +10 -0
- womm/assets/copier/official/javascript/template/src/index.tsx.jinja +11 -0
- womm/assets/copier/official/javascript/template/src/main.js.jinja +21 -0
- womm/assets/copier/official/javascript/template/src/main.ts.jinja +21 -0
- womm/assets/copier/official/javascript/template/tsconfig.json.jinja +35 -0
- womm/assets/copier/official/javascript/template/vite.config.mjs.jinja +10 -0
- womm/assets/copier/official/javascript/template/{% if with_ci %}.github{% endif %}/workflows/ci.yml.jinja +63 -0
- womm/assets/copier/official/javascript/template/{% if with_tests %}tests{% endif %}/smoke.test.js.jinja +12 -0
- womm/assets/copier/official/javascript/template/{% if with_tests %}tests{% endif %}/smoke.test.ts.jinja +12 -0
- womm/assets/copier/official/javascript/template/{% if with_vscode %}.vscode{% endif %}/extensions.json.jinja +4 -0
- womm/assets/copier/official/javascript/template/{% if with_vscode %}.vscode{% endif %}/settings.json.jinja +27 -0
- womm/assets/copier/official/python/copier.yml +107 -0
- womm/assets/copier/official/python/template/.gitignore.jinja +40 -0
- womm/assets/copier/official/python/template/.pre-commit-config.yaml.jinja +19 -0
- womm/assets/copier/official/python/template/.python-version.jinja +1 -0
- womm/assets/copier/official/python/template/README.md.jinja +83 -0
- womm/assets/copier/official/python/template/pyproject.toml.jinja +114 -0
- womm/assets/copier/official/python/template/{% if framework == 'django' %}manage.py{% endif %}.jinja +23 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/__init__.py.jinja +3 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/asgi.py.jinja +9 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/core/__init__.py.jinja +0 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/core/apps.py.jinja +10 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/core/models.py.jinja +1 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/core/views.py.jinja +8 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/py.typed +0 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/settings.py.jinja +81 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/urls.py.jinja +11 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/wsgi.py.jinja +9 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/__init__.py.jinja +3 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/asgi.py.jinja +9 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/core/__init__.py.jinja +0 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/core/apps.py.jinja +10 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/core/models.py.jinja +1 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/core/views.py.jinja +8 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/py.typed +0 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/settings.py.jinja +81 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/urls.py.jinja +11 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/wsgi.py.jinja +9 -0
- womm/assets/copier/official/python/template/{% if with_ci %}.github{% endif %}/workflows/ci.yml.jinja +78 -0
- womm/assets/copier/official/python/template/{% if with_tests %}tests{% endif %}/test_smoke.py.jinja +16 -0
- womm/assets/copier/official/python/template/{% if with_vscode %}.vscode{% endif %}/extensions.json.jinja +8 -0
- womm/assets/copier/official/python/template/{% if with_vscode %}.vscode{% endif %}/settings.json.jinja +28 -0
- womm/bin/refresh_env.cmd +130 -0
- womm/cli.py +111 -0
- womm/commands/__init__.py +30 -0
- womm/commands/core/__init__.py +29 -0
- womm/commands/core/doctor.py +52 -0
- womm/commands/core/path.py +337 -0
- womm/commands/project/__init__.py +31 -0
- womm/commands/project/create.py +128 -0
- womm/commands/project/setup.py +438 -0
- womm/commands/project/template.py +160 -0
- womm/commands/system/__init__.py +31 -0
- womm/commands/system/context/__init__.py +82 -0
- womm/commands/system/context/backup.py +344 -0
- womm/commands/system/context/inventory.py +111 -0
- womm/commands/system/context/registration.py +290 -0
- womm/commands/system/deps.py +165 -0
- womm/commands/system/system.py +130 -0
- womm/exceptions/__init__.py +69 -0
- womm/exceptions/common/__init__.py +55 -0
- womm/exceptions/common/command_service.py +91 -0
- womm/exceptions/common/file_service.py +60 -0
- womm/exceptions/common/security_service.py +44 -0
- womm/exceptions/common/validation_service.py +70 -0
- womm/exceptions/context/__init__.py +27 -0
- womm/exceptions/context/context_service.py +55 -0
- womm/exceptions/project/__init__.py +29 -0
- womm/exceptions/project/project_service.py +59 -0
- womm/exceptions/system/__init__.py +25 -0
- womm/exceptions/system/system_service.py +53 -0
- womm/interfaces/__init__.py +71 -0
- womm/interfaces/context/__init__.py +34 -0
- womm/interfaces/context/menu_interface.py +686 -0
- womm/interfaces/context/registry_interface.py +562 -0
- womm/interfaces/context/script_detector_interface.py +208 -0
- womm/interfaces/context/script_registrar.py +264 -0
- womm/interfaces/core/__init__.py +26 -0
- womm/interfaces/core/doctor_interface.py +102 -0
- womm/interfaces/dependencies/__init__.py +28 -0
- womm/interfaces/dependencies/deps_interface.py +160 -0
- womm/interfaces/project/__init__.py +36 -0
- womm/interfaces/project/create_interface.py +162 -0
- womm/interfaces/project/detection_interface.py +181 -0
- womm/interfaces/project/manager_interface.py +99 -0
- womm/interfaces/project/setup_interface.py +477 -0
- womm/interfaces/project/template_store_interface.py +196 -0
- womm/interfaces/system/__init__.py +32 -0
- womm/interfaces/system/detector_interface.py +84 -0
- womm/interfaces/system/environment_interface.py +110 -0
- womm/interfaces/system/path_interface.py +570 -0
- womm/services/__init__.py +70 -0
- womm/services/common/__init__.py +33 -0
- womm/services/common/base_validation_service.py +450 -0
- womm/services/common/command_runner_service.py +647 -0
- womm/services/common/file_scanner_service.py +483 -0
- womm/services/common/security_validator_service.py +348 -0
- womm/services/context/__init__.py +37 -0
- womm/services/context/backup_entries.py +148 -0
- womm/services/context/parameters.py +515 -0
- womm/services/context/registry_paths.py +56 -0
- womm/services/context/registry_service.py +573 -0
- womm/services/context/validation_service.py +691 -0
- womm/services/dependencies/__init__.py +29 -0
- womm/services/dependencies/probe.py +102 -0
- womm/services/project/__init__.py +48 -0
- womm/services/project/copier_project_creation_service.py +111 -0
- womm/services/project/destination_guard.py +96 -0
- womm/services/project/detection_service.py +354 -0
- womm/services/project/env_utils.py +333 -0
- womm/services/project/javascript_environment_service.py +348 -0
- womm/services/project/python_environment_service.py +245 -0
- womm/services/project/setup_profile_resolver.py +146 -0
- womm/services/project/template_store_service.py +344 -0
- womm/services/project/validation_service.py +418 -0
- womm/services/system/__init__.py +32 -0
- womm/services/system/detector_service.py +704 -0
- womm/services/system/environment_service.py +494 -0
- womm/services/system/path_service.py +642 -0
- womm/shared/__init__.py +30 -0
- womm/shared/configs/__init__.py +51 -0
- womm/shared/configs/context/__init__.py +43 -0
- womm/shared/configs/context/context_config.py +125 -0
- womm/shared/configs/context/context_file_types_config.py +159 -0
- womm/shared/configs/context/context_limits_config.py +187 -0
- womm/shared/configs/context/context_paths_config.py +115 -0
- womm/shared/configs/context/context_types_config.py +65 -0
- womm/shared/configs/context/script_config.py +219 -0
- womm/shared/configs/dependencies/__init__.py +32 -0
- womm/shared/configs/dependencies/runtime_config.py +46 -0
- womm/shared/configs/dependencies/runtime_package_manager_config.py +48 -0
- womm/shared/configs/logging_config.py +89 -0
- womm/shared/configs/project/__init__.py +33 -0
- womm/shared/configs/project/project_config.py +109 -0
- womm/shared/configs/project/project_structure_config.py +88 -0
- womm/shared/configs/project/python_project_config.py +165 -0
- womm/shared/configs/security/__init__.py +26 -0
- womm/shared/configs/security/security_patterns_config.py +242 -0
- womm/shared/configs/system/__init__.py +28 -0
- womm/shared/configs/system/system_detector_config.py +210 -0
- womm/shared/configs/system/system_environment_config.py +101 -0
- womm/shared/models/__init__.py +13 -0
- womm/shared/models/template_source.py +65 -0
- womm/shared/paths.py +192 -0
- womm/shared/results/__init__.py +138 -0
- womm/shared/results/base.py +85 -0
- womm/shared/results/command_results.py +61 -0
- womm/shared/results/context_results.py +345 -0
- womm/shared/results/dependency_results.py +110 -0
- womm/shared/results/doctor_results.py +41 -0
- womm/shared/results/file_results.py +97 -0
- womm/shared/results/project_results.py +163 -0
- womm/shared/results/security_results.py +128 -0
- womm/shared/results/system_results.py +268 -0
- womm/shared/results/template_results.py +43 -0
- womm/shared/runtime.py +36 -0
- womm/ui/__init__.py +31 -0
- womm/ui/common/__init__.py +39 -0
- womm/ui/common/interactive_menu.py +246 -0
- womm/ui/common/logging.py +184 -0
- womm/ui/common/prompts.py +93 -0
- womm/ui/context/__init__.py +31 -0
- womm/ui/context/display.py +485 -0
- womm/ui/context/menu_display.py +189 -0
- womm/ui/context/wizard.py +557 -0
- womm/ui/project/__init__.py +42 -0
- womm/ui/project/create/create_completion_summaries.py +55 -0
- womm/ui/project/project_wizard.py +174 -0
- womm/ui/project/setup/setup_completion_summaries.py +111 -0
- womm/ui/project/templates/template_store_display.py +128 -0
- womm/ui/system/__init__.py +60 -0
- womm/ui/system/display.py +531 -0
- womm/ui/system/path_display.py +387 -0
- womm/utils/__init__.py +23 -0
- womm/utils/common/__init__.py +49 -0
- womm/utils/common/file_scanner_utils.py +110 -0
- womm/utils/common/path_resolver_utils.py +127 -0
- womm/utils/common/safe_fs_utils.py +135 -0
- womm/utils/context/__init__.py +54 -0
- womm/utils/context/core_utils.py +345 -0
- womm/utils/context/icon_utils.py +259 -0
- womm/utils/project/__init__.py +106 -0
- womm/utils/project/asset_utils.py +154 -0
- womm/utils/project/core_utils.py +391 -0
- womm/utils/project/file_utils.py +494 -0
- womm/utils/project/platform_utils.py +170 -0
- womm/utils/project/validation_utils.py +273 -0
- womm/utils/security/__init__.py +46 -0
- womm/utils/security/security_validation_utils.py +258 -0
- womm/utils/system/__init__.py +69 -0
- womm/utils/system/detector_utils.py +299 -0
- womm/utils/system/environment_utils.py +172 -0
- womm/utils/system/path_utils.py +101 -0
- womm_cli-4.0.0.dist-info/METADATA +203 -0
- womm_cli-4.0.0.dist-info/RECORD +218 -0
- womm_cli-4.0.0.dist-info/WHEEL +4 -0
- womm_cli-4.0.0.dist-info/entry_points.txt +2 -0
- womm_cli-4.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,647 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# ///////////////////////////////////////////////////////////////
|
|
3
|
+
# COMMAND RUNNER SERVICE - Unified CLI Command Runner
|
|
4
|
+
# Project: works-on-my-machine
|
|
5
|
+
# ///////////////////////////////////////////////////////////////
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
CommandRunnerService - unified, secure command execution service.
|
|
9
|
+
|
|
10
|
+
Provides a singleton service for running commands with:
|
|
11
|
+
- optional security validation
|
|
12
|
+
- retry/timeout handling
|
|
13
|
+
- structured error reporting via dedicated exceptions.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
# ///////////////////////////////////////////////////////////////
|
|
19
|
+
# IMPORTS
|
|
20
|
+
# ///////////////////////////////////////////////////////////////
|
|
21
|
+
# Standard library imports
|
|
22
|
+
import logging
|
|
23
|
+
import re
|
|
24
|
+
import subprocess # nosec B404 - running external tools is this package's purpose
|
|
25
|
+
import time
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from threading import Lock
|
|
28
|
+
from typing import Any, ClassVar
|
|
29
|
+
|
|
30
|
+
# Local imports
|
|
31
|
+
from ...exceptions.common import (
|
|
32
|
+
CommandExecutionError,
|
|
33
|
+
CommandServiceError,
|
|
34
|
+
CommandTimeoutError,
|
|
35
|
+
CommandUtilityError,
|
|
36
|
+
SecurityServiceError,
|
|
37
|
+
)
|
|
38
|
+
from ...shared.results import (
|
|
39
|
+
CommandAvailabilityResult,
|
|
40
|
+
CommandResult,
|
|
41
|
+
CommandVersionResult,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
# ///////////////////////////////////////////////////////////////
|
|
45
|
+
# VERSION PARSING
|
|
46
|
+
# ///////////////////////////////////////////////////////////////
|
|
47
|
+
|
|
48
|
+
# Two dotted components at least: a lone integer is far more often a word
|
|
49
|
+
# fragment ("python3") than a version, and reporting it would be worse than
|
|
50
|
+
# reporting nothing.
|
|
51
|
+
_VERSION_PATTERN = re.compile(r"\d+\.\d+(?:\.\d+)*")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _extract_version_number(output: str) -> str:
|
|
55
|
+
"""Extract a version number from a ``--version`` banner.
|
|
56
|
+
|
|
57
|
+
Tools format that banner freely — ``Python 3.13.1``, ``git version
|
|
58
|
+
2.47.1.windows.1``, ``pip 24.0 from C:\\...\\pip (python 3.13)``,
|
|
59
|
+
``v22.11.0``. Only the number is meaningful, so the first dotted number
|
|
60
|
+
of the first line is taken and everything around it dropped.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
output: Raw command output (stdout, or stderr as a fallback).
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
The version number, or an empty string when the output carries none —
|
|
67
|
+
callers must then report the version as unknown, never a raw fragment.
|
|
68
|
+
"""
|
|
69
|
+
first_line = output.strip().split("\n")[0]
|
|
70
|
+
match = _VERSION_PATTERN.search(first_line)
|
|
71
|
+
return match.group(0) if match else ""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# ///////////////////////////////////////////////////////////////
|
|
75
|
+
# COMMAND RUNNER SERVICE CLASS
|
|
76
|
+
# ///////////////////////////////////////////////////////////////
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class CommandRunnerService:
|
|
80
|
+
"""Singleton command runner with optional security validation."""
|
|
81
|
+
|
|
82
|
+
_instance: ClassVar[CommandRunnerService | None] = None
|
|
83
|
+
_initialized: ClassVar[bool] = False
|
|
84
|
+
_lock: ClassVar[Lock] = Lock()
|
|
85
|
+
|
|
86
|
+
def __new__(
|
|
87
|
+
cls,
|
|
88
|
+
default_cwd: str | Path | None = None,
|
|
89
|
+
timeout: int = 30,
|
|
90
|
+
max_retries: int = 3,
|
|
91
|
+
retry_delay: float = 1.0,
|
|
92
|
+
) -> CommandRunnerService:
|
|
93
|
+
"""Create or return the singleton instance."""
|
|
94
|
+
del default_cwd, timeout, max_retries, retry_delay
|
|
95
|
+
with cls._lock:
|
|
96
|
+
if cls._instance is None:
|
|
97
|
+
cls._instance = super().__new__(cls)
|
|
98
|
+
return cls._instance
|
|
99
|
+
|
|
100
|
+
def __init__(
|
|
101
|
+
self,
|
|
102
|
+
default_cwd: str | Path | None = None,
|
|
103
|
+
timeout: int = 30,
|
|
104
|
+
max_retries: int = 3,
|
|
105
|
+
retry_delay: float = 1.0,
|
|
106
|
+
) -> None:
|
|
107
|
+
"""Initialize command runner service (only once).
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
default_cwd: Default working directory
|
|
111
|
+
timeout: Command timeout in seconds
|
|
112
|
+
max_retries: Maximum number of retries for failed commands
|
|
113
|
+
retry_delay: Delay between retries in seconds
|
|
114
|
+
|
|
115
|
+
Raises:
|
|
116
|
+
CommandUtilityError: If initialization parameters are invalid
|
|
117
|
+
"""
|
|
118
|
+
if CommandRunnerService._initialized:
|
|
119
|
+
return
|
|
120
|
+
|
|
121
|
+
try:
|
|
122
|
+
# Validate initialization parameters
|
|
123
|
+
self._validate_init_parameters(timeout, max_retries, retry_delay)
|
|
124
|
+
|
|
125
|
+
self.default_cwd = Path(default_cwd) if default_cwd else Path.cwd()
|
|
126
|
+
self.timeout = timeout
|
|
127
|
+
self.max_retries = max_retries
|
|
128
|
+
self.retry_delay = retry_delay
|
|
129
|
+
self.logger = logging.getLogger(__name__)
|
|
130
|
+
CommandRunnerService._initialized = True
|
|
131
|
+
|
|
132
|
+
except (
|
|
133
|
+
CommandUtilityError,
|
|
134
|
+
CommandExecutionError,
|
|
135
|
+
SecurityServiceError,
|
|
136
|
+
CommandTimeoutError,
|
|
137
|
+
):
|
|
138
|
+
# Re-raise specialized exceptions as-is
|
|
139
|
+
raise
|
|
140
|
+
except (OSError, TypeError, ValueError) as e:
|
|
141
|
+
# Wrap unexpected external exceptions
|
|
142
|
+
raise CommandUtilityError(
|
|
143
|
+
message=f"Unexpected error during CLI manager initialization: {e}",
|
|
144
|
+
details=f"Exception type: {type(e).__name__}",
|
|
145
|
+
) from e
|
|
146
|
+
|
|
147
|
+
# ///////////////////////////////////////////////////////////////
|
|
148
|
+
# PUBLIC API METHODS
|
|
149
|
+
# ///////////////////////////////////////////////////////////////
|
|
150
|
+
|
|
151
|
+
def run(
|
|
152
|
+
self,
|
|
153
|
+
command: str | list[str],
|
|
154
|
+
description: str = "",
|
|
155
|
+
cwd: str | Path | None = None,
|
|
156
|
+
validate_security: bool = False,
|
|
157
|
+
**kwargs: Any,
|
|
158
|
+
) -> CommandResult:
|
|
159
|
+
"""Execute a command with optional security validation.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
command: Command to execute
|
|
163
|
+
description: Description for logging
|
|
164
|
+
cwd: Working directory
|
|
165
|
+
validate_security: Whether to validate command security
|
|
166
|
+
**kwargs: Additional subprocess arguments
|
|
167
|
+
|
|
168
|
+
Returns:
|
|
169
|
+
CommandResult: Result of command execution
|
|
170
|
+
|
|
171
|
+
Raises:
|
|
172
|
+
CommandUtilityError: If command validation fails
|
|
173
|
+
SecurityServiceError: If security validation fails
|
|
174
|
+
CommandTimeoutError: If command times out
|
|
175
|
+
CommandExecutionError: If command execution fails
|
|
176
|
+
"""
|
|
177
|
+
try:
|
|
178
|
+
# Input validation
|
|
179
|
+
self._validate_command_input(command)
|
|
180
|
+
|
|
181
|
+
# Convert string command to list
|
|
182
|
+
if isinstance(command, str):
|
|
183
|
+
command = [command]
|
|
184
|
+
elif not isinstance(command, list):
|
|
185
|
+
raise CommandUtilityError(
|
|
186
|
+
message=f"Command must be a string or list of strings, got: {type(command)}",
|
|
187
|
+
details=f"Invalid command type: {type(command).__name__}",
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
# Set working directory
|
|
191
|
+
working_dir = Path(cwd) if cwd else self.default_cwd
|
|
192
|
+
|
|
193
|
+
# Security validation if requested
|
|
194
|
+
if validate_security:
|
|
195
|
+
self._validate_command_security(command)
|
|
196
|
+
|
|
197
|
+
# Log command execution if description provided
|
|
198
|
+
if description:
|
|
199
|
+
self.logger.info(f"Executing command: {description}")
|
|
200
|
+
|
|
201
|
+
# Execute command with retries
|
|
202
|
+
start_time = time.time()
|
|
203
|
+
last_error = None
|
|
204
|
+
|
|
205
|
+
for attempt in range(self.max_retries + 1):
|
|
206
|
+
try:
|
|
207
|
+
result = self._execute_command(command, working_dir, **kwargs)
|
|
208
|
+
execution_time = time.time() - start_time
|
|
209
|
+
|
|
210
|
+
return CommandResult(
|
|
211
|
+
returncode=result.returncode,
|
|
212
|
+
stdout=result.stdout,
|
|
213
|
+
stderr=result.stderr,
|
|
214
|
+
command=command,
|
|
215
|
+
cwd=working_dir,
|
|
216
|
+
security_validated=validate_security,
|
|
217
|
+
execution_time=execution_time,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
except subprocess.TimeoutExpired as e:
|
|
221
|
+
last_error = CommandTimeoutError(
|
|
222
|
+
command=str(command),
|
|
223
|
+
timeout_seconds=self.timeout,
|
|
224
|
+
details=f"Attempt {attempt + 1}/{self.max_retries + 1}",
|
|
225
|
+
)
|
|
226
|
+
if attempt < self.max_retries:
|
|
227
|
+
time.sleep(self.retry_delay)
|
|
228
|
+
continue
|
|
229
|
+
else:
|
|
230
|
+
raise last_error from e
|
|
231
|
+
|
|
232
|
+
except subprocess.SubprocessError as e:
|
|
233
|
+
last_error = CommandExecutionError(
|
|
234
|
+
command=str(command),
|
|
235
|
+
return_code=getattr(e, "returncode", -1),
|
|
236
|
+
stderr=str(e),
|
|
237
|
+
details=f"Attempt {attempt + 1}/{self.max_retries + 1}: {e}",
|
|
238
|
+
)
|
|
239
|
+
if attempt < self.max_retries:
|
|
240
|
+
time.sleep(self.retry_delay)
|
|
241
|
+
continue
|
|
242
|
+
else:
|
|
243
|
+
raise last_error from e
|
|
244
|
+
|
|
245
|
+
except (OSError, TypeError, ValueError) as e:
|
|
246
|
+
last_error = CommandExecutionError(
|
|
247
|
+
command=str(command),
|
|
248
|
+
return_code=-1,
|
|
249
|
+
stderr=str(e),
|
|
250
|
+
details=f"Unexpected error on attempt {attempt + 1}/{self.max_retries + 1}: {e}",
|
|
251
|
+
)
|
|
252
|
+
if attempt < self.max_retries:
|
|
253
|
+
time.sleep(self.retry_delay)
|
|
254
|
+
continue
|
|
255
|
+
else:
|
|
256
|
+
raise last_error from e
|
|
257
|
+
|
|
258
|
+
# This should never be reached, but just in case
|
|
259
|
+
if last_error is None:
|
|
260
|
+
raise CommandUtilityError(
|
|
261
|
+
message="Command execution failed without exception context",
|
|
262
|
+
details=f"Command: {command}",
|
|
263
|
+
)
|
|
264
|
+
raise last_error
|
|
265
|
+
|
|
266
|
+
except (
|
|
267
|
+
CommandUtilityError,
|
|
268
|
+
SecurityServiceError,
|
|
269
|
+
CommandTimeoutError,
|
|
270
|
+
CommandExecutionError,
|
|
271
|
+
):
|
|
272
|
+
# Re-raise specialized exceptions as-is
|
|
273
|
+
raise
|
|
274
|
+
except CommandServiceError:
|
|
275
|
+
# Re-raise CLI-specific exceptions unchanged
|
|
276
|
+
raise
|
|
277
|
+
except (OSError, TypeError, ValueError) as e:
|
|
278
|
+
# Wrap unexpected external exceptions
|
|
279
|
+
raise CommandUtilityError(
|
|
280
|
+
message=f"Unexpected error during command execution: {e}",
|
|
281
|
+
details=f"Exception type: {type(e).__name__}, Command: {command}",
|
|
282
|
+
) from e
|
|
283
|
+
|
|
284
|
+
# ///////////////////////////////////////////////////////////////
|
|
285
|
+
# PRIVATE EXECUTION HELPERS
|
|
286
|
+
# ///////////////////////////////////////////////////////////////
|
|
287
|
+
|
|
288
|
+
def _execute_command(
|
|
289
|
+
self,
|
|
290
|
+
cmd: list[str],
|
|
291
|
+
cwd: Path,
|
|
292
|
+
**kwargs: Any,
|
|
293
|
+
) -> subprocess.CompletedProcess[str]:
|
|
294
|
+
"""Execute a single command attempt.
|
|
295
|
+
|
|
296
|
+
Args:
|
|
297
|
+
cmd: Command to execute as list of strings
|
|
298
|
+
cwd: Working directory
|
|
299
|
+
**kwargs: Additional subprocess arguments
|
|
300
|
+
|
|
301
|
+
Returns:
|
|
302
|
+
subprocess.CompletedProcess: Result of command execution
|
|
303
|
+
|
|
304
|
+
Raises:
|
|
305
|
+
CommandUtilityError: If command validation fails
|
|
306
|
+
subprocess.TimeoutExpired: If command times out
|
|
307
|
+
subprocess.SubprocessError: If command execution fails
|
|
308
|
+
"""
|
|
309
|
+
try:
|
|
310
|
+
# Validate command format
|
|
311
|
+
if not isinstance(cmd, list) or not all(
|
|
312
|
+
isinstance(arg, str) for arg in cmd
|
|
313
|
+
):
|
|
314
|
+
raise CommandUtilityError(
|
|
315
|
+
message=f"Command must be a list of strings, got: {type(cmd)}",
|
|
316
|
+
details=f"Invalid command format: {type(cmd).__name__}",
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
if not cmd:
|
|
320
|
+
raise CommandUtilityError(
|
|
321
|
+
message="Command cannot be empty",
|
|
322
|
+
details="Empty command list provided",
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
# Prepare subprocess arguments with explicit security settings
|
|
326
|
+
subprocess_args: dict[str, Any] = {
|
|
327
|
+
"cwd": cwd,
|
|
328
|
+
"timeout": self.timeout,
|
|
329
|
+
"text": True,
|
|
330
|
+
"encoding": "utf-8",
|
|
331
|
+
"errors": "replace",
|
|
332
|
+
"capture_output": True,
|
|
333
|
+
"shell": False, # Explicitly disable shell for security
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
# Add valid kwargs for subprocess
|
|
337
|
+
valid_subprocess_args = {
|
|
338
|
+
"input",
|
|
339
|
+
"env",
|
|
340
|
+
"check",
|
|
341
|
+
"stdin",
|
|
342
|
+
"stdout",
|
|
343
|
+
"stderr",
|
|
344
|
+
"preexec_fn",
|
|
345
|
+
"close_fds",
|
|
346
|
+
"pass_fds",
|
|
347
|
+
"restore_signals",
|
|
348
|
+
"start_new_session",
|
|
349
|
+
"group",
|
|
350
|
+
"extra_groups",
|
|
351
|
+
"user",
|
|
352
|
+
"umask",
|
|
353
|
+
"startupinfo",
|
|
354
|
+
"creationflags",
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
subprocess_args.update(
|
|
358
|
+
{
|
|
359
|
+
key: value
|
|
360
|
+
for key, value in kwargs.items()
|
|
361
|
+
if key in valid_subprocess_args
|
|
362
|
+
}
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
# Execute command with explicit security validation
|
|
366
|
+
# The command has already been validated by the calling method
|
|
367
|
+
return subprocess.run(cmd, check=False, **subprocess_args) # nosec B603 - cmd validated by SecurityValidatorService upstream
|
|
368
|
+
|
|
369
|
+
except (
|
|
370
|
+
CommandUtilityError,
|
|
371
|
+
subprocess.TimeoutExpired,
|
|
372
|
+
subprocess.SubprocessError,
|
|
373
|
+
):
|
|
374
|
+
# Re-raise specialized exceptions as-is
|
|
375
|
+
raise
|
|
376
|
+
except (OSError, TypeError, ValueError) as e:
|
|
377
|
+
# Wrap unexpected external exceptions
|
|
378
|
+
raise CommandUtilityError(
|
|
379
|
+
message=f"Unexpected error during command execution: {e}",
|
|
380
|
+
details=f"Exception type: {type(e).__name__}, Command: {cmd}",
|
|
381
|
+
) from e
|
|
382
|
+
|
|
383
|
+
# ///////////////////////////////////////////////////////////////
|
|
384
|
+
# PUBLIC CONVENIENCE METHODS (INSTANCE)
|
|
385
|
+
# ///////////////////////////////////////////////////////////////
|
|
386
|
+
|
|
387
|
+
def run_silent(self, command: str | list[str], **kwargs: Any) -> CommandResult:
|
|
388
|
+
"""Execute a command in silent mode.
|
|
389
|
+
|
|
390
|
+
Args:
|
|
391
|
+
command: Command to execute
|
|
392
|
+
**kwargs: Additional arguments for run method
|
|
393
|
+
|
|
394
|
+
Returns:
|
|
395
|
+
CommandResult: Result of command execution
|
|
396
|
+
"""
|
|
397
|
+
return self.run(command, **kwargs)
|
|
398
|
+
|
|
399
|
+
def run_secure(
|
|
400
|
+
self,
|
|
401
|
+
command: str | list[str],
|
|
402
|
+
description: str = "",
|
|
403
|
+
**kwargs: Any,
|
|
404
|
+
) -> CommandResult:
|
|
405
|
+
"""Execute a command with security validation.
|
|
406
|
+
|
|
407
|
+
Args:
|
|
408
|
+
command: Command to execute
|
|
409
|
+
description: Description for logging
|
|
410
|
+
**kwargs: Additional arguments for run method
|
|
411
|
+
|
|
412
|
+
Returns:
|
|
413
|
+
CommandResult: Result of command execution
|
|
414
|
+
"""
|
|
415
|
+
return self.run(command, description, validate_security=True, **kwargs)
|
|
416
|
+
|
|
417
|
+
def check_command_available(self, command: str) -> CommandAvailabilityResult:
|
|
418
|
+
"""Check if a command is available and optionally validate security.
|
|
419
|
+
|
|
420
|
+
Args:
|
|
421
|
+
command: Command to check
|
|
422
|
+
|
|
423
|
+
Returns:
|
|
424
|
+
CommandAvailabilityResult: Result with availability and security validation status
|
|
425
|
+
"""
|
|
426
|
+
try:
|
|
427
|
+
if not command:
|
|
428
|
+
return CommandAvailabilityResult(
|
|
429
|
+
success=False,
|
|
430
|
+
message="Command name is empty",
|
|
431
|
+
command_name=command,
|
|
432
|
+
is_available=False,
|
|
433
|
+
security_validated=False,
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
import shutil
|
|
437
|
+
|
|
438
|
+
if not shutil.which(command):
|
|
439
|
+
return CommandAvailabilityResult(
|
|
440
|
+
success=False,
|
|
441
|
+
message=f"Command '{command}' not found in PATH",
|
|
442
|
+
command_name=command,
|
|
443
|
+
is_available=False,
|
|
444
|
+
security_validated=False,
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
# Additional security check
|
|
448
|
+
security_validated = False
|
|
449
|
+
try:
|
|
450
|
+
from .security_validator_service import SecurityValidatorService
|
|
451
|
+
|
|
452
|
+
validator = SecurityValidatorService()
|
|
453
|
+
validation_result = validator.validate_command([command])
|
|
454
|
+
security_validated = validation_result.is_valid
|
|
455
|
+
except ImportError:
|
|
456
|
+
# If security validator is not available, skip security validation
|
|
457
|
+
security_validated = True
|
|
458
|
+
except (OSError, SecurityServiceError, TypeError, ValueError):
|
|
459
|
+
# If security validation fails, command is not secure
|
|
460
|
+
security_validated = False
|
|
461
|
+
|
|
462
|
+
return CommandAvailabilityResult(
|
|
463
|
+
success=True,
|
|
464
|
+
message=f"Command '{command}' is available",
|
|
465
|
+
command_name=command,
|
|
466
|
+
is_available=True,
|
|
467
|
+
security_validated=security_validated,
|
|
468
|
+
)
|
|
469
|
+
|
|
470
|
+
except (OSError, TypeError, ValueError) as e:
|
|
471
|
+
# Log but don't raise - this is a helper method
|
|
472
|
+
self.logger.warning(
|
|
473
|
+
f"Error checking command availability: {command}, Error: {e}"
|
|
474
|
+
)
|
|
475
|
+
return CommandAvailabilityResult(
|
|
476
|
+
success=False,
|
|
477
|
+
error=str(e),
|
|
478
|
+
command_name=command,
|
|
479
|
+
is_available=False,
|
|
480
|
+
security_validated=False,
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
def get_command_version(
|
|
484
|
+
self,
|
|
485
|
+
command: str,
|
|
486
|
+
version_flag: str = "--version",
|
|
487
|
+
) -> CommandVersionResult:
|
|
488
|
+
"""Get version of a command.
|
|
489
|
+
|
|
490
|
+
Args:
|
|
491
|
+
command: Command to get version for
|
|
492
|
+
version_flag: Flag to use for version check
|
|
493
|
+
|
|
494
|
+
Returns:
|
|
495
|
+
CommandVersionResult: Result with version information
|
|
496
|
+
"""
|
|
497
|
+
try:
|
|
498
|
+
if not command:
|
|
499
|
+
return CommandVersionResult(
|
|
500
|
+
success=False,
|
|
501
|
+
message="Command name is empty",
|
|
502
|
+
command_name=command,
|
|
503
|
+
version="",
|
|
504
|
+
version_flag=version_flag,
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
availability_result = self.check_command_available(command)
|
|
508
|
+
if not availability_result.is_available:
|
|
509
|
+
return CommandVersionResult(
|
|
510
|
+
success=False,
|
|
511
|
+
message=f"Command '{command}' not available",
|
|
512
|
+
command_name=command,
|
|
513
|
+
version="",
|
|
514
|
+
version_flag=version_flag,
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
result = self.run_silent([command, version_flag])
|
|
518
|
+
# Some tools print their version banner on stderr (java, older
|
|
519
|
+
# pythons), so stdout alone is not a reliable source.
|
|
520
|
+
output = result.stdout.strip() or result.stderr.strip()
|
|
521
|
+
if bool(result) and output:
|
|
522
|
+
version = _extract_version_number(output)
|
|
523
|
+
if version:
|
|
524
|
+
return CommandVersionResult(
|
|
525
|
+
success=True,
|
|
526
|
+
message=f"Version retrieved for '{command}'",
|
|
527
|
+
command_name=command,
|
|
528
|
+
version=version,
|
|
529
|
+
version_flag=version_flag,
|
|
530
|
+
)
|
|
531
|
+
|
|
532
|
+
return CommandVersionResult(
|
|
533
|
+
success=False,
|
|
534
|
+
message=(
|
|
535
|
+
f"No version number in the output of '{command} {version_flag}'"
|
|
536
|
+
),
|
|
537
|
+
command_name=command,
|
|
538
|
+
version="",
|
|
539
|
+
version_flag=version_flag,
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
return CommandVersionResult(
|
|
543
|
+
success=False,
|
|
544
|
+
message=f"No version output from '{command} {version_flag}'",
|
|
545
|
+
command_name=command,
|
|
546
|
+
version="",
|
|
547
|
+
version_flag=version_flag,
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
except (CommandServiceError, OSError, TypeError, ValueError) as e:
|
|
551
|
+
# Log but don't raise - this is a helper method
|
|
552
|
+
self.logger.warning(f"Error getting command version: {command}, Error: {e}")
|
|
553
|
+
return CommandVersionResult(
|
|
554
|
+
success=False,
|
|
555
|
+
error=str(e),
|
|
556
|
+
command_name=command,
|
|
557
|
+
version="",
|
|
558
|
+
version_flag=version_flag,
|
|
559
|
+
)
|
|
560
|
+
|
|
561
|
+
# ///////////////////////////////////////////////////////////////
|
|
562
|
+
# PRIVATE VALIDATION HELPERS
|
|
563
|
+
# ///////////////////////////////////////////////////////////////
|
|
564
|
+
|
|
565
|
+
def _validate_init_parameters(
|
|
566
|
+
self, timeout: int, max_retries: int, retry_delay: float
|
|
567
|
+
) -> None:
|
|
568
|
+
"""Validate initialization parameters.
|
|
569
|
+
|
|
570
|
+
Args:
|
|
571
|
+
timeout: Command timeout in seconds
|
|
572
|
+
max_retries: Maximum number of retries
|
|
573
|
+
retry_delay: Delay between retries
|
|
574
|
+
|
|
575
|
+
Raises:
|
|
576
|
+
CommandUtilityError: If parameters are invalid
|
|
577
|
+
"""
|
|
578
|
+
if timeout <= 0:
|
|
579
|
+
raise CommandUtilityError(
|
|
580
|
+
message=f"Timeout must be positive, got: {timeout}",
|
|
581
|
+
details="Invalid timeout parameter for CLI manager initialization",
|
|
582
|
+
)
|
|
583
|
+
|
|
584
|
+
if max_retries < 0:
|
|
585
|
+
raise CommandUtilityError(
|
|
586
|
+
message=f"Max retries must be non-negative, got: {max_retries}",
|
|
587
|
+
details="Invalid max_retries parameter for CLI manager initialization",
|
|
588
|
+
)
|
|
589
|
+
|
|
590
|
+
if retry_delay < 0:
|
|
591
|
+
raise CommandUtilityError(
|
|
592
|
+
message=f"Retry delay must be non-negative, got: {retry_delay}",
|
|
593
|
+
details="Invalid retry_delay parameter for CLI manager initialization",
|
|
594
|
+
)
|
|
595
|
+
|
|
596
|
+
def _validate_command_input(self, command: str | list[str]) -> None:
|
|
597
|
+
"""Validate command input.
|
|
598
|
+
|
|
599
|
+
Args:
|
|
600
|
+
command: Command to validate
|
|
601
|
+
|
|
602
|
+
Raises:
|
|
603
|
+
CommandUtilityError: If command is invalid
|
|
604
|
+
"""
|
|
605
|
+
if not command:
|
|
606
|
+
raise CommandUtilityError(
|
|
607
|
+
message="Command cannot be empty",
|
|
608
|
+
details="Empty command provided for execution",
|
|
609
|
+
)
|
|
610
|
+
|
|
611
|
+
def _validate_command_security(self, command: list[str]) -> None:
|
|
612
|
+
"""Validate command security using SecurityValidator.
|
|
613
|
+
|
|
614
|
+
Args:
|
|
615
|
+
command: Command to validate
|
|
616
|
+
|
|
617
|
+
Raises:
|
|
618
|
+
SecurityServiceError: If security validation fails
|
|
619
|
+
"""
|
|
620
|
+
try:
|
|
621
|
+
from .security_validator_service import SecurityValidatorService
|
|
622
|
+
|
|
623
|
+
validator = SecurityValidatorService()
|
|
624
|
+
validation_result = validator.validate_command(command)
|
|
625
|
+
if not validation_result.is_valid:
|
|
626
|
+
raise SecurityServiceError(
|
|
627
|
+
message=(
|
|
628
|
+
"Security validation failed: "
|
|
629
|
+
f"{validation_result.validation_reason}"
|
|
630
|
+
),
|
|
631
|
+
details=(
|
|
632
|
+
f"command={command} | "
|
|
633
|
+
"Command contains potentially dangerous patterns"
|
|
634
|
+
),
|
|
635
|
+
)
|
|
636
|
+
except SecurityServiceError:
|
|
637
|
+
raise
|
|
638
|
+
except ImportError:
|
|
639
|
+
self.logger.warning("Security validator not available, skipping validation")
|
|
640
|
+
except (OSError, TypeError, ValueError) as e:
|
|
641
|
+
raise SecurityServiceError(
|
|
642
|
+
message=f"Security validation failed: {e}",
|
|
643
|
+
details=(
|
|
644
|
+
f"command={command} | "
|
|
645
|
+
"Command contains potentially dangerous patterns"
|
|
646
|
+
),
|
|
647
|
+
) from e
|