Esempio n. 1
0
        private void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (_isDisposed)
            {
                return;
            }

            if (e.Data == null)
            {
                bool shouldExit;
                lock (_seenNullLock)
                {
                    _seenNullInOutput = true;
                    shouldExit        = _seenNullInError || !_process.StartInfo.RedirectStandardError;
                }
                if (shouldExit)
                {
                    OnExited(_process, EventArgs.Empty);
                }
            }
            else if (!string.IsNullOrEmpty(e.Data))
            {
                foreach (var line in SplitLines(e.Data))
                {
                    if (_output != null)
                    {
                        _output.Add(line);
                    }
                    if (_redirector != null)
                    {
                        _redirector.WriteLine(line);
                    }
                }
            }
        }
 private void WriteOutput(string message)
 {
     if (_output != null)
     {
         _output.WriteLine(message);
     }
 }
Esempio n. 3
0
        private static async Task ContinueCreate(IServiceProvider provider, IPythonInterpreterFactory factory, string path, bool useVEnv, Redirector output)
        {
            path = PathUtils.TrimEndSeparator(path);
            var name = Path.GetFileName(path);
            var dir  = Path.GetDirectoryName(path);

            if (output != null)
            {
                output.WriteLine(Strings.VirtualEnvCreating.FormatUI(path));
                if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForVirtualEnvCreate)
                {
                    output.ShowAndActivate();
                }
                else
                {
                    output.Show();
                }
            }

            // Ensure the target directory exists.
            Directory.CreateDirectory(dir);

            using (var proc = ProcessOutput.Run(
                       factory.Configuration.InterpreterPath,
                       new[] { "-m", useVEnv ? "venv" : "virtualenv", name },
                       dir,
                       UnbufferedEnv,
                       false,
                       output
                       )) {
                var exitCode = await proc;

                if (output != null)
                {
                    if (exitCode == 0)
                    {
                        output.WriteLine(Strings.VirtualEnvCreationSucceeded.FormatUI(path));
                    }
                    else
                    {
                        output.WriteLine(Strings.VirtualEnvCreationFailedExitCode.FormatUI(path, exitCode));
                    }
                    if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForVirtualEnvCreate)
                    {
                        output.ShowAndActivate();
                    }
                    else
                    {
                        output.Show();
                    }
                }

                if (exitCode != 0 || !Directory.Exists(path))
                {
                    throw new InvalidOperationException(Strings.VirtualEnvCreationFailed.FormatUI(path));
                }
            }
        }
 public void OnOutputTextReceived(ICondaEnvironmentManager sender, string text)
 {
     _outputWindow.WriteLine(text.TrimEndNewline());
     _taskHandler?.Progress.Report(new TaskProgressData()
     {
         CanBeCanceled   = false,
         ProgressText    = text,
         PercentComplete = null
     });
 }
Esempio n. 5
0
        public static async Task <bool> Install(
            IServiceProvider provider,
            IPythonInterpreterFactory factory,
            string package,
            IServiceProvider site,
            bool elevate,
            Redirector output = null
            )
        {
            factory.ThrowIfNotRunnable("factory");

            bool isScript;

            if (site != null && GetEasyInstallPath(factory, out isScript) == null)
            {
                await Pip.QueryInstallPip(factory, site, Strings.InstallEasyInstall, elevate, output);
            }

            if (output != null)
            {
                output.WriteLine(Strings.PackageInstalling.FormatUI(package));
                if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation)
                {
                    output.ShowAndActivate();
                }
                else
                {
                    output.Show();
                }
            }

            var exitCode = await ContinueRun(factory, output, elevate, package);

            if (output != null)
            {
                if (exitCode == 0)
                {
                    output.WriteLine(Strings.PackageInstallSucceeded.FormatUI(package));
                }
                else
                {
                    output.WriteLine(Strings.PackageInstallFailedExitCode.FormatUI(package, exitCode));
                }
                if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation)
                {
                    output.ShowAndActivate();
                }
                else
                {
                    output.Show();
                }
            }
            return(exitCode == 0);
        }
Esempio n. 6
0
 private void PipExtensionProvider_OperationStarted(object sender, ValueEventArgs <string> e)
 {
     _outputWindow.WriteLine(e.Value);
     if (_statusBar != null)
     {
         _statusBar.SetText(e.Value);
     }
     if (_pyService.GeneralOptions.ShowOutputWindowForPackageInstallation)
     {
         _outputWindow.ShowAndActivate();
     }
 }
