Пример #1
0
        private static void AnalyzeCode(
            out PythonAnalyzer analyzer,
            out IPythonProjectEntry entry,
            string code,
            Version preferredVersion = null,
            InterpreterArchitecture preferredArch = null,
            string module = "test-module"
            )
        {
            var provider = InterpFactory;
            var factory  = provider.GetInterpreterFactories().OrderByDescending(f => f.Configuration.Version)
                           .Where(f => preferredVersion == null || f.Configuration.Version == preferredVersion)
                           .Where(f => preferredArch == null || f.Configuration.Architecture == preferredArch)
                           .FirstOrDefault();

            Assert.IsNotNull(factory, "no factory found");

            analyzer = PythonAnalyzer.CreateSynchronously(factory);
            var path = Path.Combine(TestData.GetTempPath(randomSubPath: true), module.Replace('.', '\\'));

            Directory.CreateDirectory(PathUtils.GetParent(path));
            File.WriteAllText(path, code);

            entry = analyzer.AddModule(module, path);
            PythonAst ast;

            using (var p = Parser.CreateParser(new StringReader(code), factory.GetLanguageVersion())) {
                ast = p.ParseFile();
                entry.UpdateTree(ast, null);
            }

            entry.Analyze(CancellationToken.None, true);
        }
Пример #2
0
        public string ApplyConfiguration(ConfigurationEnvironmentView view)
        {
            if (!_alwaysCreateNew)
            {
                var factory = view.EnvironmentView.Factory;
                if (view.Description != factory.Configuration.Description)
                {
                    // We're renaming the interpreter, remove the old one...
                    _interpreterOptions.RemoveConfigurableInterpreter(factory.Configuration.Id);
                }
            }

            Version version;

            if (!Version.TryParse(view.VersionName, out version))
            {
                version = null;
            }

            return(_interpreterOptions.AddConfigurableInterpreter(
                       view.Description,
                       new InterpreterConfiguration(
                           "",
                           view.Description,
                           view.PrefixPath,
                           view.InterpreterPath,
                           view.WindowsInterpreterPath,
                           view.PathEnvironmentVariable,
                           InterpreterArchitecture.TryParse(view.ArchitectureName ?? ""),
                           version
                           )
                       ));
        }
 private static string GetInterpreterId(InterpreterArchitecture arch) {
     if (arch == InterpreterArchitecture.x64) {
         return "IronPython|2.7-64";
     } else {
         return "IronPython|2.7-32";
     }
 }
        internal static InterpreterConfiguration GetConfiguration(InterpreterArchitecture arch)
        {
            var prefixPath = IronPythonResolver.GetPythonInstallDir();

            if (string.IsNullOrEmpty(prefixPath))
            {
                return(null);
            }

            // IronPython 2.7.8 changed the executable names for 64-bit vs 32-bit
            var ipyExe  = arch == InterpreterArchitecture.x64 ? "ipy64.exe" : "ipy.exe";
            var ipywExe = arch == InterpreterArchitecture.x64 ? "ipyw64.exe" : "ipyw.exe";

            if (File.Exists(Path.Combine(prefixPath, "ipy32.exe")))
            {
                ipyExe  = arch == InterpreterArchitecture.x64 ? "ipy.exe" : "ipy32.exe";
                ipywExe = arch == InterpreterArchitecture.x64 ? "ipyw.exe" : "ipyw32.exe";
            }

            return(new InterpreterConfiguration(
                       GetInterpreterId(arch),
                       string.Format("IronPython 2.7{0: ()}", arch),
                       prefixPath,
                       Path.Combine(prefixPath, ipyExe),
                       Path.Combine(prefixPath, ipywExe),
                       "IRONPYTHONPATH",
                       arch,
                       new Version(2, 7),
                       InterpreterUIMode.SupportsDatabase
                       ));
        }
 public InterpreterConfiguration GetPythonConfiguration(string prefix, InterpreterArchitecture architecture, Version version)
 {
     return(_registryCache.FirstOrDefault(configuration =>
                                          configuration.Id.StartsWith(prefix) &&
                                          configuration.Architecture == architecture &&
                                          configuration.Version == version));
 }
 private static InterpreterFactoryCreationOptions GetCreationOptions(InterpreterArchitecture arch) {
     return new InterpreterFactoryCreationOptions {
         PackageManager = BuiltInPackageManagers.PipXFrames,
         DatabasePath = Path.Combine(
             PythonTypeDatabase.CompletionDatabasePath,
             InterpreterFactoryCreator.GetRelativePathForConfigurationId(GetInterpreterId(arch))
         )
     };
 }
 private static InterpreterFactoryCreationOptions GetCreationOptions(InterpreterArchitecture arch)
 {
     return(new InterpreterFactoryCreationOptions {
         PackageManager = BuiltInPackageManagers.PipXFrames,
         DatabasePath = Path.Combine(
             PythonTypeDatabase.CompletionDatabasePath,
             InterpreterFactoryCreator.GetRelativePathForConfigurationId(GetInterpreterId(arch))
             )
     });
 }
 private static string GetInterpreterId(InterpreterArchitecture arch)
 {
     if (arch == InterpreterArchitecture.x64)
     {
         return("IronPython|2.7-64");
     }
     else
     {
         return("IronPython|2.7-32");
     }
 }
