Last active
September 4, 2021 09:48
-
-
Save jack4it/3b3171ad8ba21d1437f7dc1d24d9b0bd 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
public static class ShellHelper | |
{ | |
public static Task<int> Bash(this string cmd, ILogger logger) | |
{ | |
var source = new TaskCompletionSource<int>(); | |
var escapedArgs = cmd.Replace("\"", "\\\""); | |
var process = new Process | |
{ | |
StartInfo = new ProcessStartInfo | |
{ | |
FileName = "bash", | |
Arguments = $"-c \"{escapedArgs}\"", | |
RedirectStandardOutput = true, | |
RedirectStandardError = true, | |
UseShellExecute = false, | |
CreateNoWindow = true | |
}, | |
EnableRaisingEvents = true | |
}; | |
process.Exited += (sender, args) => | |
{ | |
logger.LogWarning(process.StandardError.ReadToEnd()); | |
logger.LogInformation(process.StandardOutput.ReadToEnd()); | |
if (process.ExitCode == 0) | |
{ | |
source.SetResult(0); | |
} | |
else | |
{ | |
source.SetException(new Exception($"Command `{cmd}` failed with exit code `{process.ExitCode}`")); | |
} | |
process.Dispose(); | |
}; | |
try | |
{ | |
process.Start(); | |
} | |
catch (Exception e) | |
{ | |
logger.LogError(e, "Command {} failed", cmd); | |
source.SetException(e); | |
} | |
return source.Task; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment