Exemplo n.º 1
0
        public async Task <ExecStatusEventArgs> RunAsync()
        {
            var proc = new Process {
                StartInfo = new ProcessStartInfo {
                    FileName  = Arguments [0],
                    Arguments = string.Join(
                        " ",
                        Arguments.Skip(1).Select(ProcessArguments.Quote)),
                    UseShellExecute  = false,
                    CreateNoWindow   = true,
                    WorkingDirectory = WorkingDirectory
                }
            };

            if (isWindows && Elevated)
            {
                proc.StartInfo.UseShellExecute = true;
                proc.StartInfo.Verb            = "runas";
            }
            else
            {
                proc.StartInfo.RedirectStandardInput  = Flags.HasFlag(RedirectStdin);
                proc.StartInfo.RedirectStandardOutput = Flags.HasFlag(RedirectStdout);
                proc.StartInfo.RedirectStandardError  = Flags.HasFlag(RedirectStderr);
            }

            if (proc.StartInfo.RedirectStandardOutput)
            {
                proc.OutputDataReceived += (sender, e)
                                           => WriteOutput(e.Data, OutputRedirection.StandardOutput);
            }

            if (proc.StartInfo.RedirectStandardError)
            {
                proc.ErrorDataReceived += (sender, e)
                                          => WriteOutput(e.Data, OutputRedirection.StandardError);
            }

            void WriteOutput(string data, TextWriter writer)
            {
                if (string.IsNullOrEmpty(data))
                {
                    return;
                }

                data += Environment.NewLine;

                if (Flags.HasFlag(OutputOnSynchronizationContext) &&
                    SynchronizationContext.Current != null)
                {
                    SynchronizationContext.Current.Post(writer.Write, data);
                }
                else
                {
                    writer.Write(data);
                }
            }

            var eventArgs = new ExecStatusEventArgs(this);

            Monitor?.Invoke(null, eventArgs);
            var exitCode = await ProcessRunner(Arguments, proc).ConfigureAwait(false);

            eventArgs = eventArgs.WithProcessEnded(exitCode);
            Monitor?.Invoke(null, eventArgs);

            if (exitCode != 0)
            {
                throw new ExitException(eventArgs);
            }

            return(eventArgs);
        }
Exemplo n.º 2
0
 internal ExitException(ExecStatusEventArgs @event)
     : base($"{@event.Exec.Arguments [0]} terminated with exit code {@event.ExitCode}")
     => Event = @event;