wabbajack/Wabbajack.Common/ProcessHelper.cs

114 lines
3.4 KiB
C#
Raw Normal View History

2020-03-19 12:13:57 +00:00
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using AlphaPath = Alphaleonis.Win32.Filesystem.Path;
namespace Wabbajack.Common
{
public class ProcessHelper
{
public enum StreamType
{
Output,
Error,
}
public AbsolutePath Path { get; set; }
public IEnumerable<object> Arguments { get; set; } = Enumerable.Empty<object>();
2020-03-19 12:13:57 +00:00
public bool LogError { get; set; } = true;
public readonly Subject<(StreamType Type, string Line)> Output = new Subject<(StreamType Type, string)>();
public bool ThrowOnNonZeroExitCode { get; set; } = false;
2020-03-19 12:13:57 +00:00
public ProcessHelper()
{
}
public async Task<int> Start()
{
var args = Arguments.Select(arg =>
{
return arg switch
{
AbsolutePath abs => $"\"{abs}\"",
RelativePath rel => $"\"{rel}\"",
_ => arg.ToString()
};
});
2020-03-19 12:13:57 +00:00
var info = new ProcessStartInfo
{
FileName = (string)Path,
Arguments = string.Join(" ", args),
2020-03-19 12:13:57 +00:00
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
var finished = new TaskCompletionSource<int>();
var p = new Process
{
StartInfo = info,
EnableRaisingEvents = true
};
EventHandler Exited = (sender, args) =>
2020-03-19 12:13:57 +00:00
{
finished.SetResult(p.ExitCode);
};
p.Exited += Exited;
2020-03-19 12:13:57 +00:00
DataReceivedEventHandler OutputDataReceived = (sender, data) =>
2020-03-19 12:13:57 +00:00
{
if (string.IsNullOrEmpty(data.Data)) return;
Output.OnNext((StreamType.Output, data.Data));
};
p.OutputDataReceived += OutputDataReceived;
2020-03-19 12:13:57 +00:00
DataReceivedEventHandler ErrorEventHandler = (sender, data) =>
2020-03-19 12:13:57 +00:00
{
if (string.IsNullOrEmpty(data.Data)) return;
Output.OnNext((StreamType.Error, data.Data));
if (LogError)
Utils.Log($"{Path.FileName} ({p.Id}) StdErr: {data.Data}");
2020-03-19 12:13:57 +00:00
};
p.ErrorDataReceived += ErrorEventHandler;
2020-03-19 12:13:57 +00:00
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
ChildProcessTracker.AddProcess(p);
try
{
p.PriorityClass = ProcessPriorityClass.BelowNormal;
}
catch (Exception)
{
// ignored
}
var result = await finished.Task;
p.CancelErrorRead();
p.CancelOutputRead();
p.OutputDataReceived -= OutputDataReceived;
p.ErrorDataReceived -= ErrorEventHandler;
p.Exited -= Exited;
2020-03-19 12:13:57 +00:00
Output.OnCompleted();
if (result != 0 && ThrowOnNonZeroExitCode)
throw new Exception($"Error executing {Path} - Exit Code {result} - Check the log for more information");
2020-03-19 12:13:57 +00:00
return result;
}
}
}