public void Save()
 {
     _interpreterOptions.DefaultInterpreter =
         _interpreters.FindInterpreter(DefaultInterpreter);
     _interpreters.Interpreters.LastOrDefault();
     DefaultInterpreter        = _interpreterOptions.DefaultInterpreter.Configuration.Id;
     DefaultInterpreterVersion = _interpreterOptions.DefaultInterpreter.Configuration.Version;
 }
Beispiel #2
0
 public void Save()
 {
     _interpreterOptions.DefaultInterpreter =
         _interpreters.FindInterpreter(DefaultInterpreter);
     _interpreters.Interpreters.LastOrDefault();
     DefaultInterpreter        = _interpreterOptions.DefaultInterpreter.Configuration.Id;
     DefaultInterpreterVersion = _interpreterOptions.DefaultInterpreter.Configuration.Version;
     Changed?.Invoke(this, EventArgs.Empty);
 }
Beispiel #3
0
        /// <summary>
        /// <para>Gets a shared analyzer for a given environment.</para>
        /// <para>When the analyzer is no longer required, call
        /// <see cref="VsProjectAnalyzer.RemoveUser"/> and if it returns
        /// <c>true</c>, call <see cref="VsProjectAnalyzer.Dispose"/>.</para>
        /// </summary>
        internal async Task <VsProjectAnalyzer> GetSharedAnalyzerAsync(IPythonInterpreterFactory factory = null)
        {
            var result = TryGetSharedAnalyzer(factory, out var id);

            if (result != null)
            {
                return(result);
            }

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

            factory = factory ?? InterpreterRegistryService.FindInterpreter(id);
            result  = await CreateAnalyzerAsync(factory);

            var realResult = _analyzers.GetOrAdd(id, result);

            if (realResult != result && result.RemoveUser())
            {
                result.Dispose();
            }
            return(realResult);
        }
        public static IPythonReplEvaluator Create(
            IServiceProvider serviceProvider,
            string id,
            IInterpreterRegistryService interpreterService
            )
        {
            var factory = interpreterService.FindInterpreter(id);

            if (factory == null)
            {
                try {
                    factory = new UnavailableFactory(id);
                } catch (FormatException) {
                    return(null);
                }
            }
            return(new PythonReplEvaluator(factory, serviceProvider, interpreterService));
        }
        /// <summary>
        /// Creates an interactive evaluator programmatically for some plugin
        /// </summary>
        private IInteractiveEvaluator CreateConfigurableEvaluator(string replId)
        {
            string[] components = replId.Split(new[] { '|' }, 2);
            if (components.Length == 2)
            {
                string interpreter = components[1];

                var factory = _interpreterService.FindInterpreter(interpreter);

                if (factory != null)
                {
                    var replOptions = new ConfigurablePythonReplOptions();
                    replOptions.InterpreterFactory = factory;

                    if (interpreter.StartsWith(MSBuildProjectInterpreterFactoryProvider.MSBuildProviderName + "|"))
                    {
                        string[] projectComponents = interpreter.Split(new[] { '|' }, 3);
                        string   projectName       = projectComponents[2];

                        var solution = _serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
                        if (solution != null)
                        {
                            foreach (var pyProj in solution.EnumerateLoadedPythonProjects())
                            {
                                var name = ((IVsHierarchy)pyProj).GetRootCanonicalName();
                                if (string.Equals(name, projectName, StringComparison.OrdinalIgnoreCase))
                                {
                                    replOptions.Project = pyProj;
                                    break;
                                }
                            }
                        }
                    }

                    return(new PythonReplEvaluatorDontPersist(
                               replOptions.InterpreterFactory,
                               _serviceProvider,
                               replOptions,
                               _interpreterService
                               ));
                }
            }
            return(null);
        }
        private static IPythonInterpreterFactory GetFactory(string interpreter, IWorkspace workspace, IInterpreterRegistryService registryService)
        {
            IPythonInterpreterFactory factory = null;

            if (interpreter != null && registryService != null)
            {
                factory = registryService.FindInterpreter(interpreter);
                if (factory == null)
                {
                    if (PathUtils.IsValidPath(interpreter) && !Path.IsPathRooted(interpreter))
                    {
                        interpreter = workspace.MakeRooted(interpreter);
                    }
                    factory = registryService.Interpreters.SingleOrDefault(f => PathUtils.IsSamePath(f.Configuration.InterpreterPath, interpreter));
                }
            }

            return(factory);
        }
Beispiel #7
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));
        }
Beispiel #8
0
        public static IPythonInterpreterFactory GetInterpreterFactory(this IWorkspace workspace, IInterpreterRegistryService registryService, IInterpreterOptionsService optionsService)
        {
            if (workspace == null)
            {
                throw new ArgumentNullException(nameof(workspace));
            }

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

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

            var interpreter = workspace.GetInterpreter();

            IPythonInterpreterFactory factory = null;

            if (interpreter != null)
            {
                factory = registryService.FindInterpreter(interpreter);
                if (factory == null)
                {
                    if (PathUtils.IsValidPath(interpreter) && !Path.IsPathRooted(interpreter))
                    {
                        interpreter = workspace.MakeRooted(interpreter);
                    }
                    factory = registryService.Interpreters.SingleOrDefault(f => PathUtils.IsSamePath(f.Configuration.InterpreterPath, interpreter));
                }
            }

            return(factory ?? optionsService.DefaultInterpreter);
        }
Beispiel #9
0
        private async Task CreateVirtualEnvironmentAsync(ITaskHandler taskHandler)
        {
            IPythonInterpreterFactory factory = null;

            bool failed     = true;
            var  baseInterp = _registry.FindInterpreter(_baseInterpreter);

            try {
                factory = await VirtualEnv.CreateAndAddFactory(
                    _site,
                    _registry,
                    _options,
                    _project,
                    _workspace,
                    _virtualEnvPath,
                    baseInterp,
                    _registerAsCustomEnv,
                    _customEnvName,
                    _useVEnv
                    );

                if (factory != null)
                {
                    if (_installReqs && File.Exists(_reqsPath))
                    {
                        await InstallPackagesAsync(taskHandler, factory);
                    }

                    await _site.GetUIThread().InvokeTask(async() => {
                        // Note that for a workspace, VirtualEnv.CreateAndAddFactory
                        // takes care of updating PythonSettings.json, as that is
                        // required in order to obtain the factory. So no need to do
                        // anything here for workspace.
                        if (_project != null)
                        {
                            _project.AddInterpreter(factory.Configuration.Id);
                            if (_setAsCurrent)
                            {
                                _project.SetInterpreterFactory(factory);
                            }
                        }

                        if (_setAsDefault && _options != null)
                        {
                            _options.DefaultInterpreter = factory;
                        }

                        if (_viewInEnvWindow)
                        {
                            await InterpreterListToolWindow.OpenAtAsync(_site, factory);
                        }
                    });
                }

                failed = false;
            } finally {
                _logger?.LogEvent(PythonLogEvent.CreateVirtualEnv, new CreateVirtualEnvInfo()
                {
                    Failed = failed,
                    InstallRequirements = _installReqs,
                    UseVEnv             = _useVEnv,
                    Global                 = _registerAsCustomEnv,
                    LanguageVersion        = baseInterp?.Configuration?.Version.ToString() ?? "",
                    Architecture           = baseInterp?.Configuration?.ArchitectureString ?? "",
                    SetAsDefault           = _setAsDefault,
                    SetAsCurrent           = _setAsCurrent,
                    OpenEnvironmentsWindow = _viewInEnvWindow,
                });
            }

            taskHandler?.Progress.Report(new TaskProgressData()
            {
                CanBeCanceled   = false,
                ProgressText    = Strings.VirtualEnvStatusCenterCreateProgressCompleted,
                PercentComplete = 100,
            });
        }
