コード例 #1
0
        private static PythonVersion TryGetCPythonPath(PythonLanguageVersion version, RegistryKey python, bool x64)
        {
            if (python != null)
            {
                string versionStr = version.ToString().Substring(1);
                string id         = versionStr = versionStr[0] + "." + versionStr[1];
                if (!x64 && version >= PythonLanguageVersion.V35)
                {
                    versionStr += "-32";
                }

                using (var versionKey = python.OpenSubKey(versionStr + "\\InstallPath")) {
                    if (versionKey != null)
                    {
                        var installPath = versionKey.GetValue("");
                        if (installPath != null)
                        {
                            var path = Path.Combine(installPath.ToString(), "python.exe");
                            var arch = NativeMethods.GetBinaryType(path);
                            if (arch == ProcessorArchitecture.X86)
                            {
                                return(x64 ? null : new PythonVersion(
                                           path,
                                           version,
                                           CPythonInterpreterFactoryConstants.GetIntepreterId(
                                               "PythonCore",
                                               arch,
                                               id
                                               ),
                                           false,
                                           false,
                                           true
                                           ));
                            }
                            else if (arch == ProcessorArchitecture.Amd64)
                            {
                                return(x64 ? new PythonVersion(
                                           path,
                                           version,
                                           CPythonInterpreterFactoryConstants.GetIntepreterId(
                                               "PythonCore",
                                               arch,
                                               id
                                               ),
                                           true,
                                           false,
                                           true
                                           ) : null);
                            }
                            else
                            {
                                return(null);
                            }
                        }
                    }
                }
            }
            return(null);
        }
コード例 #2
0
ファイル: InterpreterView.cs プロジェクト: szh2bg/PTVS
        private static string FormatInvalidId(string id)
        {
            string company, tag;

            if (CPythonInterpreterFactoryConstants.TryParseInterpreterId(id, out company, out tag))
            {
                if (company == PythonRegistrySearch.PythonCoreCompany)
                {
                    company = "Python";
                }
                return("{0} {1}".FormatUI(company, tag));
            }
            return(id);
        }
コード例 #3
0
        private static PythonVersion GetJythonVersion(PythonLanguageVersion version)
        {
            var candidates = new List <DirectoryInfo>();
            var ver        = version.ToVersion();
            var path1      = string.Format("jython{0}{1}*", ver.Major, ver.Minor);
            var path2      = string.Format("jython{0}.{1}*", ver.Major, ver.Minor);

            foreach (var drive in DriveInfo.GetDrives())
            {
                if (drive.DriveType != DriveType.Fixed)
                {
                    continue;
                }

                try
                {
                    candidates.AddRange(drive.RootDirectory.EnumerateDirectories(path1));
                    candidates.AddRange(drive.RootDirectory.EnumerateDirectories(path2));
                }
                catch
                {
                }
            }

            foreach (var dir in candidates)
            {
                var interpreter = dir.EnumerateFiles("jython.bat").FirstOrDefault();
                if (interpreter == null)
                {
                    continue;
                }
                var libPath = dir.EnumerateDirectories("Lib").FirstOrDefault();
                if (libPath == null || !libPath.EnumerateFiles("site.py").Any())
                {
                    continue;
                }
                return(new PythonVersion(new VisualStudioInterpreterConfiguration(
                                             CPythonInterpreterFactoryConstants.GetInterpreterId(
                                                 "Jython",
                                                 version.ToVersion().ToString()
                                                 ),
                                             string.Format("Jython {0}", version.ToVersion()),
                                             dir.FullName,
                                             interpreter.FullName,
                                             version: version.ToVersion()
                                             )));
            }
            return(null);
        }