Esempio n. 7
0
        // If the global interpreter comes from the Microsoft Store, and you try to create a venv
        // under %localappdata%, the venv will actually be created under the python install localcache,
        // and a redirect will be put in place that is only understood by the python.exe used to create
        // the venv.
        // Therefore, we have to use the python intepreter to check the real path of the venv,
        // in case it's been redirected.
        private async Task <string> GetRealPath(string path)
        {
            // if we can see the path, it hasn't been redirected, so no need to call into python
            if (Directory.Exists(path) || File.Exists(path))
            {
                return(path);
            }

            // get the redirected path from python
            _redirector.WriteLine(Strings.LookingForRedirectedEnv.FormatUI(path));
            var command = $"import os; print(os.path.realpath(r\"{ path }\"))";
            var output  = ProcessOutput.RunHiddenAndCapture(
                _interpreter.InterpreterExecutablePath,
                new[] { "-c", command }
                );

            try {
                var result = await WaitForOutput(_interpreter.InterpreterExecutablePath, output);

                var redirectedPath = result.StandardOutputLines.FirstOrDefault();
                if (!string.IsNullOrEmpty(redirectedPath) && Directory.Exists(redirectedPath))
                {
                    _redirector.WriteLine(Strings.LookingForRedirectedEnvFound.FormatUI(redirectedPath));
                }
                return(redirectedPath);
            } catch (ProcessException p) {
                _redirector.WriteLine(Strings.LookingForRedirectedEnvFailed.FormatUI(path));
                foreach (var line in p.Result.StandardErrorLines)
                {
                    _redirector.WriteLine(line);
                }
                throw;
            }
        }
Esempio n. 8
0
        public static async Task InstallPip(IServiceProvider provider, IPythonInterpreterFactory factory, bool elevate, Redirector output = null)
        {
            factory.ThrowIfNotRunnable("factory");

            var pipDownloaderPath = PythonToolsInstallPath.GetFile("pip_downloader.py");

            if (output != null)
            {
                output.WriteLine(Strings.PipInstalling);
                if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation)
                {
                    output.ShowAndActivate();
                }
                else
                {
                    output.Show();
                }
            }
            using (var proc = ProcessOutput.Run(
                       factory.Configuration.InterpreterPath,
                       new[] { pipDownloaderPath },
                       factory.Configuration.PrefixPath,
                       null,
                       false,
                       output,
                       elevate: elevate
                       )) {
                var exitCode = await proc;
                if (output != null)
                {
                    if (exitCode == 0)
                    {
                        output.WriteLine(Strings.PipInstallSucceeded);
                    }
                    else
                    {
                        output.WriteLine(Strings.PipInstallFailedExitCode.FormatUI(exitCode));
                    }
                    if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation)
                    {
                        output.ShowAndActivate();
                    }
                    else
                    {
                        output.Show();
                    }
                }
            }
        }
Esempio n. 9
0
        public static async Task <bool> Uninstall(
            IServiceProvider provider,
            IPythonInterpreterFactory factory,
            string package,
            bool elevate,
            Redirector output = null
            )
        {
            factory.ThrowIfNotRunnable("factory");

            if (output != null)
            {
                output.WriteLine(Strings.PackageUninstalling.FormatUI(package));
                if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation)
                {
                    output.ShowAndActivate();
                }
                else
                {
                    output.Show();
                }
            }

            using (var proc = Run(factory, output, elevate, "uninstall", "-y", package)) {
                var exitCode = await proc;

                if (output != null)
                {
                    if (exitCode == 0)
                    {
                        output.WriteLine(Strings.PackageUninstallSucceeded.FormatUI(package));
                    }
                    else
                    {
                        output.WriteLine(Strings.PackageUninstallFailedExitCode.FormatUI(package, exitCode));
                    }
                    if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation)
                    {
                        output.ShowAndActivate();
                    }
                    else
                    {
                        output.Show();
                    }
                }
                return(exitCode == 0);
            }
        }
Esempio n. 10
0
        private async Task CreateVenv()
        {
            RemoveExistingVenv();

            _redirector.WriteLine(Strings.InstallingCookiecutterCreateEnv.FormatUI(_envFolderPath));
            var output = ProcessOutput.Run(
                _interpreter.InterpreterExecutablePath,
                new[] { "-m", "venv", _envFolderPath },
                null,
                null,
                false,
                _redirector
                );

            await WaitForOutput(_interpreter.InterpreterExecutablePath, output);
        }
 private void WriteOutput(string resourceKey, params object[] args)
 {
     if (_output != null)
     {
         _output.WriteLine(SR.GetString(resourceKey, args));
     }
 }
