public async Task Create()
 {
     IsWorking = true;
     try {
         var op = new AddVirtualEnvironmentOperation(
             _project,
             VirtualEnvPath,
             BaseInterpreter.Id,
             WillCreateVirtualEnv,
             UseVEnv,
             WillInstallRequirementsTxt,
             _requirementsPath,
             OutputWindowRedirector.GetGeneral(_project.Site)
             );
         await op.Run();
     } catch (OperationCanceledException) {
     } finally {
         IsWorking = false;
         RefreshCanCreateVirtualEnv(VirtualEnvPath);
     }
 }
        public AddCondaEnvironmentOperation(
            IServiceProvider site,
            ICondaEnvironmentManager condaMgr,
            PythonProjectNode project,
            IPythonWorkspaceContext workspace,
            string envNameOrPath,
            string envFilePath,
            List <PackageSpec> packages,
            bool setAsCurrent,
            bool setAsDefault,
            bool viewInEnvWindow
            )
        {
            _site            = site ?? throw new ArgumentNullException(nameof(site));
            _condaMgr        = condaMgr ?? throw new ArgumentNullException(nameof(condaMgr));
            _project         = project;
            _workspace       = workspace;
            _envNameOrPath   = envNameOrPath ?? throw new ArgumentNullException(nameof(envNameOrPath));
            _envFilePath     = envFilePath;
            _packages        = packages ?? throw new ArgumentNullException(nameof(packages));
            _setAsCurrent    = setAsCurrent;
            _setAsDefault    = setAsDefault;
            _viewInEnvWindow = viewInEnvWindow;

            // If passed a path, the actual name reported by conda will the last part
            _actualName = PathUtils.GetFileOrDirectoryName(_envNameOrPath);
            if (_actualName.Length == 0)
            {
                _actualName = _envNameOrPath;
            }

            _outputWindow = OutputWindowRedirector.GetGeneral(_site);
            _statusBar    = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar;
            _showAndActiveOutputWindow = _site.GetPythonToolsService().GeneralOptions.ShowOutputWindowForVirtualEnvCreate;
            _statusCenter    = _site.GetService(typeof(SVsTaskStatusCenterService)) as IVsTaskStatusCenterService;
            _registry        = _site.GetComponentModel().GetService <IInterpreterRegistryService>();
            _options         = _site.GetComponentModel().GetService <IInterpreterOptionsService>();
            _logger          = _site.GetService(typeof(IPythonToolsLogger)) as IPythonToolsLogger;
            _factoryProvider = _site.GetComponentModel().GetService <CondaEnvironmentFactoryProvider>();
        }
예제 #3
0
        private void ShowCookiecutterPage()
        {
            Debug.Assert(_cookiecutterPage == null);

            var outputWindow = OutputWindowRedirector.GetGeneral(this);

            Debug.Assert(outputWindow != null);

            ReportPrereqsEvent(true);

            string feedUrl = CookiecutterPackage.Instance.RecommendedFeed;

            if (string.IsNullOrEmpty(feedUrl))
            {
                feedUrl = UrlConstants.DefaultRecommendedFeed;
            }

            object commonIdeFolderPath;
            var    shell = (IVsShell)GetService(typeof(SVsShell));

            ErrorHandler.ThrowOnFailure(shell.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out commonIdeFolderPath));

            var gitClient           = GitClientProvider.Create(outputWindow, commonIdeFolderPath as string);
            var projectSystemClient = new ProjectSystemClient((EnvDTE80.DTE2)GetService(typeof(EnvDTE.DTE)));

            _cookiecutterPage = new CookiecutterContainerPage(
                this,
                outputWindow,
                CookiecutterTelemetry.Current,
                gitClient,
                new Uri(feedUrl),
                OpenGeneratedFolder,
                projectSystemClient,
                UpdateCommandUI
                );
            _cookiecutterPage.ContextMenuRequested += OnContextMenuRequested;
            _cookiecutterPage.InitializeAsync(CookiecutterPackage.Instance.CheckForTemplateUpdate).HandleAllExceptions(this, GetType()).DoNotWait();

            ((Frame)Content).Content = _cookiecutterPage;
        }
