Execute command with comprehensive error handling
(cmd: str, cwd: Optional[str] = None, timeout: int = 300,
capture_output: bool = True, check: bool = True)
| 146 | logger = BuildLogger() |
| 147 | |
| 148 | def run_command(cmd: str, cwd: Optional[str] = None, timeout: int = 300, |
| 149 | capture_output: bool = True, check: bool = True) -> subprocess.CompletedProcess: |
| 150 | """Execute command with comprehensive error handling""" |
| 151 | logger.info(f"Executing: {cmd}") |
| 152 | if cwd: |
| 153 | logger.info(f"Working directory: {cwd}") |
| 154 | |
| 155 | try: |
| 156 | result = subprocess.run( |
| 157 | cmd, shell=True, cwd=cwd, capture_output=capture_output, |
| 158 | text=True, timeout=timeout, encoding='utf-8', errors='replace' |
| 159 | ) |
| 160 | |
| 161 | if result.stdout and result.stdout.strip(): |
| 162 | clean_stdout = clean_text(result.stdout.strip()) |
| 163 | logger.info(f"Output: {clean_stdout}") |
| 164 | |
| 165 | if result.stderr and result.stderr.strip(): |
| 166 | clean_stderr = clean_text(result.stderr.strip()) |
| 167 | logger.warning(f"Stderr: {clean_stderr}") |
| 168 | |
| 169 | if check and result.returncode != 0: |
| 170 | error_msg = f"Command failed (code {result.returncode}): {cmd}" |
| 171 | if result.stderr: |
| 172 | error_msg += f"\nError: {result.stderr}" |
| 173 | raise BuildError(error_msg) |
| 174 | |
| 175 | logger.success(f"Command completed (code: {result.returncode})") |
| 176 | return result |
| 177 | |
| 178 | except subprocess.TimeoutExpired as e: |
| 179 | error_msg = f"Command timed out after {timeout}s: {cmd}" |
| 180 | logger.error(error_msg) |
| 181 | raise BuildError(error_msg) from e |
| 182 | |
| 183 | except Exception as e: |
| 184 | error_msg = f"Command execution failed: {cmd} - {str(e)}" |
| 185 | logger.error(error_msg) |
| 186 | if check: |
| 187 | raise BuildError(error_msg) from e |
| 188 | return subprocess.CompletedProcess(cmd, 1, "", str(e)) |
| 189 | |
| 190 | class BuildEnvironment: |
| 191 | """Build environment management and validation""" |
no test coverage detected