Example #1
0
        internal static async Task<IEnumerable<string>> ExecuteNpmCommandAsync(
            Redirector redirector,
            string pathToNpm,
            string executionDirectory,
            string[] arguments,
            ManualResetEvent cancellationResetEvent) {

            IEnumerable<string> standardOutputLines = null;

            using (var process = ProcessOutput.Run(
                pathToNpm,
                arguments,
                executionDirectory,
                null,
                false,
                redirector,
                quoteArgs: false,
                outputEncoding: Encoding.UTF8 // npm uses UTF-8 regardless of locale if its output is redirected
                )) {
                var whnd = process.WaitHandle;
                if (whnd == null) {
                    // Process failed to start, and any exception message has
                    // already been sent through the redirector
                    if (redirector != null) {
                        redirector.WriteErrorLine(Resources.ErrCannotStartNpm);
                    }
                } else {
                    var handles = cancellationResetEvent != null ? new[] { whnd, cancellationResetEvent } : new[] { whnd };
                    var i = await Task.Run(() => WaitHandle.WaitAny(handles));
                    if (i == 0) {
                        Debug.Assert(process.ExitCode.HasValue, "npm process has not really exited");
                        process.Wait();

                        if (process.StandardOutputLines != null) {
                            standardOutputLines = process.StandardOutputLines.ToList();
                        }
                        if (redirector != null) {
                            redirector.WriteLine(string.Format(
                                "\r\n===={0}====\r\n\r\n",
                                string.Format(Resources.NpmCommandCompletedWithExitCode, process.ExitCode ?? -1)
                                ));
                        }
                    } else {
                        process.Kill();
                        if (redirector != null) {
                            redirector.WriteErrorLine(string.Format(
                            "\r\n===={0}====\r\n\r\n",
                            Resources.NpmCommandCancelled));
                        }

                        if (cancellationResetEvent != null) {
                            cancellationResetEvent.Reset();
                        }
                        throw new OperationCanceledException();
                    }
                }
            }
            return standardOutputLines;
        }
Example #2
0
 /// <summary>
 /// Installs virtualenv. If pip is not installed, the returned task will
 /// succeed but error text will be passed to the redirector.
 /// </summary>
 public static Task<bool> Install(IServiceProvider provider, IPythonInterpreterFactory factory, Redirector output = null) {
     bool elevate = provider.GetPythonToolsService().GeneralOptions.ElevatePip;
     if (factory.Configuration.Version < new Version(2, 5)) {
         if (output != null) {
             output.WriteErrorLine("Python versions earlier than 2.5 are not supported by PTVS.");
         }
         throw new OperationCanceledException();
     } else if (factory.Configuration.Version == new Version(2, 5)) {
         return Pip.Install(provider, factory, "https://go.microsoft.com/fwlink/?LinkID=317970", elevate, output);
     } else {
         return Pip.Install(provider, factory, "https://go.microsoft.com/fwlink/?LinkID=317969", elevate, output);
     }
 }
Example #3
0
        private static DateTime?TryGetLastWriteTimeUtc(string path, Redirector output = null)
        {
            try
            {
                return(File.GetLastWriteTimeUtc(path));
            }
            catch (UnauthorizedAccessException ex)
            {
                if (output != null)
                {
                    output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
                    output.WriteErrorLine(ex.ToString());
#endif
                }
            }
            catch (ArgumentException ex)
            {
                if (output != null)
                {
                    output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
                    output.WriteErrorLine(ex.ToString());
#endif
                }
            }
            catch (PathTooLongException ex)
            {
                if (output != null)
                {
                    output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
                    output.WriteErrorLine(ex.ToString());
#endif
                }
            }
            catch (NotSupportedException ex)
            {
                if (output != null)
                {
                    output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
                    output.WriteErrorLine(ex.ToString());
#endif
                }
            }
            return(null);
        }
