Last active
October 29, 2018 10:41
-
-
Save flamencist/6dd98dff1a61231890a9ac8c0e4e0b74 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace Bash | |
{ | |
internal class BashExecutor | |
{ | |
public Task<string> ExecuteAsync(string cmd, CancellationToken cancellationToken) | |
{ | |
var tcs = new TaskCompletionSource<string>(); | |
var escapedArgs = cmd.Replace("\"", "\\\""); | |
var process = new Process | |
{ | |
StartInfo = new ProcessStartInfo | |
{ | |
FileName = "/bin/bash", | |
Arguments = $"-c \"{escapedArgs}\"", | |
RedirectStandardOutput = true, | |
RedirectStandardError = true, | |
UseShellExecute = false, | |
CreateNoWindow = true | |
}, | |
EnableRaisingEvents = true | |
}; | |
cancellationToken.Register(() => | |
{ | |
try | |
{ | |
process.Kill(); | |
tcs.TrySetCanceled(); | |
} | |
catch (Exception e) | |
{ | |
tcs.TrySetException(new Exception($"Process crashed {process.ExitCode.ToString()}. Error: {e}")); | |
} | |
}); | |
var started = process.Start(); | |
if (!started) | |
{ | |
throw new InvalidOperationException("Could not start process: " + process); | |
} | |
process.StandardOutput.ReadToEndAsync().ContinueWith(t => | |
{ | |
process.WaitForExit(); | |
if(process.ExitCode == 0) | |
{ | |
tcs.TrySetResult(t.Result); | |
} | |
}, cancellationToken); | |
process.StandardError.ReadToEndAsync().ContinueWith(t => | |
{ | |
process.WaitForExit(); | |
if(process.ExitCode != 0) | |
{ | |
tcs.TrySetException(new Exception($"Process crashed {process.ExitCode.ToString()}. Error: {t.Result}")); | |
} | |
}, cancellationToken); | |
return tcs.Task; | |
} | |
public string Execute(string cmd, TimeSpan timeout) | |
{ | |
try | |
{ | |
var cancellationTokenSource = new CancellationTokenSource(timeout); | |
return ExecuteAsync(cmd, cancellationTokenSource.Token).Result?.TrimEnd('\n'); | |
} | |
catch (AggregateException e) | |
{ | |
if (e.InnerException != null) | |
{ | |
throw e.InnerException; | |
} | |
throw; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment