mycroforge/MycroForge.CLI/Bash.cs
2024-04-22 20:25:20 +02:00

47 lines
1.4 KiB
C#

using System.Diagnostics;
namespace MycroForge.CLI;
public static class Bash
{
public static async Task ExecuteAsync(params string[] script)
{
var info = new ProcessStartInfo
{
FileName = "bash",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
using var process = Process.Start(info);
if (process is null)
throw new NullReferenceException("Could not initialize bash process.");
process.OutputDataReceived += (sender, args) => { Console.WriteLine(args.Data); };
process.BeginOutputReadLine();
process.ErrorDataReceived += (sender, args) =>
{
// Only print error data when it's not empty to prevent noise in the shell
if (!string.IsNullOrEmpty(args.Data))
Console.WriteLine(args.Data);
};
process.BeginErrorReadLine();
await using var input = process.StandardInput;
foreach (var line in script)
await input.WriteLineAsync(line);
await input.FlushAsync();
input.Close();
await process.WaitForExitAsync();
if (process.ExitCode != 0)
Console.WriteLine($"Process exited with status code {process.ExitCode}.");
}
}