|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.ComponentModel; |
| 4 | +using System.Diagnostics; |
| 5 | +using System.IO; |
| 6 | +using System.Runtime.InteropServices; |
| 7 | +using System.Threading; |
| 8 | + |
| 9 | +namespace GitTools.Testing.Internal |
| 10 | +{ |
| 11 | + public static class ProcessHelper |
| 12 | + { |
| 13 | + private static readonly object LockObject = new object(); |
| 14 | + |
| 15 | + // http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/f6069441-4ab1-4299-ad6a-b8bb9ed36be3 |
| 16 | + private static Process Start(ProcessStartInfo startInfo) |
| 17 | + { |
| 18 | + Process process; |
| 19 | + |
| 20 | + lock (LockObject) |
| 21 | + { |
| 22 | + using (new ChangeErrorMode(ErrorModes.FailCriticalErrors | ErrorModes.NoGpFaultErrorBox)) |
| 23 | + { |
| 24 | + try |
| 25 | + { |
| 26 | + process = Process.Start(startInfo); |
| 27 | + } |
| 28 | + catch (Win32Exception exception) |
| 29 | + { |
| 30 | + switch ((NativeErrorCode)exception.NativeErrorCode) |
| 31 | + { |
| 32 | + case NativeErrorCode.Success: |
| 33 | + // Success is not a failure. |
| 34 | + break; |
| 35 | + |
| 36 | + case NativeErrorCode.FileNotFound: |
| 37 | + throw new FileNotFoundException($"The executable file '{startInfo.FileName}' could not be found.", |
| 38 | + startInfo.FileName, |
| 39 | + exception); |
| 40 | + |
| 41 | + case NativeErrorCode.PathNotFound: |
| 42 | + throw new DirectoryNotFoundException($"The path to the executable file '{startInfo.FileName}' could not be found.", |
| 43 | + exception); |
| 44 | + } |
| 45 | + |
| 46 | + throw; |
| 47 | + } |
| 48 | + |
| 49 | + try |
| 50 | + { |
| 51 | + if (process != null) |
| 52 | + { |
| 53 | + process.PriorityClass = ProcessPriorityClass.Idle; |
| 54 | + } |
| 55 | + } |
| 56 | + catch |
| 57 | + { |
| 58 | + // NOTE: It seems like in some situations, setting the priority class will throw a Win32Exception |
| 59 | + // with the error code set to "Success", which I think we can safely interpret as a success and |
| 60 | + // not an exception. |
| 61 | + // |
| 62 | + // See: https://travis-ci.org/GitTools/GitVersion/jobs/171288284#L2026 |
| 63 | + // And: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx |
| 64 | + // |
| 65 | + // There's also the case where the process might be killed before we try to adjust its priority |
| 66 | + // class, in which case it will throw an InvalidOperationException. What we ideally should do |
| 67 | + // is start the process in a "suspended" state, adjust the priority class, then resume it, but |
| 68 | + // that's not possible in pure .NET. |
| 69 | + // |
| 70 | + // See: https://travis-ci.org/GitTools/GitVersion/jobs/166709203#L2278 |
| 71 | + // And: http://www.codeproject.com/Articles/230005/Launch-a-process-suspended |
| 72 | + // |
| 73 | + // -- @asbjornu |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return process; |
| 79 | + } |
| 80 | + |
| 81 | + // http://csharptest.net/532/using-processstart-to-capture-console-output/ |
| 82 | + public static int Run(Action<string> output, Action<string> errorOutput, TextReader input, string exe, string args, string workingDirectory, params KeyValuePair<string, string>[] environmentalVariables) |
| 83 | + { |
| 84 | + if (string.IsNullOrEmpty(exe)) |
| 85 | + throw new ArgumentNullException(nameof(exe)); |
| 86 | + if (output == null) |
| 87 | + throw new ArgumentNullException(nameof(output)); |
| 88 | + |
| 89 | + workingDirectory ??= Environment.CurrentDirectory; |
| 90 | + |
| 91 | + var psi = new ProcessStartInfo |
| 92 | + { |
| 93 | + UseShellExecute = false, |
| 94 | + RedirectStandardError = true, |
| 95 | + RedirectStandardOutput = true, |
| 96 | + RedirectStandardInput = true, |
| 97 | + WindowStyle = ProcessWindowStyle.Hidden, |
| 98 | + CreateNoWindow = true, |
| 99 | + ErrorDialog = false, |
| 100 | + WorkingDirectory = workingDirectory, |
| 101 | + FileName = exe, |
| 102 | + Arguments = args |
| 103 | + }; |
| 104 | + foreach (var environmentalVariable in environmentalVariables) |
| 105 | + { |
| 106 | + if (psi.EnvironmentVariables.ContainsKey(environmentalVariable.Key)) |
| 107 | + { |
| 108 | + psi.EnvironmentVariables[environmentalVariable.Key] = environmentalVariable.Value; |
| 109 | + } |
| 110 | + else |
| 111 | + { |
| 112 | + psi.EnvironmentVariables.Add(environmentalVariable.Key, environmentalVariable.Value); |
| 113 | + } |
| 114 | + if (psi.EnvironmentVariables.ContainsKey(environmentalVariable.Key) && environmentalVariable.Value == null) |
| 115 | + { |
| 116 | + psi.EnvironmentVariables.Remove(environmentalVariable.Key); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + using var process = Start(psi); |
| 121 | + using var mreOut = new ManualResetEvent(false); |
| 122 | + using var mreErr = new ManualResetEvent(false); |
| 123 | + process.EnableRaisingEvents = true; |
| 124 | + process.OutputDataReceived += (_, e) => |
| 125 | + { |
| 126 | + // ReSharper disable once AccessToDisposedClosure |
| 127 | + if (e.Data == null) |
| 128 | + mreOut.Set(); |
| 129 | + else |
| 130 | + output(e.Data); |
| 131 | + }; |
| 132 | + process.BeginOutputReadLine(); |
| 133 | + process.ErrorDataReceived += (_, e) => |
| 134 | + { |
| 135 | + // ReSharper disable once AccessToDisposedClosure |
| 136 | + if (e.Data == null) |
| 137 | + mreErr.Set(); |
| 138 | + else |
| 139 | + errorOutput(e.Data); |
| 140 | + }; |
| 141 | + process.BeginErrorReadLine(); |
| 142 | + |
| 143 | + string line; |
| 144 | + while (input != null && null != (line = input.ReadLine())) |
| 145 | + process.StandardInput.WriteLine(line); |
| 146 | + |
| 147 | + process.StandardInput.Close(); |
| 148 | + process.WaitForExit(); |
| 149 | + |
| 150 | + mreOut.WaitOne(); |
| 151 | + mreErr.WaitOne(); |
| 152 | + |
| 153 | + return process.ExitCode; |
| 154 | + } |
| 155 | + |
| 156 | + /// <summary> |
| 157 | + /// System error codes. |
| 158 | + /// See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx |
| 159 | + /// </summary> |
| 160 | + private enum NativeErrorCode |
| 161 | + { |
| 162 | + Success = 0x0, |
| 163 | + FileNotFound = 0x2, |
| 164 | + PathNotFound = 0x3 |
| 165 | + } |
| 166 | + |
| 167 | + [Flags] |
| 168 | + public enum ErrorModes |
| 169 | + { |
| 170 | + Default = 0x0, |
| 171 | + FailCriticalErrors = 0x1, |
| 172 | + NoGpFaultErrorBox = 0x2, |
| 173 | + NoAlignmentFaultExcept = 0x4, |
| 174 | + NoOpenFileErrorBox = 0x8000 |
| 175 | + } |
| 176 | + |
| 177 | + private struct ChangeErrorMode : IDisposable |
| 178 | + { |
| 179 | + private readonly int oldMode; |
| 180 | + |
| 181 | + public ChangeErrorMode(ErrorModes mode) |
| 182 | + { |
| 183 | + try |
| 184 | + { |
| 185 | + oldMode = SetErrorMode((int)mode); |
| 186 | + } |
| 187 | + catch (Exception ex) when (ex is EntryPointNotFoundException || ex is DllNotFoundException) |
| 188 | + { |
| 189 | + oldMode = (int)mode; |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + |
| 194 | + void IDisposable.Dispose() |
| 195 | + { |
| 196 | + try |
| 197 | + { |
| 198 | + SetErrorMode(oldMode); |
| 199 | + } |
| 200 | + catch (Exception ex) when (ex is EntryPointNotFoundException || ex is DllNotFoundException) |
| 201 | + { |
| 202 | + // NOTE: Mono doesn't support DllImport("kernel32.dll") and its SetErrorMode method, obviously. @asbjornu |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + [DllImport("kernel32.dll")] |
| 207 | + private static extern int SetErrorMode(int newMode); |
| 208 | + } |
| 209 | + } |
| 210 | +} |
0 commit comments