Пример #9
0
        public bool IsConfigurationChanged(ConfigurationEnvironmentView view)
        {
            var factory = view.EnvironmentView.Factory;

            return(view.Description != factory.Configuration.Description ||
                   view.PrefixPath != factory.Configuration.PrefixPath ||
                   view.InterpreterPath != factory.Configuration.InterpreterPath ||
                   view.WindowsInterpreterPath != factory.Configuration.WindowsInterpreterPath ||
                   view.PathEnvironmentVariable != factory.Configuration.PathEnvironmentVariable ||
                   InterpreterArchitecture.TryParse(view.ArchitectureName) != factory.Configuration.Architecture ||
                   view.VersionName != factory.Configuration.Version.ToString());
        }
Пример #10
0
 internal static InterpreterConfiguration GetConfiguration(InterpreterArchitecture arch) {
     var prefixPath = IronPythonResolver.GetPythonInstallDir();
     return new InterpreterConfiguration(
         GetInterpreterId(arch),
         string.Format("IronPython 2.7{0: ()}", arch),
         prefixPath,
         Path.Combine(prefixPath, arch == InterpreterArchitecture.x64 ? "ipy64.exe" : "ipy.exe"),
         Path.Combine(prefixPath, arch == InterpreterArchitecture.x64 ? "ipyw64.exe" : "ipyw.exe"),
         "IRONPYTHONPATH",
         arch,
         new Version(2, 7),
         InterpreterUIMode.SupportsDatabase
     );
 }
        /// <summary>
        /// Reconstructs an interpreter configuration from a dictionary.
        /// </summary>
        public static VisualStudioInterpreterConfiguration CreateFromDictionary(Dictionary <string, object> properties)
        {
            var id                      = Read(properties, nameof(InterpreterConfiguration.Id));
            var description             = Read(properties, nameof(InterpreterConfiguration.Description)) ?? "";
            var prefixPath              = Read(properties, nameof(PrefixPath));
            var interpreterPath         = Read(properties, nameof(InterpreterConfiguration.InterpreterPath));
            var windowsInterpreterPath  = Read(properties, nameof(WindowsInterpreterPath));
            var pathEnvironmentVariable = Read(properties, nameof(InterpreterConfiguration.PathEnvironmentVariable));
            var architecture            = InterpreterArchitecture.TryParse(Read(properties, nameof(InterpreterConfiguration.Architecture)));

            var version = default(Version);

            try
            {
                version = Version.Parse(Read(properties, nameof(Version)));
            }
            catch (Exception ex) when(ex is ArgumentException || ex is FormatException)
            {
                version = new Version();
            }

            InterpreterUIMode uiMode = 0;

            foreach (var bit in (Read(properties, nameof(UIMode)) ?? "").Split('|'))
            {
                if (Enum.TryParse(bit, out InterpreterUIMode m))
                {
                    uiMode |= m;
                }
            }

            VisualStudioInterpreterConfiguration configuration = new VisualStudioInterpreterConfiguration(id, description, prefixPath, interpreterPath, windowsInterpreterPath, pathEnvironmentVariable, architecture, version, uiMode);

            if (properties.TryGetValue(nameof(InterpreterConfiguration.SearchPaths), out object o))
            {
                configuration.SearchPaths.Clear();
                switch (o)
                {
                case string s:
                    configuration.SearchPaths.AddRange(s.Split(';'));
                    break;

                case IEnumerable <string> ss:
                    configuration.SearchPaths.AddRange(ss);
                    break;
                }
            }

            return(configuration);
        }
