|
| 1 | +from __future__ import annotations |
1 | 2 |
|
2 | 3 | import glob |
3 | 4 | import os |
4 | 5 | import shutil |
5 | 6 | import subprocess |
6 | 7 | import sys |
7 | 8 |
|
8 | | -def cleanup(out): |
9 | | - ret = '' |
10 | | - for s in out.decode('utf-8').split('\n'): |
11 | | - if len(s) > 1 and s[0] == '#': |
| 9 | + |
| 10 | +def cleanup(out: str) -> str: |
| 11 | + parts = [] |
| 12 | + for line in out.decode('utf-8').splitlines(): |
| 13 | + if len(line) > 1 and line[0] == '#': |
12 | 14 | continue |
13 | | - s = "".join(s.split()) |
14 | | - ret = ret + s |
15 | | - return ret |
| 15 | + parts.append("".join(line.split())) |
| 16 | + return "".join(parts) |
16 | 17 |
|
17 | 18 |
|
18 | 19 | # Check for required compilers and exit if any are missing |
@@ -93,15 +94,23 @@ def cleanup(out): |
93 | 94 | ] |
94 | 95 |
|
95 | 96 |
|
96 | | -def run(compiler_executable, compiler_args): |
97 | | - """Execute a compiler command and capture its output.""" |
| 97 | +def run(compiler_executable: str, compiler_args: list[str]) -> tuple[int, str, str]: |
| 98 | + """Execute a compiler command and capture its exit code, stdout, and stderr.""" |
98 | 99 | compiler_cmd = [compiler_executable] |
99 | 100 | compiler_cmd.extend(compiler_args) |
100 | | - p = subprocess.Popen(compiler_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
101 | | - comm = p.communicate() |
102 | | - exit_code = p.returncode |
103 | | - output = cleanup(comm[0]) |
104 | | - error = comm[0].decode('utf-8').strip() |
| 101 | + |
| 102 | + try: |
| 103 | + with subprocess.Popen(compiler_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as process: |
| 104 | + stdout, stderr = process.communicate() |
| 105 | + exit_code = process.returncode |
| 106 | + except FileNotFoundError as e: |
| 107 | + # Compiler not found |
| 108 | + return (127, "", f"{e}") |
| 109 | + except Exception as e: |
| 110 | + return (1, "", f"{e}") |
| 111 | + |
| 112 | + output = cleanup(stdout) # bytes -> str via cleanup |
| 113 | + error = (stderr or b"").decode("utf-8", errors="replace").strip() |
105 | 114 | return (exit_code, output, error) |
106 | 115 |
|
107 | 116 |
|
|
0 commit comments