Esempio n. 12
0
        private async Task <bool> DownloadTypings(IEnumerable <string> packages, Redirector redirector)
        {
            if (!packages.Any())
            {
                return(true);
            }

            string tsdPath = await EnsureTsdInstalled();

            if (string.IsNullOrEmpty(tsdPath))
            {
                if (redirector != null)
                {
                    redirector.WriteErrorLine(SR.GetString(SR.TsdNotInstalledError));
                }
                return(false);
            }

            using (var process = ProcessOutput.Run(
                       tsdPath,
                       TsdInstallArguments(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 tsd");
                    }
                    return(false);
                }
                var i = await process;
                if (i == 0)
                {
                    if (redirector != null)
                    {
                        redirector.WriteLine(SR.GetString(SR.TsdInstallCompleted));
                    }
                    return(true);
                }
                else
                {
                    process.Kill();
                    if (redirector != null)
                    {
                        redirector.WriteErrorLine(SR.GetString(SR.TsdInstallErrorOccurred));
                    }
                    return(false);
                }
            }
        }
Esempio n. 13
0
        private static async Task <bool> CompileAsync(string arguments, string workingDir, Redirector redirector)
        {
            Debug.Assert(!string.IsNullOrEmpty(arguments), $"{nameof(arguments)} should not be empty.");

            var pathToTsc = Path.Combine(TypeScriptCompilerLocator.GetDefaultVersion(), CompilerExe);

            redirector?.WriteLine($"=== {Resources.TscBuildStarted}: {pathToTsc} {arguments} ===");

            using (var process = ProcessOutput.Run(
                       pathToTsc,
                       new[] { arguments },
                       workingDir,
                       env: null,
                       visible: false,
                       redirector: redirector,
                       quoteArgs: false,
                       outputEncoding: Encoding.UTF8))
            {
                var whnd = process.WaitHandle;
                if (whnd == null)
                {
                    // Process failed to start, and any exception message has
                    // already been sent through the redirector
                    redirector.WriteErrorLine(string.Format(Resources.TscBuildError, pathToTsc));
                    return(false);
                }
                else
                {
                    var finished = await Task.Run(() => whnd.WaitOne());

                    if (finished)
                    {
                        Debug.Assert(process.ExitCode.HasValue, "tsc.exe process has not really exited");
                        // there seems to be a case when we're signalled as completed, but the
                        // process hasn't actually exited
                        process.Wait();

                        redirector.WriteErrorLine($"==== {Resources.TscBuildCompleted} ====");

                        return(process.ExitCode == 0);
                    }
                    else
                    {
                        process.Kill();
                        redirector.WriteErrorLine($"==== {Resources.TscBuildCanceled} ====");

                        return(false);
                    }
                }
            }
        }
Esempio n. 14
0
        private async Task <bool> ExecuteTypingsTool(IEnumerable <string> arguments, Redirector redirector)
        {
            string typingsTool = await EnsureTypingsToolInstalled(redirector);

            if (string.IsNullOrEmpty(typingsTool))
            {
                redirector?.WriteErrorLine(Resources.TypingsToolNotInstalledError);
                return(false);
            }

            using (var process = ProcessOutput.Run(
                       typingsTool,
                       arguments,
                       _pathToRootProjectDirectory,
                       null,
                       false,
                       redirector,
                       quoteArgs: true,
                       outputEncoding: Encoding.UTF8,
                       errorEncoding: Encoding.UTF8)) {
                if (!process.IsStarted)
                {
                    // Process failed to start, and any exception message has
                    // already been sent through the redirector
                    redirector?.WriteErrorLine(Resources.TypingsToolCouldNotStart);
                    return(false);
                }
                var i = await process;
                if (i == 0)
                {
                    redirector?.WriteLine(Resources.TypingsToolTypingsInstallCompleted);
                    return(true);
                }
                else
                {
                    process.Kill();
                    redirector?.WriteErrorLine(Resources.TypingsToolTypingsInstallErrorOccurred);
                    return(false);
                }
            }
        }
