|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# Copyright 2026 Ague Samuel Amen |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import subprocess |
| 19 | +from pathlib import Path |
| 20 | +from typing import Any, List, Optional |
| 21 | + |
| 22 | +from Core.Locking import BuildContext |
| 23 | +from Core.process_security import hardened_popen_kwargs, secure_command |
| 24 | + |
| 25 | +class BuildService: |
| 26 | + """Business logic for compilation and build orchestration.""" |
| 27 | + |
| 28 | + @staticmethod |
| 29 | + def run_engine_compile( |
| 30 | + *, |
| 31 | + workspace: Path, |
| 32 | + engine_id: str, |
| 33 | + context: BuildContext, |
| 34 | + engine_config: dict[str, Any] | None = None, |
| 35 | + ) -> dict[str, Any]: |
| 36 | + import EngineLoader as engines_loader |
| 37 | + |
| 38 | + entry_path = workspace / Path(context.entry_point) |
| 39 | + if not context.entry_point or not entry_path.is_file(): |
| 40 | + return { |
| 41 | + "success": False, |
| 42 | + "error": f"Entrypoint missing or obsolete: {context.entry_point}", |
| 43 | + } |
| 44 | + |
| 45 | + try: |
| 46 | + engine = engines_loader.create(engine_id) |
| 47 | + except Exception as exc: |
| 48 | + return {"success": False, "error": f"Unable to load engine '{engine_id}': {exc}"} |
| 49 | + |
| 50 | + try: |
| 51 | + setattr(engine, "_config_overrides", dict(engine_config or {})) |
| 52 | + except Exception: |
| 53 | + pass |
| 54 | + |
| 55 | + try: |
| 56 | + resolved = engine.program_and_args_from_context(context) |
| 57 | + except NotImplementedError: |
| 58 | + return { |
| 59 | + "success": False, |
| 60 | + "error": f"Engine '{engine_id}' does not support BuildContext builds", |
| 61 | + } |
| 62 | + except Exception as exc: |
| 63 | + return { |
| 64 | + "success": False, |
| 65 | + "error": f"Engine '{engine_id}' failed to build command: {exc}", |
| 66 | + } |
| 67 | + if not resolved: |
| 68 | + return {"success": False, "error": f"Engine '{engine_id}' returned no command"} |
| 69 | + |
| 70 | + program, args = resolved |
| 71 | + try: |
| 72 | + safe_program, safe_args, safe_env = secure_command( |
| 73 | + program, |
| 74 | + args, |
| 75 | + {"ARK_WORKSPACE": str(workspace)}, |
| 76 | + ) |
| 77 | + except Exception as exc: |
| 78 | + return {"success": False, "error": f"Unsafe compile command blocked: {exc}"} |
| 79 | + |
| 80 | + try: |
| 81 | + completed = subprocess.run( |
| 82 | + [safe_program] + safe_args, |
| 83 | + cwd=str(workspace), |
| 84 | + env=safe_env, |
| 85 | + capture_output=True, |
| 86 | + text=True, |
| 87 | + **hardened_popen_kwargs(), |
| 88 | + ) |
| 89 | + except Exception as exc: |
| 90 | + return {"success": False, "error": f"Compilation failed to start: {exc}"} |
| 91 | + |
| 92 | + return { |
| 93 | + "success": completed.returncode == 0, |
| 94 | + "return_code": completed.returncode, |
| 95 | + "command": [safe_program] + safe_args, |
| 96 | + "stdout": completed.stdout, |
| 97 | + "stderr": completed.stderr, |
| 98 | + "error": None if completed.returncode == 0 else (completed.stderr.strip() or "Build failed"), |
| 99 | + } |
| 100 | + |
| 101 | + @staticmethod |
| 102 | + def run_bcasl_headless(workspace_dir: str, timeout: float = 0.0) -> int: |
| 103 | + ws_path = Path(workspace_dir) |
| 104 | + if not ws_path.exists() or not ws_path.is_dir(): |
| 105 | + print(f"Invalid workspace: {workspace_dir}") |
| 106 | + return 1 |
| 107 | + |
| 108 | + try: |
| 109 | + from bcasl import run_pre_compile |
| 110 | + except Exception as exc: |
| 111 | + print(f"Unable to load BCASL module: {exc}") |
| 112 | + return 1 |
| 113 | + |
| 114 | + if timeout > 0: |
| 115 | + import os |
| 116 | + os.environ["PYCOMPILER_BCASL_PLUGIN_TIMEOUT"] = str(timeout) |
| 117 | + |
| 118 | + class _CliLogger: |
| 119 | + def append(self, msg: str): |
| 120 | + if not msg.endswith("\n"): |
| 121 | + msg += "\n" |
| 122 | + print(f"[BCASL] {msg}", end="") |
| 123 | + |
| 124 | + class _CliContext: |
| 125 | + def __init__(self, ws_dir): |
| 126 | + self.workspace_dir = ws_dir |
| 127 | + self.log = _CliLogger() |
| 128 | + |
| 129 | + try: |
| 130 | + report = run_pre_compile(_CliContext(str(ws_path))) |
| 131 | + except Exception as exc: |
| 132 | + print(f"Failed to initialize BCASL mode: {exc}") |
| 133 | + return 1 |
| 134 | + |
| 135 | + if report is None: |
| 136 | + print("BCASL execution failed to start.") |
| 137 | + return 1 |
| 138 | + if report.ok: |
| 139 | + print("BCASL run completed successfully.") |
| 140 | + return 0 |
| 141 | + |
| 142 | + # Accessing failures if it's a list-like report |
| 143 | + try: |
| 144 | + failed = sum(1 for item in report if not item.success) |
| 145 | + except Exception: |
| 146 | + failed = 1 |
| 147 | + |
| 148 | + print(f"BCASL run finished with failures: {failed} plugin(s) failed.") |
| 149 | + return 1 |
0 commit comments