Пример #12
0
        internal static InterpreterConfiguration GetConfiguration(InterpreterArchitecture arch)
        {
            var prefixPath = IronPythonResolver.GetPythonInstallDir();

            return(new InterpreterConfiguration(
                       GetInterpreterId(arch),
                       string.Format("IronPython 2.7{0: ()}", arch),
                       prefixPath,
                       Path.Combine(prefixPath, arch == InterpreterArchitecture.x64 ? "ipy64.exe" : "ipy.exe"),
                       Path.Combine(prefixPath, arch == InterpreterArchitecture.x64 ? "ipyw64.exe" : "ipyw.exe"),
                       "IRONPYTHONPATH",
                       arch,
                       new Version(2, 7),
                       InterpreterUIMode.SupportsDatabase
                       ));
        }
 public VisualStudioInterpreterConfiguration(
     string id,
     string description,
     string prefixPath    = null,
     string pythonExePath = null,
     string winPath       = "",
     string pathVar       = "",
     InterpreterArchitecture architecture = default(InterpreterArchitecture),
     Version version          = null,
     InterpreterUIMode uiMode = InterpreterUIMode.Normal
     ) : base(id, description, pythonExePath, pathVar, string.Empty, string.Empty, architecture, version)
 {
     PrefixPath             = prefixPath;
     WindowsInterpreterPath = string.IsNullOrEmpty(winPath) ? pythonExePath : winPath;
     UIMode = uiMode;
 }
Пример #14
0
        public void Search(RegistryKey root, InterpreterArchitecture assumedArch) {
            if (root == null) {
                return;
            }

            var companies = GetSubkeys(root);
            foreach (var company in companies) {
                if ("PyLauncher".Equals(company, StringComparison.OrdinalIgnoreCase)) {
                    continue;
                }
                bool pythonCore = PythonCoreCompany.Equals(company, StringComparison.OrdinalIgnoreCase);

                using (var companyKey = root.OpenSubKey(company)) {
                    if (companyKey == null) {
                        continue;
                    }

                    var companyDisplay = companyKey.GetValue("DisplayName") as string;
                    var companySupportUrl = companyKey.GetValue("SupportUrl") as string;

                    if (pythonCore) {
                        companyDisplay = companyDisplay ?? PythonCoreCompanyDisplayName;
                        companySupportUrl = companySupportUrl ?? PythonCoreSupportUrl;
                    } else {
                        companyDisplay = companyDisplay ?? company;
                    }

                    var tags = GetSubkeys(companyKey);
                    foreach (var tag in tags) {
                        using (var tagKey = companyKey.OpenSubKey(tag))
                        using (var installKey = tagKey?.OpenSubKey("InstallPath")) {
                            var config = TryReadConfiguration(company, tag, tagKey, installKey, pythonCore, assumedArch);
                            if (config == null) {
                                continue;
                            }

                            if (_seenIds.Add(config.Id)) {
                                var supportUrl = tagKey.GetValue("SupportUrl") as string ?? companySupportUrl;

                                var info = new PythonInterpreterInformation(config, companyDisplay, companySupportUrl, supportUrl);
                                _info.Add(info);
                            }
                        }
                    }
                }
            }
        }