Esempio n. 15
0
        private async Task ReanalyzeWorkspaceHelperAsync(IPythonInterpreterFactory factory, Redirector log)
        {
            _site.MustBeCalledFromUIThread();

            try {
                if (!_recreatingAnalyzer.Wait(0))
                {
                    // Someone else is recreating, so wait for them to finish and return
                    log?.WriteLine("Waiting for existing call");
                    await _recreatingAnalyzer.WaitAsync();

                    try {
                        log?.WriteLine("Existing call complete");
                    } catch {
                        _recreatingAnalyzer.Release();
                        throw;
                    }
                    if (_analyzer?.InterpreterFactory == factory)
                    {
                        _recreatingAnalyzer.Release();
                        return;
                    }
                }
            } catch (ObjectDisposedException) {
                return;
            }

            IVsStatusbar statusBar           = null;
            bool         statusBarConfigured = false;

            try {
                if ((statusBar = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar) != null)
                {
                    statusBar.SetText(Strings.AnalyzingProject);
                    try {
                        object index = (short)0;
                        statusBar.Animation(1, ref index);
                    } catch (ArgumentNullException) {
                        // Issue in status bar implementation
                        // https://github.com/Microsoft/PTVS/issues/3064
                        // Silently suppress since animation is not critical.
                    }
                    statusBar.FreezeOutput(1);
                    statusBarConfigured = true;
                }

                var oldWatcher = _workspaceFileWatcher;
                _workspaceFileWatcher = new FileWatcher(_pythonWorkspace.Location)
                {
                    EnableRaisingEvents   = true,
                    IncludeSubdirectories = true,
                    NotifyFilter          = NotifyFilters.FileName | NotifyFilters.LastWrite
                };
                _workspaceFileWatcher.Changed += OnWorkspaceFileChanged;
                _workspaceFileWatcher.Deleted += OnWorkspaceFileDeleted;
                oldWatcher?.Dispose();

                log?.WriteLine("Creating new workspace analyzer");
                var analyzer = await CreateAnalyzerAsync(factory, _pythonWorkspace.Location);

                Debug.Assert(analyzer != null);
                log?.WriteLine($"Created workspace analyzer {analyzer}");

                WorkspaceAnalyzerChanging?.Invoke(this, new AnalyzerChangingEventArgs(_analyzer, analyzer));

                var oldAnalyzer = Interlocked.Exchange(ref _analyzer, analyzer);

                if (oldAnalyzer != null)
                {
                    if (analyzer != null)
                    {
                        int beforeCount = analyzer.Files.Count();
                        log?.WriteLine($"Transferring from old analyzer {oldAnalyzer}, which has {oldAnalyzer.Files.Count()} files");
                        await analyzer.TransferFromOldAnalyzer(oldAnalyzer);

                        log?.WriteLine($"Tranferred {analyzer.Files.Count() - beforeCount} files");
                        log?.WriteLine($"Old analyzer now has {oldAnalyzer.Files.Count()} files");
                    }
                    if (oldAnalyzer.RemoveUser())
                    {
                        log?.WriteLine("Disposing old analyzer");
                        oldAnalyzer.Dispose();
                    }
                }

                var files          = new List <string>();
                var pythonServices = _site.GetPythonToolsService();
                foreach (var existing in pythonServices.GetActiveSharedAnalyzers().Select(kv => kv.Value).Where(v => !v.IsDisposed))
                {
                    foreach (var kv in existing.LoadedFiles)
                    {
                        files.Add(kv.Key);
                        log?.WriteLine($"Unloading {kv.Key} from default analyzer");
                        foreach (var b in (kv.Value.TryGetBufferParser()?.AllBuffers).MaybeEnumerate())
                        {
                            PythonTextBufferInfo.MarkForReplacement(b);
                        }
                        try {
                            await existing.UnloadFileAsync(kv.Value);
                        } catch (ObjectDisposedException) {
                            break;
                        }
                    }
                }

                if (analyzer != null)
                {
                    // Set search paths first, as it will save full reanalysis later
                    log?.WriteLine("Setting search paths");
                    await analyzer.SetSearchPathsAsync(_pythonWorkspace.GetAbsoluteSearchPaths());

                    // Add all our files into our analyzer
                    log?.WriteLine($"Adding {files.Count} files");
                    await analyzer.AnalyzeFileAsync(files.ToArray());
                }

                WorkspaceAnalyzerChanged?.Invoke(this, EventArgs.Empty);
            } catch (ObjectDisposedException) {
                // Raced with disposal
            } catch (Exception ex) {
                log?.WriteErrorLine(ex.ToString());
                throw;
            } finally {
                try {
                    if (statusBar != null && statusBarConfigured)
                    {
                        statusBar.FreezeOutput(0);
                        object index = (short)0;
                        statusBar.Animation(0, ref index);
                        statusBar.Clear();
                    }
                } finally {
                    try {
                        _recreatingAnalyzer.Release();
                    } catch (ObjectDisposedException) {
                    }
                }
            }
        }
