Exemplo n.º 1
0
        private void OnInterpretersChanged(object sender, EventArgs e)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke((Action)(() => OnInterpretersChanged(sender, e)));
                return;
            }

            var existing = Interpreters.Where(iv => iv.Interpreter != null).ToDictionary(iv => iv.Interpreter);
            var def      = _project.GetInterpreterFactory();

            int i = 0;

            foreach (var interp in InterpreterView.GetInterpreters(_project.Site, _project).Select(x => x.Interpreter))
            {
                if (!existing.Remove(interp))
                {
                    Interpreters.Insert(i, new InterpreterView(interp, interp.Configuration.FullDescription, interp == def));
                }
                i += 1;
            }
            foreach (var kv in existing)
            {
                Interpreters.Remove(kv.Value);
            }
        }
Exemplo n.º 2
0
        public AddVirtualEnvironmentView(
            PythonProjectNode project,
            IInterpreterRegistryService interpreterService,
            IPythonInterpreterFactory selectInterpreter
            )
        {
            _interpreterService = interpreterService;
            _project            = project;
            VirtualEnvBasePath  = _projectHome = project.ProjectHome;
            Interpreters        = new ObservableCollection <InterpreterView>(InterpreterView.GetInterpreters(project.Site, project));
            var selection = Interpreters.FirstOrDefault(v => v.Interpreter == selectInterpreter);

            if (selection == null)
            {
                selection = Interpreters.FirstOrDefault(v => v.Interpreter == project.GetInterpreterFactory())
                            ?? Interpreters.LastOrDefault();
            }
            BaseInterpreter = selection;

            _project.InterpreterFactoriesChanged += OnInterpretersChanged;

            var venvName = "env";

            for (int i = 1; Directory.Exists(Path.Combine(_projectHome, venvName)); ++i)
            {
                venvName = "env" + i.ToString();
            }
            VirtualEnvName = venvName;

            CanInstallRequirementsTxt  = File.Exists(PathUtils.GetAbsoluteFilePath(_projectHome, "requirements.txt"));
            WillInstallRequirementsTxt = CanInstallRequirementsTxt;
        }
Exemplo n.º 3
0
        internal static string GetInterpreterPath(PythonProjectNode project, bool isWindows)
        {
            var factory = project.GetInterpreterFactory();

            if (factory == null)
            {
                throw new NoInterpretersException();
            }

            var interpreterService = project.Site.GetComponentModel().GetService <IInterpreterOptionsService>();

            if (interpreterService == null || factory == interpreterService.NoInterpretersValue)
            {
                throw new NoInterpretersException();
            }

            return(isWindows ?
                   factory.Configuration.WindowsInterpreterPath :
                   factory.Configuration.InterpreterPath);
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
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);
            }
        }