Пример #15
0
 /// <summary>
 /// <para>Constructs a new interpreter configuration based on the
 /// provided values.</para>
 /// <para>No validation is performed on the parameters.</para>
 /// <para>If winPath is null or empty,
 /// <see cref="WindowsInterpreterPath"/> will be set to path.</para>
 /// </summary>
 public InterpreterConfiguration(
     string id,
     string description,
     string prefixPath = null,
     string path = null,
     string winPath = "",
     string pathVar = "",
     InterpreterArchitecture arch = default(InterpreterArchitecture),
     Version version = null
 ) {
     Id = id;
     Description = description;
     PrefixPath = prefixPath;
     InterpreterPath = path;
     WindowsInterpreterPath = string.IsNullOrEmpty(winPath) ? path : winPath;
     PathEnvironmentVariable = pathVar;
     Architecture = arch ?? InterpreterArchitecture.Unknown;
     Version = version ?? new Version();
 }
Пример #16
0
 public NotFoundInterpreterFactory(
     string id,
     Version version,
     string description = null,
     string prefixPath = null,
     InterpreterArchitecture architecture = default(InterpreterArchitecture),
     string descriptionSuffix = null) {
     Configuration = new InterpreterConfiguration(
         id,
         description ?? "Unknown Python {0}{1: ()} (unavailable)".FormatUI(version, architecture),
         prefixPath,
         null,
         null,
         null,
         architecture,
         version,
         InterpreterUIMode.CannotBeDefault | InterpreterUIMode.CannotBeConfigured
     );
 }
Пример #17
0
 /// <summary>
 /// <para>Constructs a new interpreter configuration based on the
 /// provided values.</para>
 /// <para>No validation is performed on the parameters.</para>
 /// <para>If winPath is null or empty,
 /// <see cref="WindowsInterpreterPath"/> will be set to path.</para>
 /// </summary>
 public InterpreterConfiguration(
     string id,
     string description,
     string prefixPath            = null,
     string path                  = null,
     string winPath               = "",
     string pathVar               = "",
     InterpreterArchitecture arch = default(InterpreterArchitecture),
     Version version              = null
     )
 {
     Id                      = id;
     Description             = description;
     PrefixPath              = prefixPath;
     InterpreterPath         = path;
     WindowsInterpreterPath  = string.IsNullOrEmpty(winPath) ? path : winPath;
     PathEnvironmentVariable = pathVar;
     Architecture            = arch ?? InterpreterArchitecture.Unknown;
     Version                 = version ?? new Version();
 }
Пример #18
0
        public static async Task <IPythonInterpreterFactory> CreateCustomEnv(
            IInterpreterRegistryService registryService,
            IInterpreterOptionsService optionsService,
            string prefixPath,
            string interpreterPath,
            string windowsInterpreterPath,
            string pathEnvironmentVariable,
            InterpreterArchitecture architecture,
            Version version,
            string description
            )
        {
            if (registryService == null)
            {
                throw new ArgumentNullException(nameof(registryService));
            }

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

            var id = optionsService.AddConfigurableInterpreter(
                description,
                new InterpreterConfiguration(
                    "", // ignored - id is generated and returned by AddConfigurableInterpreter
                    description,
                    prefixPath,
                    interpreterPath,
                    windowsInterpreterPath,
                    pathEnvironmentVariable,
                    architecture,
                    version
                    )
                );

            return(registryService.FindInterpreter(id));
        }
Пример #19
0
        public void ApplyConfiguration(ConfigurationEnvironmentView view)
        {
            var factory = view.EnvironmentView.Factory;

            if (view.Description != factory.Configuration.Description)
            {
                // We're renaming the interpreter, remove the old one...
                _interpreterOptions.RemoveConfigurableInterpreter(factory.Configuration.Id);
            }

            var newInterp = _interpreterOptions.AddConfigurableInterpreter(
                view.Description,
                new InterpreterConfiguration(
                    "",
                    view.Description,
                    view.PrefixPath,
                    view.InterpreterPath,
                    view.WindowsInterpreterPath,
                    view.PathEnvironmentVariable,
                    InterpreterArchitecture.TryParse(view.ArchitectureName),
                    Version.Parse(view.VersionName)
                    )
                );
        }
Пример #20
0
        private void AddPythonConfigurationsFromRegistry(List <InterpreterConfiguration> configurations, RegistryKey key, InterpreterArchitecture assumedArchitecture)
        {
            if (key == null)
            {
                return;
            }

            var companies = key.GetSubKeyNames();

            foreach (var company in companies)
            {
                if ("PyLauncher".Equals(company, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                using (var companyKey = key.OpenSubKey(company)) {
                    if (companyKey == null)
                    {
                        continue;
                    }

                    var tags = companyKey.GetSubKeyNames();
                    foreach (var tag in tags)
                    {
                        using (var tagKey = companyKey.OpenSubKey(tag))
                            using (var installKey = tagKey?.OpenSubKey("InstallPath")) {
                                var config = TryReadConfiguration(company, tag, tagKey, installKey, assumedArchitecture);
                                if (config != null)
                                {
                                    configurations.Add(config);
                                }
                            }
                    }
                }
            }
        }
Пример #21
0
        private InterpreterConfiguration TryReadConfiguration(
            string company,
            string tag,
            RegistryKey tagKey,
            RegistryKey installKey,
            InterpreterArchitecture assumedArchitecture
            )
        {
            if (tagKey == null || installKey == null)
            {
                return(null);
            }

            var pythonCoreCompatibility = "PythonCore".Equals(company, StringComparison.OrdinalIgnoreCase);
            var prefixPath = PathUtils.NormalizePath(installKey.GetValue(null) as string);
            var exePath    = PathUtils.NormalizePath(installKey.GetValue("ExecutablePath") as string);


            if (pythonCoreCompatibility && !string.IsNullOrEmpty(prefixPath))
            {
                if (string.IsNullOrEmpty(exePath))
                {
                    try {
                        exePath = Python.Tests.Utilities.PathUtils.GetAbsoluteFilePath(prefixPath, "python.exe");
                    } catch (ArgumentException) {
                    }
                }
            }

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

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

            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 var sysVersion))
            {
                sysVersion = new Version(0, 0);
            }

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

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

                case ProcessorArchitecture.Amd64:
                    architecture = InterpreterArchitecture.x64;
                    break;
                }
            }

            if (pythonCoreCompatibility && sysVersion != null && sysVersion < new Version(3, 5) && architecture == 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 ?? "PYTHONPATH";
            var id      = $"Global|{company}|{tag}";

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

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

            return(new InterpreterConfiguration(
                       id: id,
                       description: description,
                       interpreterPath: exePath,
                       pathVar: pathVar,
                       libPath: Path.Combine(prefixPath, "Lib"),
                       sitePackagesPath: Path.Combine(prefixPath, "Lib", "site-packages"),
                       architecture: architecture,
                       version: sysVersion
                       ));
        }
Пример #22
0
 private static InterpreterConfiguration GetAnacondaVersion(PythonLanguageVersion version, InterpreterArchitecture arch)
 => PythonInstallPathResolver.Instance.GetCondaPythonConfiguration(arch, version.ToVersion());
