81 lines
2.5 KiB
C#
81 lines
2.5 KiB
C#
using System.Diagnostics;
|
|
using System.Text;
|
|
using MicroForge.CLI.Exceptions;
|
|
|
|
namespace MicroForge.CLI;
|
|
|
|
public static class Bash
|
|
{
|
|
public static async Task RunAsync(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) => 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}.");
|
|
}
|
|
|
|
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.");
|
|
|
|
await using var input = process.StandardInput;
|
|
foreach (var line in script)
|
|
await input.WriteLineAsync(line);
|
|
|
|
await input.FlushAsync();
|
|
input.Close();
|
|
|
|
var sb = new StringBuilder();
|
|
sb.Append(await process.StandardOutput.ReadToEndAsync());
|
|
sb.Append(await process.StandardError.ReadToEndAsync());
|
|
Console.WriteLine(sb.ToString());
|
|
|
|
await process.WaitForExitAsync();
|
|
|
|
// if (process.ExitCode != 0)
|
|
// throw new BashException($"Process exited with status code {process.ExitCode}.");
|
|
|
|
if (process.ExitCode != 0)
|
|
Console.WriteLine($"Process exited with status code {process.ExitCode}.");
|
|
}
|
|
} |