// SPDX-FileCopyrightText: 2026 Progmasoft // SPDX-License-Identifier: MIT using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Progmasoft.Tazel.Driver; /// What a process did: its exit status, and its output and errors together, in the order they came. /// The exit status; -1 when it could not start or ran out of time. /// What it printed. /// Whether it was stopped because it ran out of time. /// Whether it was stopped because the command stopped, such as after another action failed. internal sealed record ProcessResult(int ExitCode, string Output, bool TimedOut = false, bool Canceled = false); /// Starts programs directly, with an argument list and no shell between. internal static class Processes { /// /// Runs in with exactly , and /// keeps what it prints. It is stopped, with what it started, after . /// public static async Task RunAsync( IReadOnlyList command, string directory, IReadOnlyDictionary environment, TimeSpan? timeout, CancellationToken cancel) { ArgumentNullException.ThrowIfNull(command); ArgumentNullException.ThrowIfNull(environment); var start = new ProcessStartInfo(command[0]) { WorkingDirectory = directory, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, UseShellExecute = false, CreateNoWindow = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8, }; AddArguments(start, command); start.Environment.Clear(); foreach (var (name, value) in environment) { start.Environment[name] = value; } var output = new StringBuilder(); using var process = new Process { StartInfo = start }; process.OutputDataReceived += (_, line) => Append(output, line.Data); process.ErrorDataReceived += (_, line) => Append(output, line.Data); try { process.Start(); } catch (Win32Exception error) { return new ProcessResult(-1, $"{command[0]} could not be started: {error.Message}"); } process.StandardInput.Close(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); using var limit = CancellationTokenSource.CreateLinkedTokenSource(cancel); if (timeout is { } span) { limit.CancelAfter(span); } try { await process.WaitForExitAsync(limit.Token).ConfigureAwait(false); } catch (OperationCanceledException) { ProcessTree.Kill(process); await process.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false); var canceled = cancel.IsCancellationRequested; return new ProcessResult(-1, Text(output), TimedOut: !canceled, Canceled: canceled); } // WaitForExitAsync returns once the output has been read to its end as well. return new ProcessResult(process.ExitCode, Text(output)); } /// /// Gives the arguments of . A line for cmd.exe, as /// cmd.exe /d /s /c "line", is passed as written: cmd.exe does not read the escapes other programs read, so /// the line reaches it unchanged. /// public static void AddArguments(ProcessStartInfo start, IReadOnlyList command) { ArgumentNullException.ThrowIfNull(start); ArgumentNullException.ThrowIfNull(command); if (OperatingSystem.IsWindows() && command.Count == 5 && string.Equals(Path.GetFileName(command[0]), "cmd.exe", StringComparison.OrdinalIgnoreCase) && command[1] == "/d" && command[2] == "/s" && command[3] == "/c") { start.Arguments = $"/d /s /c {command[4]}"; return; } for (var i = 1; i < command.Count; i++) { start.ArgumentList.Add(command[i]); } } /// Runs and keeps what it prints apart from its errors. public static async Task<(int ExitCode, string Output, string Errors)> CaptureAsync( IReadOnlyList command, string directory, IReadOnlyDictionary environment, CancellationToken cancel) { ArgumentNullException.ThrowIfNull(command); ArgumentNullException.ThrowIfNull(environment); var start = new ProcessStartInfo(command[0]) { WorkingDirectory = directory, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, UseShellExecute = false, CreateNoWindow = true, }; AddArguments(start, command); start.Environment.Clear(); foreach (var (name, value) in environment) { start.Environment[name] = value; } using var process = new Process { StartInfo = start }; try { process.Start(); } catch (Win32Exception error) { return (-1, "", $"{command[0]} could not be started: {error.Message}"); } process.StandardInput.Close(); var output = process.StandardOutput.ReadToEndAsync(cancel); var errors = process.StandardError.ReadToEndAsync(cancel); await process.WaitForExitAsync(cancel).ConfigureAwait(false); return (process.ExitCode, await output.ConfigureAwait(false), await errors.ConfigureAwait(false)); } /// Runs with the terminal of Tazel, as tazel run does. public static int RunAttached(IReadOnlyList command, string directory, IReadOnlyDictionary environment) { ArgumentNullException.ThrowIfNull(command); ArgumentNullException.ThrowIfNull(environment); var start = new ProcessStartInfo(command[0]) { WorkingDirectory = directory, UseShellExecute = false }; AddArguments(start, command); start.Environment.Clear(); foreach (var (name, value) in environment) { start.Environment[name] = value; } using var process = Process.Start(start) ?? throw new InvalidOperationException($"{command[0]} did not start"); process.WaitForExit(); return process.ExitCode; } /// Tazel's own environment, for what runs as the user would run it. public static Dictionary Inherited() { var environment = new Dictionary(StringComparer.Ordinal); foreach (System.Collections.DictionaryEntry entry in System.Environment.GetEnvironmentVariables()) { if (entry.Key is string name && entry.Value is string value) { environment[name] = value; } } return environment; } /// /// The small environment the actions of a build run with: the programs on PATH find their own files, and nothing /// else of the user's environment changes what they make. /// public static Dictionary ForActions() { var environment = new Dictionary(StringComparer.Ordinal) { ["LC_ALL"] = "C" }; foreach (var name in new[] { "PATH", "TMPDIR", "TMP", "TEMP", "SYSTEMROOT", "SystemRoot", "WINDIR", "HOME", "DEVELOPER_DIR", "SDKROOT", "INCLUDE", "LIB", "LIBPATH" }) { if (System.Environment.GetEnvironmentVariable(name) is { } value) { environment[name] = value; } } if (OperatingSystem.IsMacOS()) { environment["ZERO_AR_DATE"] = "1"; } // Compilers, assemblers and linkers that would stamp the time into an output (GCC's __DATE__, binutils' PE and // COFF headers) take it from here instead, so that the same inputs give the same bytes. A value the user set is // kept: it is how a reproducible release names its own date. environment["SOURCE_DATE_EPOCH"] = System.Environment.GetEnvironmentVariable("SOURCE_DATE_EPOCH") ?? "0"; return environment; } private static void Append(StringBuilder output, string? line) { if (line is null) { return; } lock (output) { output.Append(line).Append('\n'); } } private static string Text(StringBuilder output) { lock (output) { return output.ToString(); } } }