Пример #23
0
        public void Search(RegistryKey root, InterpreterArchitecture assumedArch)
        {
            if (root == null)
            {
                return;
            }

            var companies = GetSubkeys(root).Union(StoreAppCompanies);

            foreach (var company in companies)
            {
                if ("PyLauncher".Equals(company, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                bool pythonCore = PythonCoreCompany.Equals(company, StringComparison.OrdinalIgnoreCase);

                using (var companyKey = root.OpenSubKey(company))
                {
                    if (companyKey == null)
                    {
                        continue;
                    }

                    var companyDisplay    = companyKey.GetValue("DisplayName") as string;
                    var companySupportUrl = companyKey.GetValue("SupportUrl") as string;

                    if (pythonCore)
                    {
                        companyDisplay    = companyDisplay ?? PythonCoreCompanyDisplayName;
                        companySupportUrl = companySupportUrl ?? PythonCoreSupportUrl;
                    }
                    else
                    {
                        companyDisplay = companyDisplay ?? company;
                    }

                    var tags = GetSubkeys(companyKey).Union(StoreAppTags);
                    foreach (var tag in tags)
                    {
                        using (var tagKey = companyKey.OpenSubKey(tag))
                            using (var installKey = tagKey?.OpenSubKey("InstallPath"))
                            {
                                VisualStudioInterpreterConfiguration config = TryReadConfiguration(company, tag, tagKey, installKey, pythonCore, assumedArch);
                                if (config == null)
                                {
                                    continue;
                                }

                                if (_seenIds.Add(config.Id))
                                {
                                    var supportUrl = tagKey.GetValue("SupportUrl") as string ?? companySupportUrl;

                                    // We don't want to send people to http://python.org, even
                                    // if that's what is in the registry, so catch and fix it.
                                    if (!string.IsNullOrEmpty(supportUrl))
                                    {
                                        var url = supportUrl.TrimEnd('/');
                                        if (url.Equals("http://www.python.org", StringComparison.OrdinalIgnoreCase) ||
                                            url.Equals("http://python.org", StringComparison.OrdinalIgnoreCase))
                                        {
                                            supportUrl = PythonCoreSupportUrl;
                                        }
                                    }

                                    PythonInterpreterInformation info = new PythonInterpreterInformation(config, companyDisplay, companySupportUrl, supportUrl);
                                    _info.Add(info);
                                }
                            }
                    }
                }
            }

            InterpreterConfiguration.DisambiguateDescriptions(_info.Select(i => i.Configuration).ToArray());
        }
Пример #24
0
        private static void AnalyzeCode(
            out PythonAnalyzer analyzer,
            out IPythonProjectEntry entry,
            string code,
            Version preferredVersion = null,
            InterpreterArchitecture preferredArch = null,
            string module = "test-module"
        ) {
            var provider = InterpFactory;
            var factory = provider.GetInterpreterFactories().OrderByDescending(f => f.Configuration.Version)
                .Where(f => preferredVersion == null || f.Configuration.Version == preferredVersion)
                .Where(f => preferredArch == null || f.Configuration.Architecture == preferredArch)
                .FirstOrDefault();
            Assert.IsNotNull(factory, "no factory found");

            analyzer = PythonAnalyzer.CreateSynchronously(factory);
            var path = Path.Combine(TestData.GetTempPath(randomSubPath: true), module.Replace('.', '\\'));
            Directory.CreateDirectory(PathUtils.GetParent(path));
            File.WriteAllText(path, code);

            entry = analyzer.AddModule(module, path);
            PythonAst ast;
            using (var p = Parser.CreateParser(new StringReader(code), factory.GetLanguageVersion())) {
                ast = p.ParseFile();
                entry.UpdateTree(ast, null);
            }

            entry.Analyze(CancellationToken.None, true);
        }
Пример #25
0
 private static InterpreterConfiguration GetCPythonVersion(PythonLanguageVersion version, InterpreterArchitecture arch)
 {
     return(PythonInstallPathResolver.Instance.GetPythonConfiguration("Global|PythonCore|", arch, version.ToVersion()));
 }
Пример #26
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 InterpreterConfiguration(
                        CPythonInterpreterFactoryConstants.GetInterpreterId("PythonCore", tag),
                        "Python {0} {1}".FormatInvariant(arch, ver),
                        prefixPath,
                        exePath,
                        pathVar: CPythonInterpreterFactoryConstants.PathEnvironmentVariableName,
                        arch: arch,
                        version: ver
                    ));
                }
            }
            return null;
        }
Пример #27
0
 private static InterpreterConfiguration GetAnacondaVersion(PythonLanguageVersion version, InterpreterArchitecture arch)
 {
     return(PythonInstallPathResolver.Instance.GetPythonConfiguration("Global|ContinuumAnalytics|", arch, version.ToVersion()));
 }