예제 #4
0
        private async void RunInOutput(IPythonProject project, CommandStartInfo startInfo)
        {
            Redirector redirector = OutputWindowRedirector.GetGeneral(project.Site);

            if (startInfo.ErrorRegex != null || startInfo.WarningRegex != null)
            {
                redirector = new TeeRedirector(redirector, new ErrorListRedirector(_project.Site, project as IVsHierarchy, startInfo.WorkingDirectory, _errorListProvider, startInfo.ErrorRegex, startInfo.WarningRegex));
            }
            redirector.ShowAndActivate();

            using (var process = ProcessOutput.Run(
                       startInfo.Filename,
                       new[] { startInfo.Arguments },
                       startInfo.WorkingDirectory,
                       startInfo.EnvironmentVariables,
                       false,
                       redirector,
                       quoteArgs: false
                       )) {
                await process;
            }
        }
예제 #5
0
        private void ShowCookiecutterPage()
        {
            Debug.Assert(_cookiecutterPage == null);

            var outputWindow = OutputWindowRedirector.GetGeneral(this);

            Debug.Assert(outputWindow != null);

            ReportPrereqsEvent(true);

            string feedUrl = CookiecutterPackage.Instance.RecommendedFeed;

            if (string.IsNullOrEmpty(feedUrl))
            {
                feedUrl = UrlConstants.DefaultRecommendedFeed;
            }

            _cookiecutterPage = new CookiecutterContainerPage(outputWindow, CookiecutterTelemetry.Current, new Uri(feedUrl), OpenGeneratedFolder, UpdateCommandUI);
            _cookiecutterPage.ContextMenuRequested += OnContextMenuRequested;
            _cookiecutterPage.InitializeAsync(CookiecutterPackage.Instance.CheckForTemplateUpdate).HandleAllExceptions(this, GetType()).DoNotWait();

            ((Frame)Content).Content = _cookiecutterPage;
        }
예제 #6
0
        public async Task RunAsync()
        {
            var outputWindow = OutputWindowRedirector.GetGeneral(_site);
            var taskHandler  = _statusCenter.PreRegister(
                new TaskHandlerOptions()
            {
                ActionsAfterCompletion = CompletionActions.RetainAndNotifyOnFaulted | CompletionActions.RetainAndNotifyOnRanToCompletion,
                Title = Strings.VirtualEnvStatusCenterCreateTitle.FormatUI(PathUtils.GetFileOrDirectoryName(_virtualEnvPath)),
                DisplayTaskDetails = (t) => { outputWindow.ShowAndActivate(); }
            },
                new TaskProgressData()
            {
                CanBeCanceled   = false,
                ProgressText    = Strings.VirtualEnvStatusCenterCreateProgressPreparing,
                PercentComplete = null,
            }
                );

            var task = CreateVirtualEnvironmentAsync(taskHandler);

            taskHandler?.RegisterTask(task);
            _site.ShowTaskStatusCenter();
        }
예제 #7
0
        public async Task RunAsync()
        {
            var outputWindow = OutputWindowRedirector.GetGeneral(_site);
            var taskHandler  = _statusCenter?.PreRegister(
                new TaskHandlerOptions()
            {
                ActionsAfterCompletion = CompletionActions.RetainAndNotifyOnFaulted | CompletionActions.RetainAndNotifyOnRanToCompletion,
                Title = Strings.InstallPackagesStatusCenterTitle.FormatUI(PathUtils.GetFileOrDirectoryName(_pm.Factory.Configuration.Description)),
                DisplayTaskDetails = (t) => { outputWindow.ShowAndActivate(); }
            },
                new TaskProgressData()
            {
                CanBeCanceled   = false,
                ProgressText    = Strings.InstallPackagesStatusCenterProgressPreparing,
                PercentComplete = null,
            }
                );

            var task = InstallPackagesAsync(taskHandler);

            taskHandler?.RegisterTask(task);
            _site.ShowTaskStatusCenter();
        }
예제 #8
0
        internal static IDictionary <string, TargetResult> BuildTarget(IPythonProject project, string target)
        {
            var config = project.GetMSBuildProjectInstance();

            if (config == null)
            {
                throw new ArgumentException(Strings.ProjectDoesNotSupportedMSBuild, nameof(project));
            }

            IDictionary <string, TargetResult> outputs;

            var logger = new StringLogger();

#if DEBUG
            var loggers = new ILogger[] { new TraceLogger(), logger };
#else
            var loggers = new ILogger[] { logger };
#endif

            if (!config.Build(new[] { target }, loggers, Enumerable.Empty <ForwardingLoggerRecord>(), out outputs))
            {
                var outputWindow = OutputWindowRedirector.Get(
                    project.Site,
                    VSConstants.OutputWindowPaneGuid.BuildOutputPane_guid,
                    "Build"
                    );
                outputWindow.WriteErrorLine(Strings.ErrorBuildingCustomCommand.FormatUI(target));
                foreach (var line in logger.Lines)
                {
                    outputWindow.WriteErrorLine(line.TrimEnd('\r', '\n'));
                }
                throw new InvalidOperationException(Strings.ErrorBuildingCustomCommand.FormatUI(target));
            }

            return(outputs);
        }