Esempio n. 16
0
        public Task DeleteTemplateAsync(TemplateViewModel template) {
            try {
                string remote = template.RemoteUrl;

                _outputWindow.WriteLine(string.Format(CultureInfo.CurrentUICulture, Strings.DeletingTemplateStarted, template.ClonedPath));

                ShellUtils.DeleteDirectory(template.ClonedPath);

                _outputWindow.WriteLine(string.Empty);
                _outputWindow.WriteLine(string.Format(CultureInfo.CurrentUICulture, Strings.DeletingTemplateSuccess, template.ClonedPath));
                _outputWindow.ShowAndActivate();

                if (!string.IsNullOrEmpty(remote)) {
                    var t = Installed.Templates.SingleOrDefault(current => (current as TemplateViewModel)?.RemoteUrl == remote) as TemplateViewModel;
                    if (t != null) {
                        Installed.Templates.Remove(t);
                    }

                    t = Recommended.Templates.SingleOrDefault(current => (current as TemplateViewModel)?.RemoteUrl == remote) as TemplateViewModel;
                    if (t != null) {
                        t.ClonedPath = string.Empty;
                    }

                    t = GitHub.Templates.SingleOrDefault(current => (current as TemplateViewModel)?.RemoteUrl == remote) as TemplateViewModel;
                    if (t != null) {
                        t.ClonedPath = string.Empty;
                    }
                } else {
                    if (Installed.Templates.Contains(template)) {
                        Installed.Templates.Remove(template);
                    }
                }
            } catch (Exception ex) when (!ex.IsCriticalException()) {
                _outputWindow.WriteErrorLine(ex.Message);

                _outputWindow.WriteLine(string.Empty);
                _outputWindow.WriteLine(string.Format(CultureInfo.CurrentUICulture, Strings.DeletingTemplateFailed, template.ClonedPath));
                _outputWindow.ShowAndActivate();
            }

            return Task.CompletedTask;
        }
Esempio n. 17
0
 public void OnOutputTextReceived(ICondaEnvironmentManager sender, string text)
 {
     _window.WriteLine(text.TrimEndNewline());
 }
Esempio n. 18
0
        public static async Task <bool> Install(
            IServiceProvider provider,
            IPythonInterpreterFactory factory,
            string package,
            IServiceProvider site,
            bool elevate,
            Redirector output = null
            )
        {
            factory.ThrowIfNotRunnable("factory");

            if (!(await factory.FindModulesAsync("pip")).Any())
            {
                if (site != null)
                {
                    try {
                        await QueryInstallPip(factory, site, Strings.InstallPip, elevate, output);
                    } catch (OperationCanceledException) {
                        return(false);
                    }
                }
                else
                {
                    await InstallPip(provider, factory, elevate, output);
                }
            }

            if (output != null)
            {
                output.WriteLine(Strings.PackageInstalling.FormatUI(package));
                if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation)
                {
                    output.ShowAndActivate();
                }
                else
                {
                    output.Show();
                }
            }

            using (var proc = Run(factory, output, elevate, "install", GetInsecureArg(factory, output), package)) {
                var exitCode = await proc;

                if (output != null)
                {
                    if (exitCode == 0)
                    {
                        output.WriteLine(Strings.PackageInstallSucceeded.FormatUI(package));
                    }
                    else
                    {
                        output.WriteLine(Strings.PackageInstallFailedExitCode.FormatUI(package, exitCode));
                    }
                    if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation)
                    {
                        output.ShowAndActivate();
                    }
                    else
                    {
                        output.Show();
                    }
                }
                return(exitCode == 0);
            }
        }