Пример #28
0
 public IronPythonInterpreterFactory(InterpreterArchitecture arch)
     : base(GetConfiguration(arch), GetCreationOptions(arch)) { }
Пример #29
0
        private static PythonVersion GetAnacondaVersion(PythonLanguageVersion version, InterpreterArchitecture arch)
        {
            var res = _foundInRegistry.FirstOrDefault(ii =>
                                                      ii.Configuration.Id.StartsWith("Global|ContinuumAnalytics|") &&
                                                      ii.Configuration.Architecture == arch &&
                                                      ii.Configuration.Version == version.ToVersion()
                                                      );

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

            return(null);
        }
Пример #30
0
 public InterpreterConfiguration GetCorePythonConfiguration(InterpreterArchitecture architecture, Version version)
 => GetPythonConfiguration("Global|PythonCore|", architecture, version);
Пример #31
0
        private InterpreterConfiguration TryReadConfiguration(
            string company,
            string tag,
            RegistryKey tagKey,
            RegistryKey installKey,
            bool pythonCoreCompatibility,
            InterpreterArchitecture assumedArch
        ) {
            if (tagKey == null || installKey == null) {
                return null;
            }

            var prefixPath = PathUtils.NormalizePath(installKey.GetValue(null) as string);
            var exePath = PathUtils.NormalizePath(installKey.GetValue("ExecutablePath") as string);
            var exewPath = PathUtils.NormalizePath(installKey.GetValue("WindowedExecutablePath") as string);
            if (pythonCoreCompatibility && !string.IsNullOrEmpty(prefixPath)) {
                if (string.IsNullOrEmpty(exePath)) {
                    exePath = PathUtils.GetAbsoluteFilePath(prefixPath, CPythonInterpreterFactoryConstants.ConsoleExecutable);
                }
                if (string.IsNullOrEmpty(exewPath)) {
                    exewPath = PathUtils.GetAbsoluteFilePath(prefixPath, CPythonInterpreterFactoryConstants.WindowsExecutable);
                }
            }

            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);
            }

            InterpreterArchitecture arch;
            if (!InterpreterArchitecture.TryParse(tagKey.GetValue("SysArchitecture", null) as string, out 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 InterpreterConfiguration(
                id,
                description,
                prefixPath,
                exePath,
                exewPath,
                pathVar,
                arch,
                sysVersion
            );
        }
Пример #32
0
 public IronPythonInterpreterFactory(InterpreterArchitecture arch)
     : base(GetConfiguration(arch), GetCreationOptions(arch))
 {
 }
Пример #33
0
 public InterpreterConfiguration GetCondaPythonConfiguration(InterpreterArchitecture architecture, Version version)
 => GetPythonConfiguration("Global|ContinuumAnalytics|", architecture, version);
Пример #34
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
                       ));
        }
Пример #35
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);
        }
        private async Task ApplyCustomAsync()
        {
            IPythonInterpreterFactory factory = null;

            if (RegisterCustomEnv)
            {
                Version version;
                if (!Version.TryParse(VersionName, out version))
                {
                    version = null;
                }

                factory = await CustomEnv.CreateCustomEnv(
                    RegistryService,
                    OptionsService,
                    PrefixPath,
                    InterpreterPath,
                    WindowsInterpreterPath,
                    PathEnvironmentVariable,
                    InterpreterArchitecture.TryParse(ArchitectureName ?? ""),
                    version,
                    Description
                    );
            }
            else
            {
                Debug.Assert(SelectedProject != null, "Project is null, UI should not have allowed this");
                if (SelectedProject != null)
                {
                    Version version;
                    if (!Version.TryParse(VersionName, out version))
                    {
                        version = null;
                    }

                    if (SelectedProject.Node != null)
                    {
                        factory = SelectedProject.Node.AddMSBuildEnvironment(
                            RegistryService,
                            PrefixPath,
                            InterpreterPath,
                            WindowsInterpreterPath,
                            PathEnvironmentVariable,
                            version,
                            InterpreterArchitecture.TryParse(ArchitectureName ?? ""),
                            Description
                            );
                    }
                    else if (SelectedProject.Workspace != null)
                    {
                        await SelectedProject.Workspace.SetInterpreterAsync(InterpreterPath);
                    }
                }
            }

            if (factory != null)
            {
                if (SelectedProject != null)
                {
                    if (SelectedProject.Node != null)
                    {
                        SelectedProject.Node.AddInterpreter(factory.Configuration.Id);
                        if (SetAsCurrent)
                        {
                            SelectedProject.Node.SetInterpreterFactory(factory);
                        }
                    }
                    else if (SelectedProject.Workspace != null)
                    {
                        await SelectedProject.Workspace.SetInterpreterFactoryAsync(factory);
                    }
                }

                if (SetAsDefault)
                {
                    OptionsService.DefaultInterpreter = factory;
                }
            }
        }
