summaryrefslogtreecommitdiff
path: root/src/marlin.agents.shell/CommandRunner.cs
blob: d4fcbb30833b5c053f4ba3095a175e8aef8ac3af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System.Diagnostics;

public static class CommandRunner
{
    public static async Task<int> RunAsync(string command, Action<string> onStdout, Action<string> onStderr)
    {
        var psi = new ProcessStartInfo
        {
            FileName = GetShell(),
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        var process = new Process { StartInfo = psi };
        process.OutputDataReceived += (_, e) => { if (e.Data != null) onStdout(e.Data); };
        process.ErrorDataReceived  += (_, e) => { if (e.Data != null) onStderr(e.Data); };

        process.Start();
        process.BeginOutputReadLine();
        process.BeginErrorReadLine();

        // Write the command to stdin and close it
        await process.StandardInput.WriteLineAsync(command);
        await process.StandardInput.WriteLineAsync("exit $?");  // Exit with the command's exit code
        process.StandardInput.Close();
        
        await process.WaitForExitAsync();
        return process.ExitCode;
    }

    private static string GetShell()
    {
        return OperatingSystem.IsWindows() ? "cmd.exe" : "/bin/bash";
    }
}