Esempio n. 19
0
        public static async Task <bool> Install(
            IServiceProvider provider,
            IPythonInterpreterFactory factory,
            IInterpreterOptionsService service,
            string package,
            Redirector output = null
            )
        {
            factory.ThrowIfNotRunnable("factory");

            var condaFactory = await TryGetCondaFactoryAsync(factory, service);;

            if (condaFactory == null)
            {
                throw new InvalidOperationException("Cannot find conda");
            }
            condaFactory.ThrowIfNotRunnable();

            if (output != null)
            {
                output.WriteLine(SR.GetString(SR.PackageInstalling, package));
                if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation)
                {
                    output.ShowAndActivate();
                }
                else
                {
                    output.Show();
                }
            }

            using (var proc = ProcessOutput.Run(
                       condaFactory.Configuration.InterpreterPath,
                       new[] { "-m", "conda", "install", "--yes", "-n", factory.Configuration.PrefixPath, package },
                       factory.Configuration.PrefixPath,
                       UnbufferedEnv,
                       false,
                       output
                       )) {
                var exitCode = await proc;
                if (output != null)
                {
                    if (exitCode == 0)
                    {
                        output.WriteLine(SR.GetString(SR.PackageInstallSucceeded, package));
                    }
                    else
                    {
                        output.WriteLine(SR.GetString(SR.PackageInstallFailedExitCode, package, exitCode));
                    }
                    if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation)
                    {
                        output.ShowAndActivate();
                    }
                    else
                    {
                        output.Show();
                    }
                }
                return(exitCode == 0);
            }
        }
Esempio n. 20
0
 public void OnOutputTextReceived(string text)
 {
     _outputWindow.WriteLine(text.TrimEndNewline());
 }
Esempio n. 21
0
        public async Task DeleteTemplateAsync(TemplateViewModel template)
        {
            try {
                string remote = template.RemoteUrl;

                _outputWindow.ShowAndActivate();
                _outputWindow.WriteLine(String.Empty);
                _outputWindow.WriteLine(Strings.DeletingTemplateStarted.FormatUI(template.ClonedPath));

                await _installedSource.DeleteTemplateAsync(template.ClonedPath);

                _outputWindow.WriteLine(Strings.DeletingTemplateSuccess.FormatUI(template.ClonedPath));

                ReportTemplateEvent(CookiecutterTelemetry.TelemetryArea.Template, CookiecutterTelemetry.TemplateEvents.Delete, template);

                if (!string.IsNullOrEmpty(remote))
                {
                    var t = Installed.Templates.SingleOrDefault(current => (current as TemplateViewModel)?.RemoteUrl == remote) as TemplateViewModel;
                    if (t != null)
                    {
                        Installed.Templates.Remove(t);
                    }

                    t = Recommended.Templates.SingleOrDefault(current => (current as TemplateViewModel)?.RemoteUrl == remote) as TemplateViewModel;
                    if (t != null)
                    {
                        t.ClonedPath = string.Empty;
                    }

                    t = GitHub.Templates.SingleOrDefault(current => (current as TemplateViewModel)?.RemoteUrl == remote) as TemplateViewModel;
                    if (t != null)
                    {
                        t.ClonedPath = string.Empty;
                    }
                }
                else
                {
                    if (Installed.Templates.Contains(template))
                    {
                        Installed.Templates.Remove(template);
                    }
                }
            } catch (Exception ex) when(!ex.IsCriticalException())
            {
                _outputWindow.WriteErrorLine(ex.Message);
                _outputWindow.WriteLine(Strings.DeletingTemplateFailed.FormatUI(template.ClonedPath));
                ReportTemplateEvent(CookiecutterTelemetry.TelemetryArea.Template, CookiecutterTelemetry.TemplateEvents.Delete, template, ex);
            }
        }
Esempio n. 22
0
 private void PipExtensionProvider_OutputTextReceived(object sender, OutputEventArgs e)
 {
     _outputWindow.WriteLine(e.Data.TrimEndNewline());
 }