예제 #9
0
        /// <summary>
        /// Creates a virtual environment using venv. If venv is not available,
        /// the task will succeed but error text will be passed to the
        /// redirector.
        /// </summary>
        public static Task CreateWithVEnv(
            IServiceProvider provider,
            IPythonInterpreterFactory factory,
            string path
            )
        {
            if (provider == null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            factory.ThrowIfNotRunnable();
            return(ContinueCreate(provider, factory, path, true, OutputWindowRedirector.GetGeneral(provider)));
        }
예제 #10
0
        private async Task ExecuteWorker(PythonProjectNode project)
        {
            _errorListProvider.Tasks.Clear();

            var interpFactory = project.GetInterpreterFactoryOrThrow();
            var startInfo     = GetStartInfo(project);

            var packagesToInstall = new List <string>();

            foreach (var pkg in startInfo.RequiredPackages)
            {
                if (!await Pip.IsInstalled(interpFactory, pkg))
                {
                    packagesToInstall.Add(pkg);
                }
            }

            if (packagesToInstall.Any())
            {
                var installMissingButton = new TaskDialogButton(
                    Strings.CustomCommandPrerequisitesInstallMissing,
                    Strings.CustomCommandPrerequisitesInstallMissingSubtext + "\r\n\r\n" + string.Join("\r\n", packagesToInstall));
                var runAnywayButton = new TaskDialogButton(Strings.CustomCommandPrerequisitesRunAnyway);
                var doNotRunButton  = new TaskDialogButton(Strings.CustomCommandPrerequisitesDoNotRun);

                var taskDialog = new TaskDialog(project.Site)
                {
                    Title             = Strings.ProductTitle,
                    MainInstruction   = Strings.CustomCommandPrerequisitesInstruction,
                    Content           = Strings.CustomCommandPrerequisitesContent.FormatUI(DisplayLabelWithoutAccessKeys),
                    AllowCancellation = true,
                    Buttons           = { installMissingButton, runAnywayButton, doNotRunButton, TaskDialogButton.Cancel }
                };

                var selectedButton = taskDialog.ShowModal();
                if (selectedButton == installMissingButton)
                {
                    await Pip.Install(
                        project.Site,
                        interpFactory,
                        string.Join(" ", packagesToInstall),
                        false,
                        OutputWindowRedirector.GetGeneral(project.Site));
                }
                else if (selectedButton == runAnywayButton)
                {
                }
                else
                {
                    throw new TaskCanceledException();
                }
            }

            if (startInfo.TargetType == CreatePythonCommandItem.TargetTypePip)
            {
                if (startInfo.ExecuteInOutput)
                {
                    await Pip.Install(
                        _project.Site,
                        interpFactory,
                        string.IsNullOrEmpty(startInfo.Arguments)?
                        startInfo.Filename :
                        string.Format("{0} {1}", startInfo.Filename, startInfo.Arguments),
                        project.Site,
                        false,
                        OutputWindowRedirector.GetGeneral(project.Site)
                        );

                    return;
                }

                // Rewrite start info to execute
                startInfo.TargetType = CreatePythonCommandItem.TargetTypeModule;
                startInfo.AddArgumentAtStart(startInfo.Filename);
                startInfo.Filename = "pip";
            }

            if (startInfo.ExecuteInRepl)
            {
                if (await RunInRepl(project, startInfo))
                {
                    return;
                }
            }

            startInfo.AdjustArgumentsForProcessStartInfo(GetInterpreterPath(project, false));

            if (startInfo.ExecuteInOutput)
            {
                RunInOutput(project, startInfo);
            }
            else
            {
                RunInConsole(project, startInfo);
            }
        }
예제 #11
0
        private async Task <bool> RunInRepl(IPythonProject project, CommandStartInfo startInfo)
        {
            var  executeIn = string.IsNullOrEmpty(startInfo.ExecuteIn) ? CreatePythonCommandItem.ExecuteInRepl : startInfo.ExecuteIn;
            bool resetRepl = executeIn.StartsWith("R", StringComparison.InvariantCulture);

            var replTitle = executeIn.Substring(4).TrimStart(' ', ':');

            if (string.IsNullOrEmpty(replTitle))
            {
                replTitle = Strings.CustomCommandReplTitle.FormatUI(DisplayLabelWithoutAccessKeys);
            }
            else
            {
                var match = _customCommandLabelRegex.Match(replTitle);
                if (match.Success)
                {
                    replTitle = LoadResourceFromAssembly(
                        match.Groups["assembly"].Value,
                        match.Groups["namespace"].Value,
                        match.Groups["key"].Value
                        );
                }
            }

            replTitle = PerformSubstitutions(project, replTitle);

            var replWindowId = PythonReplEvaluatorProvider.GetTemporaryId(
                ReplId + executeIn.Substring(4),
                _project.GetInterpreterFactory().Configuration
                );

            var model        = _project.Site.GetComponentModel();
            var replProvider = model.GetService <InteractiveWindowProvider>();

            if (replProvider == null)
            {
                return(false);
            }

            bool created;
            var  replWindow = replProvider.OpenOrCreateTemporary(replWindowId, replTitle, out created);

            // TODO: Find alternative way of closing repl window on Dev15
            var replFrame = (replWindow as ToolWindowPane)?.Frame as IVsWindowFrame;

            var interactive = replWindow.InteractiveWindow;
            var pyEvaluator = replWindow.InteractiveWindow.Evaluator as PythonInteractiveEvaluator;

            if (pyEvaluator == null)
            {
                if (created && replFrame != null)
                {
                    // We created the window, but it isn't valid, so we'll close
                    // it again immediately.
                    replFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
                }

                return(false);
            }

            if (pyEvaluator.IsExecuting)
            {
                throw new InvalidOperationException(Strings.ErrorCommandAlreadyRunning);
            }

            pyEvaluator.ProjectMoniker = _project.GetMkDocument();
            pyEvaluator.Configuration  = new LaunchConfiguration(startInfo.Interpreter)
            {
                WorkingDirectory = startInfo.WorkingDirectory,
                Environment      = startInfo.EnvironmentVariables.ToDictionary(kv => kv.Key, kv => kv.Value)
            };

            project.AddActionOnClose((object)replWindow, InteractiveWindowProvider.Close);

            replWindow.Show(true);

            var result = await pyEvaluator.ResetAsync(false, quiet : true);

            if (result.IsSuccessful)
            {
                try {
                    var filename  = startInfo.Filename;
                    var arguments = startInfo.Arguments ?? string.Empty;

                    if (startInfo.IsScript)
                    {
                        interactive.WriteLine(Strings.CustomCommandExecutingScript.FormatUI(Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteFileAsync(filename, arguments);
                    }
                    else if (startInfo.IsModule)
                    {
                        interactive.WriteLine(Strings.CustomCommandExecutingModule.FormatUI(filename, arguments));
                        Debug.WriteLine("Executing -m {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteModuleAsync(filename, arguments);
                    }
                    else if (startInfo.IsCode)
                    {
                        Debug.WriteLine("Executing -c \"{0}\"", filename, arguments);
                        await pyEvaluator.ExecuteCodeAsync(filename);
                    }
                    else
                    {
                        interactive.WriteLine(Strings.CustomCommandExecutingOther.FormatUI(Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteProcessAsync(filename, arguments);
                    }

                    if (resetRepl)
                    {
                        // We really close the backend, rather than resetting.
                        pyEvaluator.Dispose();
                    }
                } catch (Exception ex) {
                    ActivityLog.LogError(Strings.ProductTitle, Strings.ErrorRunningCustomCommand.FormatUI(_label, ex));
                    var outWindow = OutputWindowRedirector.GetGeneral(project.Site);
                    if (outWindow != null)
                    {
                        outWindow.WriteErrorLine(Strings.ErrorRunningCustomCommand.FormatUI(_label, ex));
                        outWindow.Show();
                    }
                }
                return(true);
            }

            return(false);
        }
예제 #12
0
        protected override void OnCreate()
        {
            base.OnCreate();

            _site = (IServiceProvider)this;

            _pyService = _site.GetPythonToolsService();

            // TODO: Get PYEnvironment added to image list
            BitmapImageMoniker = KnownMonikers.DockPanel;
            Caption            = Strings.Environments;

            _outputWindow = OutputWindowRedirector.GetGeneral(_site);
            Debug.Assert(_outputWindow != null);
            _statusBar = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar;

            var list = new ToolWindow();

            list.Site         = _site;
            list.ViewCreated += List_ViewCreated;

            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInteractiveWindow,
                                         OpenInteractiveWindow_Executed,
                                         OpenInteractiveWindow_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInteractiveScripts,
                                         OpenInteractiveScripts_Executed,
                                         OpenInteractiveScripts_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentPathsExtension.StartInterpreter,
                                         StartInterpreter_Executed,
                                         StartInterpreter_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentPathsExtension.StartWindowsInterpreter,
                                         StartInterpreter_Executed,
                                         StartInterpreter_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         ApplicationCommands.Help,
                                         OnlineHelp_Executed,
                                         OnlineHelp_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         ToolWindow.UnhandledException,
                                         UnhandledException_Executed,
                                         UnhandledException_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInPowerShell,
                                         OpenInPowerShell_Executed,
                                         OpenInPowerShell_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInCommandPrompt,
                                         OpenInCommandPrompt_Executed,
                                         OpenInCommandPrompt_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.EnableIPythonInteractive,
                                         EnableIPythonInteractive_Executed,
                                         EnableIPythonInteractive_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.DisableIPythonInteractive,
                                         DisableIPythonInteractive_Executed,
                                         DisableIPythonInteractive_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentPathsExtension.OpenInBrowser,
                                         OpenInBrowser_Executed,
                                         OpenInBrowser_CanExecute
                                         ));

            Content = list;
        }
예제 #13
0
        protected override void OnCreate()
        {
            base.OnCreate();

            _pyService = _site.GetPythonToolsService();
            _uiThread  = _site.GetUIThread();

            _pyService.InteractiveOptions.Changed += InteractiveOptions_Changed;

            // TODO: Get PYEnvironment added to image list
            BitmapImageMoniker = KnownMonikers.DockPanel;
            Caption            = Strings.Environments;

            _outputWindow = OutputWindowRedirector.GetGeneral(_site);
            Debug.Assert(_outputWindow != null);
            _statusBar = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar;

            var list = new ToolWindow();

            list.ViewCreated  += List_ViewCreated;
            list.ViewSelected += List_ViewSelected;
            list.Site          = _site;
            try {
                list.TelemetryLogger = _pyService.Logger;
            } catch (Exception ex) {
                Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
            }

            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInteractiveWindow,
                                         OpenInteractiveWindow_Executed,
                                         OpenInteractiveWindow_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInteractiveScripts,
                                         OpenInteractiveScripts_Executed,
                                         OpenInteractiveScripts_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentPathsExtension.StartInterpreter,
                                         StartInterpreter_Executed,
                                         StartInterpreter_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentPathsExtension.StartWindowsInterpreter,
                                         StartInterpreter_Executed,
                                         StartInterpreter_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         ApplicationCommands.Help,
                                         OnlineHelp_Executed,
                                         OnlineHelp_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         ToolWindow.UnhandledException,
                                         UnhandledException_Executed,
                                         UnhandledException_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInPowerShell,
                                         OpenInPowerShell_Executed,
                                         OpenInPowerShell_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInCommandPrompt,
                                         OpenInCommandPrompt_Executed,
                                         OpenInCommandPrompt_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentPathsExtension.OpenInBrowser,
                                         OpenInBrowser_Executed,
                                         OpenInBrowser_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.Delete,
                                         DeleteEnvironment_Executed,
                                         DeleteEnvironment_CanExecute
                                         ));

            RegisterCommands(
                CommandAsyncToOleMenuCommandShimFactory.CreateCommand(CommonGuidList.guidPythonToolsCmdSet, (int)PkgCmdIDList.cmdidAddEnvironment, new AddEnvironmentCommand(this))
                );

            Content = list;
        }
예제 #14
0
 public VsPackageManagerUI(IServiceProvider provider, bool alwaysElevate = false)
 {
     _outputWindow  = OutputWindowRedirector.GetGeneral(provider);
     _options       = provider.GetPythonToolsService().GeneralOptions;
     _alwaysElevate = alwaysElevate;
 }
예제 #15
0
파일: VirtualEnv.cs 프로젝트: zyxws012/PTVS
 /// <summary>
 /// Creates a virtual environment using venv. If venv is not available,
 /// the task will succeed but error text will be passed to the
 /// redirector.
 /// </summary>
 public static Task CreateWithVEnv(IServiceProvider provider, IPythonInterpreterFactory factory, string path)
 {
     factory.ThrowIfNotRunnable();
     return(ContinueCreate(provider, factory, path, true, OutputWindowRedirector.GetGeneral(provider)));
 }
예제 #16
0
        private async Task <bool> AttachWorker(AzureWebSiteInfo webSite)
        {
            using (new WaitDialog(
                       Resources.AzureRemoteDebugWaitCaption,
                       string.Format(CultureInfo.CurrentCulture, Resources.AzureRemoteDebugWaitMessage, webSite.Uri),
                       NodejsPackage.Instance,
                       showProgress: true))
            {
                // Get path (relative to site URL) for the debugger endpoint.
                XDocument webConfig;
                try
                {
                    webConfig = await GetWebConfig(webSite);
                }
                catch (WebException)
                {
                    return(false);
                }
                catch (IOException)
                {
                    return(false);
                }
                catch (XmlException)
                {
                    return(false);
                }
                if (webConfig == null)
                {
                    return(false);
                }

                var path =
                    (from add in webConfig.Elements("configuration").Elements("system.webServer").Elements("handlers").Elements("add")
                     let type = (string)add.Attribute("type")
                                where type != null
                                let components = type.Split(',')
                                                 where components[0].Trim() == "Microsoft.NodejsTools.Debugger.WebSocketProxy"
                                                 select(string) add.Attribute("path")
                    ).FirstOrDefault();
                if (path == null)
                {
                    return(false);
                }

                try
                {
                    AttachDebugger(new UriBuilder(webSite.Uri)
                    {
                        Scheme = "wss", Port = -1, Path = path
                    }.Uri);
                }
                catch (Exception ex)
                {
                    // If we got to this point, the attach logic in debug engine will catch exceptions, display proper error message and
                    // ask the user to retry, so the only case where we actually get here is if user canceled on error. If this is the case,
                    // we don't want to pop any additional error messages, so always return true, but log the error in the Output window.
                    var output = OutputWindowRedirector.GetGeneral(NodejsPackage.Instance);
                    output.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, Resources.AzureRemoveDebugCouldNotAttachToWebsiteExceptionErrorMessage, ex.Message));
                    output.ShowAndActivate();
                }
                return(true);
            }
        }