Beispiel #10
0
        private void RefreshCanCreateVirtualEnv(string path)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke((Action)(() => RefreshCanCreateVirtualEnv(path)));
                return;
            }

            if (Interpreters.Count == 0)
            {
                WillCreateVirtualEnv    = false;
                WillAddVirtualEnv       = false;
                CannotCreateVirtualEnv  = false;
                NoInterpretersInstalled = true;
                return;
            }

            if (!IsValidVirtualEnvPath(path) || BaseInterpreter == null)
            {
                WillCreateVirtualEnv    = false;
                WillAddVirtualEnv       = false;
                CannotCreateVirtualEnv  = true;
                NoInterpretersInstalled = false;
                return;
            }


            if (Directory.Exists(path) && Directory.EnumerateFileSystemEntries(path).Any())
            {
                WillCreateVirtualEnv = false;

                var config = VirtualEnv.FindInterpreterConfiguration(null, path, _interpreterService);
                if (config != null && File.Exists(config.InterpreterPath))
                {
                    var             baseInterp = _interpreterService.FindInterpreter(config.Id);
                    InterpreterView baseInterpView;
                    if (baseInterp != null &&
                        (baseInterpView = Interpreters.FirstOrDefault(iv => iv.Interpreter == baseInterp)) != null)
                    {
                        if (_lastUserSelectedBaseInterpreter == null)
                        {
                            _lastUserSelectedBaseInterpreter = BaseInterpreter;
                        }
                        BaseInterpreter   = baseInterpView;
                        WillAddVirtualEnv = true;
                    }
                    else
                    {
                        WillAddVirtualEnv = false;
                    }
                }
                else
                {
                    WillAddVirtualEnv = false;
                }
                CannotCreateVirtualEnv  = !WillAddVirtualEnv;
                NoInterpretersInstalled = false;
            }
            else
            {
                WillCreateVirtualEnv    = true;
                WillAddVirtualEnv       = false;
                CannotCreateVirtualEnv  = false;
                NoInterpretersInstalled = false;
                if (_lastUserSelectedBaseInterpreter != null)
                {
                    BaseInterpreter = _lastUserSelectedBaseInterpreter;
                    _lastUserSelectedBaseInterpreter = null;
                }
            }
        }
