private static GitResult RunGit(GitInstance git, string arguments, string workingDirectory, int timeout = 30000 /* milliseconds */)
{
// When a git version supports overwriting multi-value config files values this should be uncommented to make
// all tests runnable on systems that have a credential.helper configured.
// arguments = "-c credential.helper=\"store --file=bonobo.randomstring.credentials.txt\" " + arguments;
Console.WriteLine("About to run '{0}' with args '{1}' in '{2}'", git, arguments, workingDirectory);
Debug.WriteLine("About to run '{0}' with args '{1}' in '{2}'", git, arguments, workingDirectory);
// http://stackoverflow.com/a/7608823/551045 and http://stackoverflow.com/a/22956924/551045
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
using (var process = new Process())
{
process.StartInfo.FileName = git.GitExe;
process.StartInfo.WorkingDirectory = workingDirectory;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
process.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(e.Data);
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
if (process.WaitForExit(timeout) &&
outputWaitHandle.WaitOne(timeout) &&
errorWaitHandle.WaitOne(timeout))
{
var strout = output.ToString();
var strerr = error.ToString();
Console.WriteLine("Stdout: {0}", output);
Console.WriteLine("Stderr: {0}", error);
return new GitResult {StdErr = strerr, StdOut = strout, ExitCode = process.ExitCode, Resources = git.Resources};
}
else
{
Assert.Fail(string.Format("Runing command '{0} {1}' timed out! Timeout {2} seconds.", git, arguments, timeout));
return new GitResult() { StdErr = null, StdOut = null, ExitCode = -1 };
}
}
}
}