Example #4
0
        /// <summary>
        /// Runs the file with the provided settings as a user with
        /// administrative permissions. The window is always hidden and output
        /// is provided to the redirector when the process terminates.
        /// </summary>
        /// <param name="filename">Executable file to run.</param>
        /// <param name="arguments">Arguments to pass.</param>
        /// <param name="workingDirectory">Starting directory.</param>
        /// <param name="redirector">
        /// An object to receive redirected output.
        /// </param>
        /// <param name="quoteArgs"></param>
        /// <returns>A <see cref="ProcessOutput"/> object.</returns>
        public static ProcessOutput RunElevated(
            string filename,
            IEnumerable <string> arguments,
            string workingDirectory,
            Redirector redirector,
            bool quoteArgs          = true,
            Encoding outputEncoding = null,
            Encoding errorEncoding  = null
            )
        {
            var outFile = Path.GetTempFileName();
            var errFile = Path.GetTempFileName();
            var psi     = new ProcessStartInfo("cmd.exe")
            {
                WindowStyle     = ProcessWindowStyle.Hidden,
                Verb            = "runas",
                CreateNoWindow  = true,
                UseShellExecute = true,
                Arguments       = string.Format(@"/S /C pushd {0} & ""{1} {2} >>{3} 2>>{4}""",
                                                QuoteSingleArgument(workingDirectory),
                                                QuoteSingleArgument(filename),
                                                GetArguments(arguments, quoteArgs),
                                                QuoteSingleArgument(outFile),
                                                QuoteSingleArgument(errFile))
            };

            var process = new Process
            {
                StartInfo = psi
            };

            var result = new ProcessOutput(process, redirector);

            if (redirector != null)
            {
                result.Exited += (s, e) =>
                {
                    try
                    {
                        try
                        {
                            var lines = File.ReadAllLines(outFile, outputEncoding ?? Encoding.Default);
                            foreach (var line in lines)
                            {
                                redirector.WriteLine(line);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (IsCriticalException(ex))
                            {
                                throw;
                            }
                            redirector.WriteErrorLine("Failed to obtain standard output from elevated process.");
#if DEBUG
                            foreach (var line in SplitLines(ex.ToString()))
                            {
                                redirector.WriteErrorLine(line);
                            }
#else
                            Trace.TraceError("Failed to obtain standard output from elevated process.");
                            Trace.TraceError(ex.ToString());
#endif
                        }
                        try
                        {
                            var lines = File.ReadAllLines(errFile, errorEncoding ?? outputEncoding ?? Encoding.Default);
                            foreach (var line in lines)
                            {
                                redirector.WriteErrorLine(line);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (IsCriticalException(ex))
                            {
                                throw;
                            }
                            redirector.WriteErrorLine("Failed to obtain standard error from elevated process.");
#if DEBUG
                            foreach (var line in SplitLines(ex.ToString()))
                            {
                                redirector.WriteErrorLine(line);
                            }
#else
                            Trace.TraceError("Failed to obtain standard error from elevated process.");
                            Trace.TraceError(ex.ToString());
#endif
                        }
                    }
                    finally
                    {
                        try
                        {
                            File.Delete(outFile);
                        }
                        catch { }
                        try
                        {
                            File.Delete(errFile);
                        }
                        catch { }
                    }
                };
            }
            return(result);
        }
Example #5
0
        private static DateTime? TryGetLastWriteTimeUtc(string path, Redirector output = null) {
            try {
                return File.GetLastWriteTimeUtc(path);
            } catch (UnauthorizedAccessException ex) {
                if (output != null) {
                    output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
                    output.WriteErrorLine(ex.ToString());
#endif
                }
            } catch (ArgumentException ex) {
                if (output != null) {
                    output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
                    output.WriteErrorLine(ex.ToString());
#endif
                }
            } catch (PathTooLongException ex) {
                if (output != null) {
                    output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
                    output.WriteErrorLine(ex.ToString());
#endif
                }
            } catch (NotSupportedException ex) {
                if (output != null) {
                    output.WriteErrorLine(string.Format("Failed to access {0}: {1}", path, ex.Message));
#if DEBUG
                    output.WriteErrorLine(ex.ToString());
#endif
                }
            }
            return null;
        }
Example #6
0
        private ProcessOutput(Process process, Redirector redirector) {
            _arguments = QuoteSingleArgument(process.StartInfo.FileName) + " " + process.StartInfo.Arguments;
            _redirector = redirector;
            if (_redirector == null) {
                _output = new List<string>();
                _error = new List<string>();
            }

            _process = process;
            if (_process.StartInfo.RedirectStandardOutput) {
                _process.OutputDataReceived += OnOutputDataReceived;
            }
            if (_process.StartInfo.RedirectStandardError) {
                _process.ErrorDataReceived += OnErrorDataReceived;
            }

            if (!_process.StartInfo.RedirectStandardOutput && !_process.StartInfo.RedirectStandardError) {
                // If we are receiving output events, we signal that the process
                // has exited when one of them receives null. Otherwise, we have
                // to listen for the Exited event.
                // If we just listen for the Exited event, we may receive it
                // before all the output has arrived.
                _process.Exited += OnExited;
            }
            _process.EnableRaisingEvents = true;

            try {
                _process.Start();
            } catch (Exception ex) {
                if (IsCriticalException(ex)) {
                    throw;
                }
                if (_redirector != null) {
                    foreach (var line in SplitLines(ex.ToString())) {
                        _redirector.WriteErrorLine(line);
                    }
                } else if (_error != null) {
                    _error.AddRange(SplitLines(ex.ToString()));
                }
                _process = null;
            }

            if (_process != null) {
                if (_process.StartInfo.RedirectStandardOutput) {
                    _process.BeginOutputReadLine();
                }
                if (_process.StartInfo.RedirectStandardError) {
                    _process.BeginErrorReadLine();
                }
                
                if (_process.StartInfo.RedirectStandardInput) {
                    // Close standard input so that we don't get stuck trying to read input from the user.
                    try {
                        _process.StandardInput.Close();
                    } catch (InvalidOperationException) {
                        // StandardInput not available
                    }
                }
            }
        }
Example #7
0
        /// <summary>
        /// Runs the file with the provided settings as a user with
        /// administrative permissions. The window is always hidden and output
        /// is provided to the redirector when the process terminates.
        /// </summary>
        /// <param name="filename">Executable file to run.</param>
        /// <param name="arguments">Arguments to pass.</param>
        /// <param name="workingDirectory">Starting directory.</param>
        /// <param name="redirector">
        /// An object to receive redirected output.
        /// </param>
        /// <param name="quoteArgs"></param>
        /// <returns>A <see cref="ProcessOutput"/> object.</returns>
        public static ProcessOutput RunElevated(
            string filename,
            IEnumerable<string> arguments,
            string workingDirectory,
            Redirector redirector,
            bool quoteArgs = true,
            Encoding outputEncoding = null,
            Encoding errorEncoding = null
        ) {
            var outFile = Path.GetTempFileName();
            var errFile = Path.GetTempFileName();
            var psi = new ProcessStartInfo("cmd.exe");
            psi.CreateNoWindow = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.UseShellExecute = true;
            psi.Verb = "runas";

            string args;
            if (quoteArgs) {
                args = string.Join(" ", arguments.Where(a => a != null).Select(QuoteSingleArgument));
            } else {
                args = string.Join(" ", arguments.Where(a => a != null));
            }
            psi.Arguments = string.Format("/S /C \"{0} {1} >>{2} 2>>{3}\"",
                QuoteSingleArgument(filename),
                args,
                QuoteSingleArgument(outFile),
                QuoteSingleArgument(errFile)
            );
            psi.WorkingDirectory = workingDirectory;
            psi.CreateNoWindow = true;
            psi.UseShellExecute = true;

            var process = new Process();
            process.StartInfo = psi;
            var result = new ProcessOutput(process, redirector);
            if (redirector != null) {
                result.Exited += (s, e) => {
                    try {
                        try {
                            var lines = File.ReadAllLines(outFile, outputEncoding ?? Encoding.Default);
                            foreach (var line in lines) {
                                redirector.WriteLine(line);
                            }
                        } catch (Exception ex) {
                            if (IsCriticalException(ex)) {
                                throw;
                            }
                            redirector.WriteErrorLine("Failed to obtain standard output from elevated process.");
#if DEBUG
                            foreach (var line in SplitLines(ex.ToString())) {
                                redirector.WriteErrorLine(line);
                            }
#else
                            Trace.TraceError("Failed to obtain standard output from elevated process.");
                            Trace.TraceError(ex.ToString());
#endif
                        }
                        try {
                            var lines = File.ReadAllLines(errFile, errorEncoding ?? outputEncoding ?? Encoding.Default);
                            foreach (var line in lines) {
                                redirector.WriteErrorLine(line);
                            }
                        } catch (Exception ex) {
                            if (IsCriticalException(ex)) {
                                throw;
                            }
                            redirector.WriteErrorLine("Failed to obtain standard error from elevated process.");
#if DEBUG
                            foreach (var line in SplitLines(ex.ToString())) {
                                redirector.WriteErrorLine(line);
                            }
#else
                            Trace.TraceError("Failed to obtain standard error from elevated process.");
                            Trace.TraceError(ex.ToString());
#endif
                        }
                    } finally {
                        try {
                            File.Delete(outFile);
                        } catch { }
                        try {
                            File.Delete(errFile);
                        } catch { }
                    }
                };
            }
            return result;
        }
        private async Task<bool> DownloadTypings(IEnumerable<string> packages, Redirector redirector) {
            if (!packages.Any()) {
                return true;
            }

            string typingsTool = await EnsureTypingsToolInstalled();
            if (string.IsNullOrEmpty(typingsTool)) {
                if (redirector != null) {
                    redirector.WriteErrorLine(SR.GetString(SR.TypingsToolNotInstalledError));
                }
                return false;
            }

            using (var process = ProcessOutput.Run(
                typingsTool,
                GetTypingsToolInstallArguments(packages),
                _pathToRootProjectDirectory,
                null,
                false,
                redirector,
                quoteArgs: true)) {
                if (!process.IsStarted) {
                    // Process failed to start, and any exception message has
                    // already been sent through the redirector
                    if (redirector != null) {
                        redirector.WriteErrorLine("could not start 'typings'");
                    }
                    return false;
                }
                var i = await process;
                if (i == 0) {
                    if (redirector != null) {
                        redirector.WriteLine(SR.GetString(SR.TypingsToolInstallCompleted));
                    }
                    return true;
                } else {
                    process.Kill();
                    if (redirector != null) {
                        redirector.WriteErrorLine(SR.GetString(SR.TypingsToolInstallErrorOccurred));
                    }
                    return false;
                }
            }
        }
Example #9
0
        private ProcessOutput(Process process, Redirector redirector)
        {
            _arguments  = QuoteSingleArgument(process.StartInfo.FileName) + " " + process.StartInfo.Arguments;
            _redirector = redirector;
            if (_redirector == null)
            {
                _output = new List <string>();
                _error  = new List <string>();
            }

            _process = process;
            if (_process.StartInfo.RedirectStandardOutput)
            {
                _process.OutputDataReceived += OnOutputDataReceived;
            }
            if (_process.StartInfo.RedirectStandardError)
            {
                _process.ErrorDataReceived += OnErrorDataReceived;
            }

            if (!_process.StartInfo.RedirectStandardOutput && !_process.StartInfo.RedirectStandardError)
            {
                // If we are receiving output events, we signal that the process
                // has exited when one of them receives null. Otherwise, we have
                // to listen for the Exited event.
                // If we just listen for the Exited event, we may receive it
                // before all the output has arrived.
                _process.Exited += OnExited;
            }
            _process.EnableRaisingEvents = true;

            try {
                _process.Start();
            } catch (Exception ex) {
                if (IsCriticalException(ex))
                {
                    throw;
                }
                if (_redirector != null)
                {
                    foreach (var line in SplitLines(ex.ToString()))
                    {
                        _redirector.WriteErrorLine(line);
                    }
                }
                else if (_error != null)
                {
                    _error.AddRange(SplitLines(ex.ToString()));
                }
                _process = null;
            }

            if (_process != null)
            {
                if (_process.StartInfo.RedirectStandardOutput)
                {
                    _process.BeginOutputReadLine();
                }
                if (_process.StartInfo.RedirectStandardError)
                {
                    _process.BeginErrorReadLine();
                }

                if (_process.StartInfo.RedirectStandardInput)
                {
                    // Close standard input so that we don't get stuck trying to read input from the user.
                    try {
                        _process.StandardInput.Close();
                    } catch (InvalidOperationException) {
                        // StandardInput not available
                    }
                }
            }
        }
Example #10
0
        /// <summary>
        /// Runs the file with the provided settings as a user with
        /// administrative permissions. The window is always hidden and output
        /// is provided to the redirector when the process terminates.
        /// </summary>
        /// <param name="filename">Executable file to run.</param>
        /// <param name="arguments">Arguments to pass.</param>
        /// <param name="workingDirectory">Starting directory.</param>
        /// <param name="redirector">
        /// An object to receive redirected output.
        /// </param>
        /// <param name="quoteArgs"></param>
        /// <returns>A <see cref="ProcessOutput"/> object.</returns>
        public static ProcessOutput RunElevated(string filename,
                                                IEnumerable <string> arguments,
                                                string workingDirectory,
                                                Redirector redirector,
                                                bool quoteArgs = true)
        {
            var outFile = Path.GetTempFileName();
            var errFile = Path.GetTempFileName();
            var psi     = new ProcessStartInfo("cmd.exe");

            psi.CreateNoWindow  = true;
            psi.WindowStyle     = ProcessWindowStyle.Hidden;
            psi.UseShellExecute = true;
            psi.Verb            = "runas";

            string args;

            if (quoteArgs)
            {
                args = string.Join(" ", arguments.Where(a => a != null).Select(QuoteSingleArgument));
            }
            else
            {
                args = string.Join(" ", arguments.Where(a => a != null));
            }
            psi.Arguments = string.Format("/S /C \"{0} {1} >>{2} 2>>{3}\"",
                                          QuoteSingleArgument(filename),
                                          args,
                                          QuoteSingleArgument(outFile),
                                          QuoteSingleArgument(errFile)
                                          );
            psi.WorkingDirectory = workingDirectory;
            psi.CreateNoWindow   = true;
            psi.UseShellExecute  = true;

            var process = new Process();

            process.StartInfo = psi;
            var result = new ProcessOutput(process, redirector);

            if (redirector != null)
            {
                result.Exited += (s, e) => {
                    try {
                        try {
                            var lines = File.ReadAllLines(outFile);
                            foreach (var line in lines)
                            {
                                redirector.WriteLine(line);
                            }
                        } catch (Exception) {
                            redirector.WriteErrorLine("Failed to obtain standard output from elevated process.");
                        }
                        try {
                            var lines = File.ReadAllLines(errFile);
                            foreach (var line in lines)
                            {
                                redirector.WriteErrorLine(line);
                            }
                        } catch (Exception) {
                            redirector.WriteErrorLine("Failed to obtain standard error from elevated process.");
                        }
                    } finally {
                        try {
                            File.Delete(outFile);
                        } catch { }
                        try {
                            File.Delete(errFile);
                        } catch { }
                    }
                };
            }
            return(result);
        }
Example #11
0
File: Pip.cs Project: omnimark/PTVS
 private static string GetInsecureArg(
     IPythonInterpreterFactory factory,
     Redirector output = null
 ) {
     if (!IsSecureInstall(factory)) {
         // Python 2.5 does not include ssl, and so the --insecure
         // option is required to use pip.
         if (output != null) {
             output.WriteErrorLine("Using '--insecure' option for Python 2.5.");
         }
         return "--insecure";
     }
     return null;
 }