예제 #17
0
        protected override void OnCreate()
        {
            base.OnCreate();

            _site = (IServiceProvider)this;

            _pyService = _site.GetPythonToolsService();

#if DEV14_OR_LATER
            // TODO: Get PYEnvironment added to image list
            BitmapImageMoniker = KnownMonikers.DockPanel;
#else
            BitmapResourceID = PythonConstants.ResourceIdForReplImages;
            BitmapIndex      = 0;
#endif
            Caption = SR.GetString(SR.Environments);

            _service = _site.GetComponentModel().GetService <IInterpreterOptionsService>();

            _outputWindow = OutputWindowRedirector.GetGeneral(_site);
            Debug.Assert(_outputWindow != null);
            _statusBar = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar;

            var list = new ToolWindow();
            list.ViewCreated += List_ViewCreated;

            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInteractiveWindow,
                                         OpenInteractiveWindow_Executed,
                                         OpenInteractiveWindow_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentView.OpenInteractiveOptions,
                                         OpenInteractiveOptions_Executed,
                                         OpenInteractiveOptions_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentPathsExtension.StartInterpreter,
                                         StartInterpreter_Executed,
                                         StartInterpreter_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         EnvironmentPathsExtension.StartWindowsInterpreter,
                                         StartInterpreter_Executed,
                                         StartInterpreter_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         ApplicationCommands.Help,
                                         OnlineHelp_Executed,
                                         OnlineHelp_CanExecute
                                         ));
            list.CommandBindings.Add(new CommandBinding(
                                         ToolWindow.UnhandledException,
                                         UnhandledException_Executed,
                                         UnhandledException_CanExecute
                                         ));

            list.Service = _service;

            Content = list;
        }