コード例 #4
0
        private static PythonVersion GetCPythonVersion(PythonLanguageVersion version, InterpreterArchitecture arch)
        {
            var res = _foundInRegistry.FirstOrDefault(ii =>
                                                      ii.Configuration.Id.StartsWith("Global|PythonCore|") &&
                                                      ii.Configuration.Architecture == arch &&
                                                      ii.Configuration.Version == version.ToVersion()
                                                      );

            if (res != null)
            {
                return(new PythonVersion(res.Configuration, cPython: true));
            }

            var ver = version.ToVersion();
            var tag = ver + (arch == InterpreterArchitecture.x86 ? "-32" : "");

            foreach (var path in new[] {
                string.Format("Python{0}{1}", ver.Major, ver.Minor),
                string.Format("Python{0}{1}_{2}", ver.Major, ver.Minor, arch.ToString("x")),
                string.Format("Python{0}{1}-{2}", ver.Major, ver.Minor, arch.ToString("#")),
                string.Format("Python{0}{1}_{2}", ver.Major, ver.Minor, arch.ToString("#")),
            })
            {
                var prefixPath = Path.Combine(Environment.GetEnvironmentVariable("SystemDrive"), "\\", path);
                var exePath    = Path.Combine(prefixPath, CPythonInterpreterFactoryConstants.ConsoleExecutable);
                var procArch   = (arch == InterpreterArchitecture.x86) ? ProcessorArchitecture.X86 :
                                 (arch == InterpreterArchitecture.x64) ? ProcessorArchitecture.Amd64 :
                                 ProcessorArchitecture.None;

                if (procArch == Microsoft.PythonTools.Infrastructure.NativeMethods.GetBinaryType(path))
                {
                    return(new PythonVersion(new VisualStudioInterpreterConfiguration(
                                                 CPythonInterpreterFactoryConstants.GetInterpreterId("PythonCore", tag),
                                                 "Python {0} {1}".FormatInvariant(arch, ver),
                                                 prefixPath,
                                                 exePath,
                                                 pathVar: CPythonInterpreterFactoryConstants.PathEnvironmentVariableName,
                                                 architecture: arch,
                                                 version: ver
                                                 )));
                }
            }
            return(null);
        }
コード例 #5
0
ファイル: ToolWindow.xaml.cs プロジェクト: yuts/PTVS
        private async void AddCustomEnvironment_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_service == null)
            {
                return;
            }

            const string baseName = "New Environment";
            string       name     = baseName;
            int          count    = 2;

            while (_interpreters.FindConfiguration(CPythonInterpreterFactoryConstants.GetInterpreterId("VisualStudio", name)) != null)
            {
                name = baseName + " " + count++;
            }

            var factory = _service.AddConfigurableInterpreter(
                name,
                new InterpreterConfiguration(
                    "",
                    name,
                    "",
                    "python\\python.exe",
                    arch: InterpreterArchitecture.x86
                    )
                );

            UpdateEnvironments(factory);

            await Dispatcher.InvokeAsync(() => {
                var coll = TryFindResource("SortedExtensions") as CollectionViewSource;
                if (coll != null)
                {
                    var select = coll.View.OfType <ConfigurationExtensionProvider>().FirstOrDefault();
                    if (select != null)
                    {
                        coll.View.MoveCurrentTo(select);
                    }
                }
            }, DispatcherPriority.Normal);
        }
