Files
aeqw89.tools.Publish/aeqw89.tools.Publish/Shell.cs
T
2026-06-04 16:23:37 +10:00

67 lines
2.6 KiB
C#

using System.Diagnostics;
using System.Text;
using Spectre.Console;
namespace aeqw89.tools.Publish;
internal static class Shell {
internal record ShellResult(string Output, string Error, int ExitCode);
internal record PackageInfo(FileInfo FileInfo) {
byte[]? _inMemory = null;
public long Size() => FileInfo.Length;
public async Task<byte[]> ReadAsync() => _inMemory ??= await File.ReadAllBytesAsync(FileInfo.FullName);
public byte[] Read() => _inMemory ??= File.ReadAllBytes(FileInfo.FullName);
}
internal static class Dotnet {
internal static async Task<Result<PackageInfo, ReadableError>> FindPackage(string dir) {
var package = Directory.GetFiles(dir, "*.nupkg").FirstOrDefault();
if (package == null) return new ReadableError(Exceptions.generic_error.EscapeMarkup());
return new PackageInfo(new FileInfo(package)).Ok();
}
internal static async Task<Result<ShellResult, ReadableError>> Pack(string tempdir, DataReceivedEventHandler? stderr, DataReceivedEventHandler? stdout) {
var p = Process.Start(new ProcessStartInfo() {
FileName = "dotnet",
Arguments = $"pack -o {tempdir}",
WorkingDirectory = Environment.CurrentDirectory,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
});
StringBuilder errorLines = new();
StringBuilder outputLines = new();
CancellationTokenSource cts = new();
p?.ErrorDataReceived += stderr;
p?.ErrorDataReceived += (_, e) => {
cts.Cancel();
errorLines.Append(e.Data);
};
bool success = false;
p?.OutputDataReceived += stdout;
p?.OutputDataReceived += (_, e) => {
if (e.Data?.ToLower().Contains("press any key") == true)
cts.Cancel();
if (e.Data?.ToLower().Contains($"successfully created package '{Path.GetFullPath(tempdir)}") == true) {
success = true;
}
};
p?.BeginErrorReadLine();
p?.BeginOutputReadLine();
try {
await (p?.WaitForExitAsync(cts.Token) ?? Task.CompletedTask);
} catch (TaskCanceledException) {
p?.Kill();
} catch (Exception e) {
return new ReadableError(Exceptions.generic_error.EscapeMarkup(), false);
}
return new ShellResult(outputLines.ToString(), errorLines.ToString(), p!.ExitCode).Ok();
}
}
}