Пример #37
0
        private async Task <ConfigurationValues> AutoDetectAsync(ConfigurationValues view)
        {
            if (!Directory.Exists(view.PrefixPath))
            {
                if (File.Exists(view.InterpreterPath))
                {
                    view.PrefixPath = Path.GetDirectoryName(view.InterpreterPath);
                }
                else if (File.Exists(view.WindowsInterpreterPath))
                {
                    view.PrefixPath = Path.GetDirectoryName(view.WindowsInterpreterPath);
                }
                else
                {
                    // Don't have enough information, so abort without changing
                    // any settings.
                    return(view);
                }
                while (Directory.Exists(view.PrefixPath) && !File.Exists(PathUtils.FindFile(view.PrefixPath, "site.py")))
                {
                    view.PrefixPath = Path.GetDirectoryName(view.PrefixPath);
                }
            }

            if (!Directory.Exists(view.PrefixPath))
            {
                // If view.PrefixPath is not valid by this point, we can't find anything
                // else, so abort withou changing any settings.
                return(view);
            }

            if (string.IsNullOrEmpty(view.Description))
            {
                view.Description = PathUtils.GetFileOrDirectoryName(view.PrefixPath);
            }

            if (!File.Exists(view.InterpreterPath))
            {
                view.InterpreterPath = PathUtils.FindFile(
                    view.PrefixPath,
                    CPythonInterpreterFactoryConstants.ConsoleExecutable,
                    firstCheck: new[] { "scripts" }
                    );
            }
            if (!File.Exists(view.WindowsInterpreterPath))
            {
                view.WindowsInterpreterPath = PathUtils.FindFile(
                    view.PrefixPath,
                    CPythonInterpreterFactoryConstants.WindowsExecutable,
                    firstCheck: new[] { "scripts" }
                    );
            }

            if (File.Exists(view.InterpreterPath))
            {
                using (var output = ProcessOutput.RunHiddenAndCapture(
                           view.InterpreterPath, "-c", "import sys; print('%s.%s' % (sys.version_info[0], sys.version_info[1]))"
                           )) {
                    var exitCode = await output;
                    if (exitCode == 0)
                    {
                        view.VersionName = output.StandardOutputLines.FirstOrDefault() ?? view.VersionName;
                    }
                }

                var arch = InterpreterArchitecture.FromExe(view.InterpreterPath);
                if (arch != InterpreterArchitecture.Unknown)
                {
                    view.ArchitectureName = arch.ToString();
                }
            }

            return(view);
        }
Пример #38
0
 private InterpreterConfiguration GetPythonConfiguration(string prefix, InterpreterArchitecture architecture, Version version)
 => _registryCache.FirstOrDefault(configuration =>
                                  configuration.Architecture == architecture &&
                                  configuration.Version == version);
Пример #39
0
        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);
        }
 public InterpreterConfiguration GetCondaPythonConfiguration(InterpreterArchitecture architecture, Version version)
 => architecture == InterpreterArchitecture.x86 ? null : _condaCache.TryGetValue(version, out var interpreterConfiguration) ? interpreterConfiguration : null;