コード例 #6
0
ファイル: ResolveEnvironment.cs プロジェクト: zyxws012/PTVS
        public bool Execute()
        {
            string id = InterpreterId;

            ProjectCollection collection = null;
            Project           project    = null;

#if !BUILDTASKS_CORE
            var exports = GetExportProvider();
            if (exports == null)
            {
                _log.LogError("Unable to obtain interpreter service.");
                return(false);
            }
#endif

            try {
                try {
                    project = ProjectCollection.GlobalProjectCollection.GetLoadedProjects(_projectPath).Single();
                } catch (InvalidOperationException) {
                    // Could not get exactly one project matching the path.
                }

                if (project == null)
                {
                    collection = new ProjectCollection();
                    project    = collection.LoadProject(_projectPath);
                }

                if (id == null)
                {
                    id = project.GetPropertyValue("InterpreterId");
                    if (String.IsNullOrWhiteSpace(id))
                    {
#if !BUILDTASKS_CORE
                        var options = exports.GetExportedValueOrDefault <IInterpreterOptionsService>();
                        if (options != null)
                        {
                            id = options.DefaultInterpreterId;
                        }
#endif
                    }
                }

                var projectHome = PathUtils.GetAbsoluteDirectoryPath(
                    project.DirectoryPath,
                    project.GetPropertyValue("ProjectHome")
                    );

                var searchPath = project.GetPropertyValue("SearchPath");
                if (!string.IsNullOrEmpty(searchPath))
                {
                    SearchPaths = searchPath.Split(';')
                                  .Select(p => PathUtils.GetAbsoluteFilePath(projectHome, p))
                                  .ToArray();
                }
                else
                {
                    SearchPaths = new string[0];
                }

#if BUILDTASKS_CORE
                ProjectItem item = null;
                InterpreterConfiguration config = null;

                if (string.IsNullOrEmpty(id))
                {
                    id = project.GetItems(MSBuildConstants.InterpreterReferenceItem).Select(pi => pi.GetMetadataValue(MSBuildConstants.IdKey)).LastOrDefault(i => !string.IsNullOrEmpty(i));
                }
                if (string.IsNullOrEmpty(id))
                {
                    item = project.GetItems(MSBuildConstants.InterpreterItem).FirstOrDefault();
                    if (item == null)
                    {
                        var found = PythonRegistrySearch.PerformDefaultSearch().OrderByDescending(i => i.Configuration.Version).ToArray();
                        config = (
                            found.Where(i => CPythonInterpreterFactoryConstants.TryParseInterpreterId(i.Configuration.Id, out var co, out _) &&
                                        PythonRegistrySearch.PythonCoreCompany.Equals(co, StringComparison.OrdinalIgnoreCase)).FirstOrDefault()
                            ?? found.FirstOrDefault()
                            )?.Configuration;
                    }
                }
                else
                {
                    // Special case MSBuild environments
                    var m = Regex.Match(id, @"MSBuild\|(?<id>.+?)\|(?<moniker>.+)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
                    if (m.Success && m.Groups["id"].Success)
                    {
                        var subId = m.Groups["id"].Value;
                        item = project.GetItems(MSBuildConstants.InterpreterItem)
                               .FirstOrDefault(pi => subId.Equals(pi.GetMetadataValue(MSBuildConstants.IdKey), StringComparison.OrdinalIgnoreCase));
                    }
                    if (item == null)
                    {
                        config = PythonRegistrySearch.PerformDefaultSearch()
                                 .FirstOrDefault(pi => id.Equals(pi.Configuration.Id, StringComparison.OrdinalIgnoreCase))?.Configuration;
                    }
                }
                if (item != null)
                {
                    PrefixPath = PathUtils.GetAbsoluteDirectoryPath(projectHome, item.EvaluatedInclude);
                    if (PathUtils.IsSubpathOf(projectHome, PrefixPath))
                    {
                        ProjectRelativePrefixPath = PathUtils.GetRelativeDirectoryPath(projectHome, PrefixPath);
                    }
                    else
                    {
                        ProjectRelativePrefixPath = string.Empty;
                    }
                    InterpreterPath         = PathUtils.GetAbsoluteFilePath(PrefixPath, item.GetMetadataValue(MSBuildConstants.InterpreterPathKey));
                    WindowsInterpreterPath  = PathUtils.GetAbsoluteFilePath(PrefixPath, item.GetMetadataValue(MSBuildConstants.WindowsPathKey));
                    Architecture            = InterpreterArchitecture.TryParse(item.GetMetadataValue(MSBuildConstants.ArchitectureKey)).ToString("X");
                    PathEnvironmentVariable = item.GetMetadataValue(MSBuildConstants.PathEnvVarKey).IfNullOrEmpty("PYTHONPATH");
                    Description             = item.GetMetadataValue(MSBuildConstants.DescriptionKey).IfNullOrEmpty(PathUtils.CreateFriendlyDirectoryPath(projectHome, PrefixPath));
                    Version ver;
                    if (Version.TryParse(item.GetMetadataValue(MSBuildConstants.VersionKey) ?? "", out ver))
                    {
                        MajorVersion = ver.Major.ToString();
                        MinorVersion = ver.Minor.ToString();
                    }
                    else
                    {
                        MajorVersion = MinorVersion = "0";
                    }
                    return(true);
                }
                else if (config != null)
                {
                    UpdateResultFromConfiguration(config, projectHome);
                    return(true);
                }
#else
                // MsBuildProjectContextProvider isn't available in-proc, instead we rely upon the
                // already loaded VsProjectContextProvider which is loaded in proc and already
                // aware of the projects loaded in Solution Explorer.
                var projectContext = exports.GetExportedValueOrDefault <MsBuildProjectContextProvider>();
                if (projectContext != null)
                {
                    projectContext.AddContext(project);
                }
                try {
                    var config = exports.GetExportedValue <IInterpreterRegistryService>().FindConfiguration(id);

                    if (config != null)
                    {
                        UpdateResultFromConfiguration(config, projectHome);
                        return(true);
                    }
                } finally {
                    if (projectContext != null)
                    {
                        projectContext.RemoveContext(project);
                    }
                }
#endif

                if (!string.IsNullOrEmpty(id))
                {
                    _log.LogError(
                        "The environment '{0}' is not available. Check your project configuration and try again.",
                        id
                        );
                    return(false);
                }
            } catch (Exception ex) {
                _log.LogErrorFromException(ex);
            } finally {
                if (collection != null)
                {
                    collection.UnloadAllProjects();
                    collection.Dispose();
                }
            }

            _log.LogError("Unable to resolve environment");
            return(false);
        }
コード例 #7
0
        private static PythonVersion GetCPythonVersion(PythonLanguageVersion version, bool x64 = false)
        {
            if (!x64)
            {
                foreach (var baseKey in new[] { Registry.LocalMachine, Registry.CurrentUser })
                {
                    using (var python = baseKey.OpenSubKey(PythonCorePath)) {
                        var res = TryGetCPythonPath(version, python, x64);
                        if (res != null)
                        {
                            return(res);
                        }
                    }
                }
            }

            if (Environment.Is64BitOperatingSystem && x64)
            {
                foreach (var baseHive in new[] { RegistryHive.LocalMachine, RegistryHive.CurrentUser })
                {
                    var python64 = RegistryKey.OpenBaseKey(baseHive, RegistryView.Registry64).OpenSubKey(PythonCorePath);
                    var res      = TryGetCPythonPath(version, python64, x64);
                    if (res != null)
                    {
                        return(res);
                    }
                }
            }

            var path = "C:\\Python" + version.ToString().Substring(1) + "\\python.exe";
            var arch = NativeMethods.GetBinaryType(path);

            if (arch == ProcessorArchitecture.X86 && !x64)
            {
                return(new PythonVersion(path, version,
                                         CPythonInterpreterFactoryConstants.GetIntepreterId(
                                             "PythonCore",
                                             arch,
                                             version.ToVersion().ToString()
                                             ),
                                         false,
                                         false,
                                         true
                                         ));
            }
            else if (arch == ProcessorArchitecture.Amd64 && x64)
            {
                return(new PythonVersion(
                           path,
                           version,
                           CPythonInterpreterFactoryConstants.GetIntepreterId(
                               "PythonCore",
                               arch,
                               version.ToVersion().ToString()
                               ),
                           true,
                           false,
                           true
                           ));
            }

            if (x64)
            {
                path = "C:\\Python" + version.ToString().Substring(1) + "_x64\\python.exe";
                arch = NativeMethods.GetBinaryType(path);
                if (arch == ProcessorArchitecture.Amd64)
                {
                    return(new PythonVersion(
                               path,
                               version,
                               CPythonInterpreterFactoryConstants.GetIntepreterId(
                                   "PythonCore",
                                   arch,
                                   version.ToVersion().ToString()
                                   ),
                               true,
                               false,
                               true

                               ));
                }
            }

            return(null);
        }
コード例 #8
0
        private VisualStudioInterpreterConfiguration TryReadConfiguration(
            string company,
            string tag,
            RegistryKey tagKey,
            RegistryKey installKey,
            bool pythonCoreCompatibility,
            InterpreterArchitecture assumedArch
            )
        {
            if (tagKey == null || installKey == null)
            {
                return(null);
            }

            string prefixPath, exePath, exewPath;

            try
            {
                prefixPath = PathUtils.NormalizePath(installKey.GetValue(null) as string);
                exePath    = PathUtils.NormalizePath(installKey.GetValue("ExecutablePath") as string);
                exewPath   = PathUtils.NormalizePath(installKey.GetValue("WindowedExecutablePath") as string);
            }
            catch (ArgumentException ex)
            {
                Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
                return(null);
            }
            if (pythonCoreCompatibility && !string.IsNullOrEmpty(prefixPath))
            {
                if (string.IsNullOrEmpty(exePath))
                {
                    try
                    {
                        exePath = PathUtils.GetAbsoluteFilePath(prefixPath, CPythonInterpreterFactoryConstants.ConsoleExecutable);
                    }
                    catch (ArgumentException)
                    {
                    }
                }
                if (string.IsNullOrEmpty(exewPath))
                {
                    try
                    {
                        exewPath = PathUtils.GetAbsoluteFilePath(prefixPath, CPythonInterpreterFactoryConstants.WindowsExecutable);
                    }
                    catch (ArgumentException)
                    {
                    }
                }
            }

            var version = tagKey.GetValue("Version") as string;

            if (pythonCoreCompatibility && string.IsNullOrEmpty(version) && tag.Length >= 3)
            {
                version = tag.Substring(0, 3);
            }

            Version sysVersion;
            var     sysVersionString = tagKey.GetValue("SysVersion") as string;

            if (pythonCoreCompatibility && string.IsNullOrEmpty(sysVersionString) && tag.Length >= 3)
            {
                sysVersionString = tag.Substring(0, 3);
            }
            if (string.IsNullOrEmpty(sysVersionString) || !Version.TryParse(sysVersionString, out sysVersion))
            {
                sysVersion = new Version(0, 0);
            }

            PythonLanguageVersion langVersion;

            try
            {
                langVersion = sysVersion.ToLanguageVersion();
            }
            catch (InvalidOperationException)
            {
                langVersion = PythonLanguageVersion.None;
                sysVersion  = new Version(0, 0);
            }

            if (!InterpreterArchitecture.TryParse(tagKey.GetValue("SysArchitecture", null) as string, out InterpreterArchitecture arch))
            {
                arch = assumedArch;
            }

            if (arch == InterpreterArchitecture.Unknown && File.Exists(exePath))
            {
                switch (NativeMethods.GetBinaryType(exePath))
                {
                case System.Reflection.ProcessorArchitecture.X86:
                    arch = InterpreterArchitecture.x86;
                    break;

                case System.Reflection.ProcessorArchitecture.Amd64:
                    arch = InterpreterArchitecture.x64;
                    break;
                }
            }

            if (pythonCoreCompatibility && sysVersion != null && sysVersion < new Version(3, 5) && arch == InterpreterArchitecture.x86)
            {
                // Older versions of CPython did not include
                // "-32" in their Tag, so we will add it here
                // for uniqueness.
                tag += "-32";
            }

            var pathVar = tagKey.GetValue("PathEnvironmentVariable") as string ??
                          CPythonInterpreterFactoryConstants.PathEnvironmentVariableName;

            var id = CPythonInterpreterFactoryConstants.GetInterpreterId(company, tag);

            var description = tagKey.GetValue("DisplayName") as string;

            if (string.IsNullOrEmpty(description))
            {
                if (pythonCoreCompatibility)
                {
                    description = "Python {0}{1: ()}".FormatUI(version, arch);
                }
                else
                {
                    description = "{0} {1}".FormatUI(company, tag);
                }
            }

            return(new VisualStudioInterpreterConfiguration(
                       id,
                       description,
                       prefixPath,
                       exePath,
                       exewPath,
                       pathVar,
                       arch,
                       sysVersion
                       ));
        }