Beispiel #11
0
        public void DiscoverTests(IEnumerable <string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
        {
            ValidateArg.NotNull(sources, "sources");
            ValidateArg.NotNull(discoverySink, "discoverySink");

            var buildEngine = new MSBuild.ProjectCollection();

            try {
                var testExecutorContext = _container.GetExportedValue <TestExecutorProjectContext>();
                // Load all the test containers passed in (.pyproj msbuild files)
                foreach (string source in sources)
                {
                    testExecutorContext.AddContext(buildEngine.LoadProject(source));
                }

                foreach (var proj in buildEngine.LoadedProjects)
                {
                    var defaultInterpreter = proj.GetPropertyValue(MSBuildConstants.InterpreterIdProperty);
                    if (String.IsNullOrWhiteSpace(defaultInterpreter))
                    {
                        defaultInterpreter = _interpreterService.DefaultInterpreterId;
                    }
                    var factory = _interpreters.FindInterpreter(defaultInterpreter);
                    if (factory == null)
                    {
                        if (!_interpreters.Configurations.Any())
                        {
                            logger.SendMessage(TestMessageLevel.Warning, "No interpreters available for project " + proj.FullPath);
                        }
                        continue;
                    }

                    var projectHome = Path.GetFullPath(Path.Combine(proj.DirectoryPath, proj.GetPropertyValue(PythonConstants.ProjectHomeSetting) ?? "."));

                    // Do the analysis even if the database is not up to date. At
                    // worst, we'll get no results.
                    using (var analyzer = new TestAnalyzer(
                               factory,
                               proj.FullPath,
                               projectHome,
                               TestExecutor.ExecutorUri
                               )) {
                        // Provide all files to the test analyzer
                        foreach (var item in proj.GetItems("Compile"))
                        {
                            string fileAbsolutePath = CommonUtils.GetAbsoluteFilePath(projectHome, item.EvaluatedInclude);
                            string fullName;

                            try {
                                fullName = ModulePath.FromFullPath(fileAbsolutePath).ModuleName;
                            } catch (ArgumentException) {
                                if (logger != null)
                                {
                                    logger.SendMessage(TestMessageLevel.Warning, "File has an invalid module name: " + fileAbsolutePath);
                                }
                                continue;
                            }

                            try {
                                using (var reader = new StreamReader(fileAbsolutePath)) {
                                    analyzer.AddModule(fullName, fileAbsolutePath, reader);
                                }
                            } catch (FileNotFoundException) {
                                // user deleted file, we send the test update, but the project
                                // isn't saved.
#if DEBUG
                            } catch (Exception ex) {
                                if (logger != null)
                                {
                                    logger.SendMessage(TestMessageLevel.Warning, "Failed to discover tests in " + fileAbsolutePath);
                                    logger.SendMessage(TestMessageLevel.Informational, ex.ToString());
                                }
                            }
#else
                            } catch (Exception) {
                                if (logger != null)
                                {
                                    logger.SendMessage(TestMessageLevel.Warning, "Failed to discover tests in " + fileAbsolutePath);
                                }
                            }
#endif
                        }
Beispiel #12
0
        private static async Task <IPythonInterpreterFactory> TryGetCondaFactoryAsync(
            IPythonInterpreterFactory target,
            IInterpreterRegistryService service
            )
        {
            var condaMetaPath = PathUtils.GetAbsoluteDirectoryPath(
                target.Configuration.PrefixPath,
                "conda-meta"
                );

            if (!Directory.Exists(condaMetaPath))
            {
                return(null);
            }

            string metaFile;

            try {
                metaFile = Directory.EnumerateFiles(condaMetaPath, "*.json").FirstOrDefault();
            } catch (Exception ex) {
                if (ex.IsCriticalException())
                {
                    throw;
                }
                return(null);
            }

            if (!string.IsNullOrEmpty(metaFile))
            {
                string text = string.Empty;
                try {
                    text = File.ReadAllText(metaFile);
                } catch (Exception ex) {
                    if (ex.IsCriticalException())
                    {
                        throw;
                    }
                }

                var m = Regex.Match(text, @"\{[^{]+link.+?\{.+?""source""\s*:\s*""(.+?)""", RegexOptions.Singleline);
                if (m.Success)
                {
                    var pkg = m.Groups[1].Value;
                    if (!Directory.Exists(pkg))
                    {
                        return(null);
                    }

                    var prefix = Path.GetDirectoryName(Path.GetDirectoryName(pkg));
                    var config = service.Configurations.FirstOrDefault(
                        f => PathUtils.IsSameDirectory(f.PrefixPath, prefix)
                        );

                    IPythonInterpreterFactory factory = null;
                    if (config != null)
                    {
                        factory = service.FindInterpreter(config.Id);
                    }

                    if (factory != null && !(await factory.FindModulesAsync("conda")).Any())
                    {
                        factory = null;
                    }

                    return(factory);
                }
            }

            if ((await target.FindModulesAsync("conda")).Any())
            {
                return(target);
            }
            return(null);
        }
Beispiel #13
0
        private static async Task<IPythonInterpreterFactory> TryGetCondaFactoryAsync(
            IPythonInterpreterFactory target,
            IInterpreterRegistryService service
        ) {
            var condaMetaPath = PathUtils.GetAbsoluteDirectoryPath(
                target.Configuration.PrefixPath,
                "conda-meta"
            );

            if (!Directory.Exists(condaMetaPath)) {
                return null;
            }

            string metaFile;
            try {
                metaFile = PathUtils.EnumerateFiles(condaMetaPath, "*.json", recurse: false).FirstOrDefault();
            } catch (Exception ex) {
                if (ex.IsCriticalException()) {
                    throw;
                }
                return null;
            }

            if (!string.IsNullOrEmpty(metaFile)) {
                string text = string.Empty;
                try {
                    text = File.ReadAllText(metaFile);
                } catch (Exception ex) {
                    if (ex.IsCriticalException()) {
                        throw;
                    }
                }

                var m = Regex.Match(text, @"\{[^{]+link.+?\{.+?""source""\s*:\s*""(.+?)""", RegexOptions.Singleline);
                if (m.Success) {
                    var pkg = m.Groups[1].Value;
                    if (!Directory.Exists(pkg)) {
                        return null;
                    }

                    var prefix = Path.GetDirectoryName(Path.GetDirectoryName(pkg));
                    var config = service.Configurations.FirstOrDefault(
                        f => PathUtils.IsSameDirectory(f.PrefixPath, prefix)
                    );

                    IPythonInterpreterFactory factory = null;
                    if (config != null) {
                        factory = service.FindInterpreter(config.Id);
                    }

                    if (factory != null && !(await factory.FindModulesAsync("conda")).Any()) {
                        factory = null;
                    }

                    return factory;
                }
            }

            if ((await target.FindModulesAsync("conda")).Any()) {
                return target;
            }
            return null;
        }