예제 #18
0
        private async Task <bool> RunInRepl(IPythonProject2 project, CommandStartInfo startInfo)
        {
            var  executeIn = string.IsNullOrEmpty(startInfo.ExecuteIn) ? CreatePythonCommandItem.ExecuteInRepl : startInfo.ExecuteIn;
            bool resetRepl = executeIn.StartsWith("R", StringComparison.InvariantCulture);

            var replTitle = executeIn.Substring(4).TrimStart(' ', ':');

            if (string.IsNullOrEmpty(replTitle))
            {
                replTitle = SR.GetString(SR.CustomCommandReplTitle, DisplayLabelWithoutAccessKeys);
            }
            else
            {
                var match = _customCommandLabelRegex.Match(replTitle);
                if (match.Success)
                {
                    replTitle = LoadResourceFromAssembly(
                        match.Groups["assembly"].Value,
                        match.Groups["namespace"].Value,
                        match.Groups["key"].Value
                        );
                }
            }

            replTitle = PerformSubstitutions(project, replTitle);

            var replWindowId = PythonReplEvaluatorProvider.GetConfigurableReplId(ReplId + executeIn.Substring(4));

            var model        = _project.Site.GetComponentModel();
            var replProvider = model.GetService <IReplWindowProvider>();

            if (replProvider == null)
            {
                return(false);
            }

            var  replWindow = replProvider.FindReplWindow(replWindowId);
            bool created    = replWindow == null;

            if (created)
            {
                replWindow = replProvider.CreateReplWindow(
                    _project.Site.GetPythonContentType(),
                    replTitle,
                    typeof(PythonLanguageInfo).GUID,
                    replWindowId
                    );
            }

            var replToolWindow = replWindow as ToolWindowPane;
            var replFrame      = (replToolWindow != null) ? replToolWindow.Frame as IVsWindowFrame : null;

            var pyEvaluator = replWindow.Evaluator as PythonReplEvaluator;
            var options     = (pyEvaluator != null) ? pyEvaluator.CurrentOptions as ConfigurablePythonReplOptions : null;

            if (options == null)
            {
                if (created && replFrame != null)
                {
                    // We created the window, but it isn't valid, so we'll close
                    // it again immediately.
                    replFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
                }

                return(false);
            }

            if (pyEvaluator.IsExecuting)
            {
                throw new InvalidOperationException(SR.GetString(SR.ErrorCommandAlreadyRunning));
            }

            options.InterpreterFactory = project.GetInterpreterFactory();
            options.Project            = project as PythonProjectNode;
            options._workingDir        = startInfo.WorkingDirectory;
            options._envVars           = startInfo.EnvironmentVariables;

            project.AddActionOnClose((object)replWindow, BasePythonReplEvaluator.CloseReplWindow);

            var pane  = replWindow as ToolWindowPane;
            var frame = pane != null ? pane.Frame as IVsWindowFrame : null;

            if (frame != null)
            {
                ErrorHandler.ThrowOnFailure(frame.Show());
            }

            var result = await pyEvaluator.Reset(quiet : true);

            if (result.IsSuccessful)
            {
                try {
                    var filename  = startInfo.Filename;
                    var arguments = startInfo.Arguments;

                    if (startInfo.IsScript)
                    {
                        pyEvaluator.Window.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        result = await pyEvaluator.ExecuteFile(filename, arguments);
                    }
                    else if (startInfo.IsModule)
                    {
                        pyEvaluator.Window.WriteLine(string.Format("Executing -m {0} {1}", filename, arguments));
                        Debug.WriteLine("Executing -m {0} {1}", filename, arguments);
                        result = await pyEvaluator.ExecuteModule(filename, arguments);
                    }
                    else if (startInfo.IsCode)
                    {
                        Debug.WriteLine("Executing -c \"{0}\"", filename, arguments);
                        result = await pyEvaluator.ExecuteText(filename);
                    }
                    else
                    {
                        pyEvaluator.Window.WriteLine(string.Format("Executing {0} {1}", Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        result = await pyEvaluator.ExecuteProcess(filename, arguments);
                    }

                    if (resetRepl)
                    {
                        // We really close the backend, rather than resetting.
                        pyEvaluator.Close();
                    }
                } catch (Exception ex) {
                    ActivityLog.LogError(SR.ProductName, SR.GetString(SR.ErrorRunningCustomCommand, _label, ex));
                    var outWindow = OutputWindowRedirector.GetGeneral(project.Site);
                    if (outWindow != null)
                    {
                        outWindow.WriteErrorLine(SR.GetString(SR.ErrorRunningCustomCommand, _label, ex));
                        outWindow.Show();
                    }
                }
                return(true);
            }

            return(false);
        }
예제 #19
0
        private async Task ExecuteWorker(PythonProjectNode project)
        {
            _errorListProvider.Tasks.Clear();

            var interpFactory = project.GetInterpreterFactory();
            var startInfo     = GetStartInfo(project);

            var packagesToInstall = new List <string>();

            foreach (var pkg in startInfo.RequiredPackages)
            {
                if (!await Pip.IsInstalled(interpFactory, pkg))
                {
                    packagesToInstall.Add(pkg);
                }
            }

            if (packagesToInstall.Any())
            {
                await Pip.QueryInstall(
                    interpFactory,
                    string.Join(" ", packagesToInstall),
                    project.Site,
                    SR.GetString(SR.CustomCommandPrerequisitesInstallPrompt, string.Join("\r\n", packagesToInstall)),
                    false,
                    OutputWindowRedirector.GetGeneral(project.Site)
                    );
            }

            if (startInfo.TargetType == CreatePythonCommandItem.TargetTypePip)
            {
                if (startInfo.ExecuteInOutput)
                {
                    await Pip.Install(
                        _project.Site,
                        interpFactory,
                        string.Format("{0} {1}", startInfo.Filename, startInfo.Arguments),
                        project.Site,
                        false,
                        OutputWindowRedirector.GetGeneral(project.Site)
                        );

                    return;
                }

                // Rewrite start info to execute
                startInfo.TargetType = CreatePythonCommandItem.TargetTypeModule;
                startInfo.AddArgumentAtStart(startInfo.Filename);
                startInfo.Filename = "pip";
            }

            if (startInfo.ExecuteInRepl)
            {
                if (await RunInRepl(project, startInfo))
                {
                    return;
                }
            }

            startInfo.AdjustArgumentsForProcessStartInfo(GetInterpreterPath(project, false));

            if (startInfo.ExecuteInOutput)
            {
                RunInOutput(project, startInfo);
            }
            else
            {
                RunInConsole(project, startInfo);
            }
        }
예제 #20
0
        public async Task <Connection> ActivateAsync()
        {
            var nodePath = await _nodeEnvironmentProvider.GetNodeExecutablePath();

            if (!File.Exists(nodePath))
            {
                MessageBox.ShowErrorMessage(_site, Strings.LanguageClientNodejsNotFound);
                return(null);
            }

            var isDebugging    = IsDebugging();
            var debugArgs      = isDebugging ? GetDebugArguments() : string.Empty;
            var serverFilePath = isDebugging ? GetDebugServerLocation() : GetServerLocation();
            var debuggerExtra  = isDebugging ? "--verbose" : string.Empty;

            if (!File.Exists(serverFilePath))
            {
                MessageBox.ShowErrorMessage(_site, Strings.LanguageClientPylanceNotFound);
                return(null);
            }

            var serverFolderPath = Path.GetDirectoryName(serverFilePath);

            var info = new ProcessStartInfo {
                FileName               = nodePath,
                WorkingDirectory       = serverFolderPath,
                RedirectStandardInput  = true,
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                CreateNoWindow         = true,
                Arguments              = $"{debugArgs} \"{serverFilePath}\" -- --stdio --cancellationReceive=file:{this.CancellationFolderName} {debuggerExtra}",
            };

            var process = new Process {
                StartInfo = info
            };

            if (process.Start())
            {
                if (isDebugging)
                {
                    System.Diagnostics.Debug.WriteLine($"Attach to {process.Id} for pylance debugging");
                    // During debugging give us time to attach
                    await Task.Delay(5000);
                }

                // Write to output if we can't launch for some reason
                if (process.HasExited)
                {
                    string output       = process.StandardError.ReadToEnd();
                    var    outputWindow = OutputWindowRedirector.GetGeneral(_site);
                    outputWindow.WriteLine(output);
                }
                else
                {
                    // Otherwise create a connection where we wrap the stdin stream so that we can intercept all messages
                    return(new Connection(
                               process.StandardOutput.BaseStream,
                               new StreamIntercepter(process.StandardInput.BaseStream, _serverSendHandler, (a) => { })));
                }
            }
            return(null);
        }