Ejemplo n.º 1
0
        private static string CreateVirtualEnv(IPythonFormatter formatter)
        {
            var python = PythonPaths.LatestVersion;

            python.AssertInstalled();

            var envPath       = python.CreateVirtualEnv(VirtualEnvName.First, new[] { formatter.Package });
            var installedPath = Path.Combine(envPath, "Scripts", $"{formatter.Package}.exe");

            Assert.IsTrue(
                File.Exists(installedPath),
                $"Cannot find {installedPath} in virtual env");

            return(Path.Combine(envPath, "scripts", "python.exe"));
        }
Ejemplo n.º 2
0
        private async Task FormatDocumentAsync(
            ITextDocument textDoc,
            ITextSnapshot snapshot,
            IPythonFormatter formatter,
            string filePath,
            string contents,
            Range range,
            string[] extraArgs
            )
        {
            await TaskScheduler.Default;
            var factory     = _optionsService.DefaultInterpreter;
            var interpreter = factory.Configuration.InterpreterPath;
            var edits       = await formatter.FormatDocumentAsync(interpreter, filePath, contents, range, extraArgs);

            await _joinableTaskFactory.SwitchToMainThreadAsync();

            LspEditorUtilities.ApplyTextEdits(edits, snapshot, textDoc.TextBuffer);
        }
Ejemplo n.º 3
0
        private async Task <bool> PromptInstallModuleAsync(
            IPythonFormatter formatter,
            IPythonInterpreterFactory factory,
            IPackageManager pm
            )
        {
            await _joinableTaskFactory.SwitchToMainThreadAsync();

            var message = Strings.InstallFormatterPrompt.FormatUI(formatter.Package, factory.Configuration.Description);

            if (ShowYesNoPrompt(message))
            {
                try {
                    return(await pm.InstallAsync(PackageSpec.FromArguments(formatter.Package), new VsPackageManagerUI(_site), CancellationToken.None));
                } catch (Exception ex) when(!ex.IsCriticalException())
                {
                    ShowErrorMessage(Strings.ErrorUnableToInstallFormatter.FormatUI(ex.Message));
                }
            }
            return(false);
        }
Ejemplo n.º 4
0
        private bool GetConfiguration(
            ITextDocument textDoc,
            out IPythonFormatter formatter,
            out IPythonInterpreterFactory factory,
            out string[] extraArgs
            )
        {
            formatter = null;
            factory   = null;
            extraArgs = new string[0];

            const string defaultFormatterId = "black";
            var          workspace          = _workspaceContextProvider.Workspace;
            string       formatterId        = UserSettings.GetStringSetting(PythonConstants.FormatterSetting, textDoc.FilePath, _site, workspace, out var source);

            switch (source)
            {
            case UserSettings.ValueSource.Project:
                factory = _site.GetProjectContainingFile(textDoc.FilePath)?.ActiveInterpreter;
                break;

            case UserSettings.ValueSource.Workspace:
                factory = workspace.CurrentFactory;
                break;
            }

            // If all fails, use global setting
            if (string.IsNullOrEmpty(formatterId))
            {
                formatterId = _site.GetPythonToolsService().FormattingOptions.Formatter;
                formatterId = !string.IsNullOrEmpty(formatterId) ? formatterId : defaultFormatterId;
            }

            formatter = _formattingProviders.SingleOrDefault(p => string.Compare(p.Value.Identifier, formatterId, StringComparison.OrdinalIgnoreCase) == 0)?.Value;
            factory   = factory ?? _optionsService.DefaultInterpreter;

            return(formatter != null && factory != null);
        }
Ejemplo n.º 5
0
        private async Task <bool> InstallFormatterAsync(IPythonFormatter formatter, IPythonInterpreterFactory factory)
        {
            var pm = _optionsService.GetPackageManagers(factory).FirstOrDefault();

            return(pm != null && await PromptInstallModuleAsync(formatter, factory, pm));
        }
Ejemplo n.º 6
0
        private async Task FormatDocumentAsync(ITextDocument textDoc, ITextSnapshot snapshot, IPythonFormatter formatter, IPythonInterpreterFactory factory, Range range, string[] extraArgs)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var documentFilePath = textDoc.FilePath;
            var documentContents = snapshot.GetText();

            var tempFilePath = textDoc.IsDirty
                ? CreateTempFileWithContents(documentFilePath, documentContents)
                : documentFilePath;

            try {
                bool isErrorModuleNotInstalled;
                bool isErrorInstallingModule;
                do
                {
                    var isErrorRangeNotSupported = false;
                    isErrorModuleNotInstalled = false;
                    isErrorInstallingModule   = false;

                    try {
                        await FormatDocumentAsync(textDoc, snapshot, formatter, tempFilePath, documentContents, range, extraArgs);
                    } catch (Exception e) when(!e.IsCriticalException())
                    {
                        isErrorModuleNotInstalled = e is PythonFormatterModuleNotFoundException;
                        isErrorRangeNotSupported  = e is PythonFormatterRangeNotSupportedException;

                        if (e is PythonFormatterModuleNotFoundException)
                        {
                            isErrorInstallingModule = !await InstallFormatterAsync(formatter, factory);
                        }
                        else
                        {
                            ShowErrorMessage(e.Message);
                        }
                    } finally {
                        stopwatch.Stop();
                        _site.GetPythonToolsService().Logger.LogEvent(
                            PythonLogEvent.FormatDocument,
                            new FormatDocumentInfo {
                            Version                   = factory.Configuration.Version.ToString(),
                            Formatter                 = formatter.Identifier,
                            TimeMilliseconds          = stopwatch.ElapsedMilliseconds,
                            IsRange                   = range != null,
                            IsError                   = true,
                            IsErrorRangeNotSupported  = isErrorRangeNotSupported,
                            IsErrorModuleNotInstalled = isErrorModuleNotInstalled,
                            IsErrorInstallingModule   = isErrorInstallingModule
                        }
                            );
                    }
                } while (isErrorModuleNotInstalled && !isErrorInstallingModule);
            } finally {
                if (documentFilePath != tempFilePath)
                {
                    try {
                        File.Delete(tempFilePath);
                    } catch (IOException) { }
                }
            }
        }