Esempio n. 23
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,
            IEnumerable <KeyValuePair <string, string> > env,
            Redirector redirector,
            bool quoteArgs          = true,
            bool elevate            = true,
            Encoding outputEncoding = null,
            Encoding errorEncoding  = null
            )
        {
            var psi = new ProcessStartInfo(PythonToolsInstallPath.GetFile("Microsoft.PythonTools.RunElevated.exe", typeof(ProcessOutput).Assembly));

            psi.CreateNoWindow = true;
            psi.WindowStyle    = ProcessWindowStyle.Hidden;

            var utf8 = new UTF8Encoding(false);
            // Send args and env as base64 to avoid newline issues
            string args;

            if (quoteArgs)
            {
                args = string.Join("|", arguments
                                   .Where(a => a != null)
                                   .Select(a => Convert.ToBase64String(utf8.GetBytes(QuoteSingleArgument(a))))
                                   );
            }
            else
            {
                args = string.Join("|", arguments
                                   .Where(a => a != null)
                                   .Select(a => Convert.ToBase64String(utf8.GetBytes(a)))
                                   );
            }

            var fullEnv = env != null?
                          string.Join("|", env.Select(kv => kv.Key + "=" + Convert.ToBase64String(utf8.GetBytes(kv.Value)))) :
                              "";

            TcpListener      listener   = null;
            Task <TcpClient> clientTask = null;

            try {
                listener      = SocketUtils.GetRandomPortListener(IPAddress.Loopback, out int port);
                psi.Arguments = port.ToString();
                clientTask    = listener.AcceptTcpClientAsync();
            } catch (Exception ex) {
                listener?.Stop();
                throw new InvalidOperationException(Strings.UnableToElevate, ex);
            }

            var process = new Process();

            clientTask.ContinueWith(t => {
                listener.Stop();
                TcpClient client;
                try {
                    client = t.Result;
                } catch (AggregateException ae) {
                    try {
                        process.Kill();
                    } catch (InvalidOperationException) {
                    } catch (Win32Exception) {
                    }

                    if (redirector != null)
                    {
                        foreach (var ex in ae.InnerExceptions.DefaultIfEmpty(ae))
                        {
                            using (var reader = new StringReader(ex.ToString())) {
                                for (var line = reader.ReadLine(); line != null; line = reader.ReadLine())
                                {
                                    redirector.WriteErrorLine(line);
                                }
                            }
                        }
                    }
                    return;
                }
                using (var writer = new StreamWriter(client.GetStream(), utf8, 4096, true)) {
                    writer.WriteLine(filename);
                    writer.WriteLine(args);
                    writer.WriteLine(workingDirectory);
                    writer.WriteLine(fullEnv);
                    writer.WriteLine(outputEncoding?.WebName ?? "");
                    writer.WriteLine(errorEncoding?.WebName ?? "");
                }

                if (redirector != null)
                {
                    var reader = new StreamReader(client.GetStream(), utf8, false, 4096, true);
                    Task.Run(() => {
                        try {
                            for (var line = reader.ReadLine(); line != null; line = reader.ReadLine())
                            {
                                if (line.StartsWithOrdinal("OUT:"))
                                {
                                    redirector.WriteLine(line.Substring(4));
                                }
                                else if (line.StartsWithOrdinal("ERR:"))
                                {
                                    redirector.WriteErrorLine(line.Substring(4));
                                }
                                else
                                {
                                    redirector.WriteLine(line);
                                }
                            }
                        } catch (IOException) {
                        } catch (ObjectDisposedException) {
                        }
                    });
                }
            });

            process.StartInfo = psi;

            return(new ProcessOutput(process, redirector));
        }
Esempio n. 24
0
 private void WriteOutput(string message)
 {
     _output?.WriteLine(message);
 }
Esempio n. 25
0
 public void OnOutputTextReceived(IPackageManager sender, string text)
 {
     _outputWindow.WriteLine(text.TrimEndNewline());
 }
Esempio n. 26
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(Path.Combine(Environment.SystemDirectory, "cmd.exe"))
            {
                CreateNoWindow  = true,
                WindowStyle     = ProcessWindowStyle.Hidden,
                UseShellExecute = true,
                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);
        }
Esempio n. 27
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(CultureInfo.InvariantCulture,
                                                               "\r\n===={0}====\r\n\r\n",
                                                               string.Format(CultureInfo.InvariantCulture, Resources.NpmCommandCompletedWithExitCode, process.ExitCode ?? -1)
                                                               ));
                        }
                    }
                    else
                    {
                        process.Kill();
                        if (redirector != null)
                        {
                            redirector.WriteErrorLine(string.Format(CultureInfo.InvariantCulture,
                                                                    "\r\n===={0}====\r\n\r\n",
                                                                    Resources.NpmCommandCancelled));
                        }

                        if (cancellationResetEvent != null)
                        {
                            cancellationResetEvent.Reset();
                        }
                        throw new OperationCanceledException();
                    }
                }
            }
            return(standardOutputLines);
        }
Esempio n. 28
0
 public void OnOutputTextReceived(string text)
 {
     _outputWindow.WriteLine(RemoveLastNewline(text));
 }