private IPackageManager TryCreatePackageManager(IPythonInterpreterFactory factory)
        {
            if (factory == null)
            {
                return(null);
            }

            var prefixPath = factory.Configuration.GetPrefixPath();

            if (string.IsNullOrEmpty(prefixPath) ||
                !Directory.Exists(Path.Combine(prefixPath, "conda-meta")))
            {
                return(null);
            }

            var condaPath = CondaUtils.GetCondaExecutablePath(prefixPath);

            if (string.IsNullOrEmpty(condaPath))
            {
                // conda.bat is no longer present in a conda 4.4 environment,
                // so find a global conda.exe to use.
                condaPath = _latestCondaExe.Value;
            }

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

            try {
                return(new CondaPackageManager(factory, condaPath));
            } catch (NotSupportedException) {
                return(null);
            }
        }
Exemplo n.º 2
0
        private async Task <KeyValuePair <string, string>[]> GetEnvironmentVariables()
        {
            var prefixPath = _factory.Configuration.GetPrefixPath();

            if (_condaLocatorProvider != null && Directory.Exists(prefixPath) && CondaUtils.IsCondaEnvironment(prefixPath))
            {
                var rootConda = _condaLocatorProvider.FindLocator()?.CondaExecutablePath;
                if (File.Exists(rootConda))
                {
                    var env = await CondaUtils.GetActivationEnvironmentVariablesForPrefixAsync(rootConda, prefixPath);

                    return(env.Union(UnbufferedEnv).ToArray());
                }
                else
                {
                    // Normally, the root is required for this environment to have been discovered,
                    // but it could be that the user added this as a custom environment and then
                    // uninstalled the root. When that's the case, there is no way to activate,
                    // so proceed without activation env variables.
                    return(UnbufferedEnv);
                }
            }
            else
            {
                // Not a conda environment, no activation necessary.
                return(UnbufferedEnv);
            }
        }
Exemplo n.º 3
0
        public IEnumerable <IPackageManager> GetPackageManagers(IPythonInterpreterFactory factory)
        {
            if (ExperimentalOptions.UseCondaPackageManager)
            {
                if (!Directory.Exists(Path.Combine(factory.Configuration.PrefixPath, "conda-meta")))
                {
                    yield break;
                }

                var condaPath = CondaUtils.GetCondaExecutablePath(factory.Configuration.PrefixPath);
                if (string.IsNullOrEmpty(condaPath))
                {
                    // conda.bat is no longer present in a conda 4.4 environment,
                    // so find a global conda.exe to use.
                    condaPath = _latestCondaExe.Value;
                }

                if (string.IsNullOrEmpty(condaPath))
                {
                    yield break;
                }

                IPackageManager pm = null;
                try {
                    pm = new CondaPackageManager(factory, condaPath);
                } catch (NotSupportedException) {
                    pm = null;
                }
                if (pm != null)
                {
                    yield return(pm);
                }
            }
        }
Exemplo n.º 4
0
 private void EnsureActivated()
 {
     if (_activatedEnvironmentVariables == null)
     {
         var prefixPath = _factory.Configuration.GetPrefixPath();
         if (_condaLocatorProvider != null && Directory.Exists(prefixPath) && CondaUtils.IsCondaEnvironment(prefixPath))
         {
             var rootConda = _condaLocatorProvider.FindLocator()?.CondaExecutablePath;
             if (File.Exists(rootConda))
             {
                 var env = CondaUtils.CaptureActivationEnvironmentVariablesForPrefix(rootConda, prefixPath);
                 _activatedEnvironmentVariables = env.Union(UnbufferedEnv).ToArray();
             }
             else
             {
                 // Normally, the root is required for this environment to have been discovered,
                 // but it could be that the user added this as a custom environment and then
                 // uninstalled the root. When that's the case, there is no way to activate,
                 // so proceed without activation env variables.
                 _activatedEnvironmentVariables = UnbufferedEnv;
             }
         }
         else
         {
             // Not a conda environment, no activation necessary.
             _activatedEnvironmentVariables = UnbufferedEnv;
         }
     }
 }
Exemplo n.º 5
0
        public static Dictionary <string, string> GetFullEnvironment(LaunchConfiguration config, IServiceProvider serviceProvider)
        {
            if (config.Interpreter == null)
            {
                throw new ArgumentNullException(nameof(Interpreter));
            }
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }


            // Start with global environment, add configured environment,
            // then add search paths.
            var baseEnv = System.Environment.GetEnvironmentVariables();
            // Clear search paths from the global environment. The launch
            // configuration should include the existing value

            var pathVar = config.Interpreter?.PathEnvironmentVariable;

            if (string.IsNullOrEmpty(pathVar))
            {
                pathVar = "PYTHONPATH";
            }
            baseEnv[pathVar] = string.Empty;

            if (CondaUtils.IsCondaEnvironment(config.Interpreter.GetPrefixPath()))
            {
                var condaExe   = CondaUtils.GetRootCondaExecutablePath(serviceProvider);
                var prefixPath = config.Interpreter.GetPrefixPath();
                if (File.Exists(condaExe) && Directory.Exists(prefixPath))
                {
                    var condaEnv = ThreadHelper.JoinableTaskFactory.Run(() => CondaUtils.GetActivationEnvironmentVariablesForPrefixAsync(condaExe, prefixPath));
                    baseEnv = PathUtils.MergeEnvironments(baseEnv.AsEnumerable <string, string>(), condaEnv, "Path", pathVar);
                }
            }

            var env = PathUtils.MergeEnvironments(
                baseEnv.AsEnumerable <string, string>(),
                config.GetEnvironmentVariables(),
                "Path", pathVar
                );

            if (config.SearchPaths != null && config.SearchPaths.Any())
            {
                env = PathUtils.MergeEnvironments(
                    env,
                    new[] {
                    new KeyValuePair <string, string>(
                        pathVar,
                        PathUtils.JoinPathList(config.SearchPaths)
                        )
                },
                    pathVar
                    );
            }
            return(env);
        }
Exemplo n.º 6
0
        private async Task EnsureActivatedAsync()
        {
            if (_activatedEnvironmentVariables == null)
            {
                var env = await CondaUtils.CaptureActivationEnvironmentVariablesForRootAsync(_condaPath);

                _activatedEnvironmentVariables = env.Union(UnbufferedEnv).ToArray();
            }
        }
Exemplo n.º 7
0
        internal static string GetLatestCondaExecutablePath(IEnumerable <IPythonInterpreterFactory> factories)
        {
            var condaPaths = factories
                             .Select(factory => CondaUtils.GetCondaExecutablePath(factory.Configuration.PrefixPath, allowBatch: false))
                             .Where(path => !string.IsNullOrEmpty(path))
                             .OrderByDescending(path => GetCondaVersion(path));

            return(condaPaths.FirstOrDefault());
        }
        private void FindCondaEnvironments(List <PythonInterpreterInformation> envs)
        {
            var mainCondaExePath = CondaUtils.GetRootCondaExecutablePath(_site);

            if (mainCondaExePath != null)
            {
                envs.AddRange(FindCondaEnvironments(mainCondaExePath));
            }
        }
        private void DiscoverInterpreterFactories()
        {
            if (Volatile.Read(ref _ignoreNotifications) > 0)
            {
                return;
            }

            DiscoveryStarted?.Invoke(this, EventArgs.Empty);

            // Discover the available interpreters...
            bool anyChanged = false;

            List <PythonInterpreterInformation> found = null;

            try {
                // Try to find an existing root conda installation
                // If the future we may decide to install a private installation of conda/miniconda
                var globalFactories  = _globalProvider.GetInterpreterFactories().ToList();
                var mainCondaExePath = CondaUtils.GetLatestCondaExecutablePath(globalFactories);
                if (mainCondaExePath != null)
                {
                    found = FindCondaEnvironments(mainCondaExePath).ToList();
                }
            } catch (ObjectDisposedException) {
                // We are aborting, so silently return with no results.
                return;
            }

            var uniqueIds = new HashSet <string>(found.Select(i => i.Configuration.Id));

            // Then update our cached state with the lock held.
            lock (_factories) {
                foreach (var info in found.MaybeEnumerate())
                {
                    PythonInterpreterInformation existingInfo;
                    if (!_factories.TryGetValue(info.Configuration.Id, out existingInfo) ||
                        info.Configuration != existingInfo.Configuration)
                    {
                        _factories[info.Configuration.Id] = info;
                        anyChanged = true;
                    }
                }

                // Remove any factories we had before and no longer see...
                foreach (var unregistered in _factories.Keys.Except(uniqueIds).ToArray())
                {
                    _factories.Remove(unregistered);
                    anyChanged = true;
                }
            }

            if (anyChanged)
            {
                OnInterpreterFactoriesChanged();
            }
        }
        public CPythonCondaPackageManagerProvider(
            [Import(typeof(SVsServiceProvider), AllowDefault = true)] IServiceProvider site = null
            )
        {
            _site = site;

            // This can be slow, if there are 2 or more global conda installations
            // (some conda versions have long startup time), so we only fetch it once.
            _latestCondaExe = new Lazy <string>(() => CondaUtils.GetRootCondaExecutablePath(_site));
        }
Exemplo n.º 11
0
        public CPythonCondaPackageManagerProvider(
            [Import] CPythonInterpreterFactoryProvider globalProvider
            )
        {
            _globalProvider = globalProvider;

            // This can be slow, if there are 2 or more global conda installations
            // (some conda versions have long startup time), so we only fetch it once.
            _latestCondaExe = new Lazy <string>(() => CondaUtils.GetLatestCondaExecutablePath(_globalProvider.GetInterpreterFactories()));
        }
Exemplo n.º 12
0
 private IPackageManager CreatePackageManager()
 {
     if (ExperimentalOptions.UseCondaPackageManager && !string.IsNullOrEmpty(CondaUtils.GetCondaExecutablePath(Configuration.PrefixPath)))
     {
         return(new CondaPackageManager());
     }
     else
     {
         return(new PipPackageManager());
     }
 }
Exemplo n.º 13
0
 public CondaPackageManager(
     IPythonInterpreterFactory factory,
     string condaPath
     )
 {
     _factory           = factory;
     _installedPackages = new List <PackageSpec>();
     _availablePackages = new List <PackageSpec>();
     _condaPath         = condaPath ?? CondaUtils.GetCondaExecutablePath(factory.Configuration.PrefixPath);
     _historyPath       = Path.Combine(_factory.Configuration.PrefixPath, "conda-meta", "history");
 }
Exemplo n.º 14
0
        public static CondaEnvironmentManager Create(IServiceProvider serviceProvider)
        {
            var condaPath = CondaUtils.GetRootCondaExecutablePath(serviceProvider);

            if (!string.IsNullOrEmpty(condaPath))
            {
                return(new CondaEnvironmentManager(condaPath));
            }

            return(null);
        }
        private void FindCondaEnvironments(List <PythonInterpreterInformation> envs)
        {
            // Try to find an existing root conda installation
            // If the future we may decide to install a private installation of conda/miniconda
            var globalFactories  = _globalProvider.GetInterpreterFactories().ToList();
            var mainCondaExePath = CondaUtils.GetLatestCondaExecutablePath(globalFactories);

            if (mainCondaExePath != null)
            {
                envs.AddRange(FindCondaEnvironments(mainCondaExePath));
            }
        }
Exemplo n.º 16
0
        private static string GetLatestCondaExecutablePath(IServiceProvider serviceProvider, IEnumerable <IPythonInterpreterFactory> factories)
        {
            var condaPaths = factories
                             .Select(factory => new {
                PrefixPath = factory.Configuration.PrefixPath,
                ExePath    = CondaUtils.GetCondaExecutablePath(factory.Configuration.PrefixPath, allowBatch: false)
            })
                             .Where(obj => !string.IsNullOrEmpty(obj.ExePath))
                             .OrderByDescending(obj => GetCondaVersion(obj.PrefixPath, obj.ExePath));

            return(condaPaths.FirstOrDefault()?.ExePath);
        }
 private IPythonInterpreterFactory CreateFactory(PythonInterpreterInformation info)
 {
     return(InterpreterFactoryCreator.CreateInterpreterFactory(
                info.Configuration,
                new InterpreterFactoryCreationOptions {
         PackageManager = CondaUtils.HasConda(info.Configuration.PrefixPath) ? BuiltInPackageManagers.Conda : BuiltInPackageManagers.Pip,
         WatchFileSystem = true,
         NoDatabase = ExperimentalOptions.NoDatabaseFactory,
         DatabasePath = ExperimentalOptions.NoDatabaseFactory ?
                        DatabasePathSelector.CalculateVSLocalDatabasePath(_site, info.Configuration, 1) :
                        DatabasePathSelector.CalculateGlobalDatabasePath(info.Configuration, PythonTypeDatabase.FormatVersion)
     }
                ));
 }
Exemplo n.º 18
0
 public CondaPackageManager(
     IPythonInterpreterFactory factory,
     string condaPath
     )
 {
     _factory           = factory;
     _installedPackages = new List <PackageSpec>();
     _availablePackages = new List <PackageSpec>();
     _condaPath         = condaPath ?? CondaUtils.GetCondaExecutablePath(factory.Configuration.GetPrefixPath());
     if (!File.Exists(_condaPath))
     {
         throw new NotSupportedException();
     }
     _historyPath = Path.Combine(_factory.Configuration.GetPrefixPath(), "conda-meta", "history");
 }
Exemplo n.º 19
0
        public static CondaEnvironmentManager Create(IInterpreterRegistryService registry)
        {
            if (registry == null)
            {
                throw new ArgumentNullException(nameof(registry));
            }

            var condaPath = CondaUtils.GetLatestCondaExecutablePath(registry.Interpreters);

            if (!string.IsNullOrEmpty(condaPath))
            {
                return(new CondaEnvironmentManager(condaPath));
            }

            return(null);
        }
Exemplo n.º 20
0
        public IEnumerable <IPackageManager> GetPackageManagers(IPythonInterpreterFactory factory)
        {
            IPackageManager pm = null;
            string          condaPath;

            if (ExperimentalOptions.UseCondaPackageManager &&
                !string.IsNullOrEmpty(condaPath = CondaUtils.GetCondaExecutablePath(factory.Configuration.PrefixPath)))
            {
                try {
                    pm = new CondaPackageManager(factory, condaPath);
                } catch (NotSupportedException) {
                    pm = null;
                }
                if (pm != null)
                {
                    yield return(pm);
                }
            }
        }
        private string GetMainCondaExecutablePath()
        {
            // Try to find an existing root conda installation
            // If the future we may decide to install a private installation of conda/miniconda
            string mainCondaExePath = null;
            var    globalFactories  = _globalProvider.GetInterpreterFactories().ToList();

            foreach (var factory in globalFactories)
            {
                var condaPath = CondaUtils.GetCondaExecutablePath(factory.Configuration.PrefixPath, allowBatch: false);
                if (!string.IsNullOrEmpty(condaPath))
                {
                    // TODO: need to pick the newest conda.exe on the machine,
                    // not just the first one found.
                    // Unfortunately, conda.exe doesn't have a version resource,
                    // we'll need to figure some other way to determine conda version.
                    mainCondaExePath = condaPath;
                    break;
                }
            }

            return(mainCondaExePath);
        }
Exemplo n.º 22
0
        public void SetInterpreterFactory(IPythonInterpreterFactory factory)
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }
            if (!File.Exists(factory.Configuration?.InterpreterPath))
            {
                throw new NotSupportedException();
            }

            _factory     = factory;
            _condaPath   = CondaUtils.GetCondaExecutablePath(factory.Configuration.PrefixPath);
            _historyPath = Path.Combine(_factory.Configuration.PrefixPath, "conda-meta", "history");

            if (_historyWatcher != null)
            {
                // Watch the conda-meta/history file, which is updated after
                // a package is installed or uninstalled successfully.
                // Note: conda packages don't all install under lib/site-packages.
                try {
                    _historyWatcher.Path = Path.GetDirectoryName(_historyPath);
                    _historyWatcher.EnableRaisingEvents = true;
                } catch (ArgumentException) {
                } catch (IOException) {
                }
            }

            Task.Delay(100).ContinueWith(async t => {
                try {
                    await UpdateIsReadyAsync(false, CancellationToken.None);
                } catch (Exception ex) when(!ex.IsCriticalException())
                {
                    Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
                }
            }).DoNotWait();
        }
Exemplo n.º 23
0
        internal async static Task <CondaInfoResult> ExecuteCondaInfoAsync(string condaPath)
        {
            var activationVars = await CondaUtils.GetActivationEnvironmentVariablesForRootAsync(condaPath);

            var envVars = activationVars.Union(UnbufferedEnv).ToArray();

            var args = new[] { "info", "--json" };

            using (var output = ProcessOutput.Run(condaPath, args, null, envVars, false, null)) {
                output.Wait();
                if (output.ExitCode == 0)
                {
                    var json = string.Join(Environment.NewLine, output.StandardOutputLines);
                    try {
                        return(JsonConvert.DeserializeObject <CondaInfoResult>(json));
                    } catch (JsonException ex) {
                        Debug.WriteLine("Failed to parse: {0}".FormatInvariant(ex.Message));
                        Debug.WriteLine(json);
                        return(null);
                    }
                }
                return(null);
            }
        }
Exemplo n.º 24
0
        private async Task <KeyValuePair <string, string>[]> GetEnvironmentVariables()
        {
            var activationVars = await CondaUtils.GetActivationEnvironmentVariablesForRootAsync(_condaPath);

            return(activationVars.Union(UnbufferedEnv).ToArray());
        }
Exemplo n.º 25
0
        public static Dictionary <string, string> GetFullEnvironment(LaunchConfiguration config, IServiceProvider serviceProvider)
        {
            if (config.Interpreter == null)
            {
                throw new ArgumentNullException(nameof(Interpreter));
            }
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }


            // Start with global environment, add configured environment,
            // then add search paths.
            var baseEnv = System.Environment.GetEnvironmentVariables();
            // Clear search paths from the global environment. The launch
            // configuration should include the existing value

            var pathVar = config.Interpreter?.PathEnvironmentVariable;

            if (string.IsNullOrEmpty(pathVar))
            {
                pathVar = "PYTHONPATH";
            }
            baseEnv[pathVar] = string.Empty;

            // TODO: We could introduce a cache so that we don't activate the
            // environment + capture the env variables every time. Not doing this
            // right now to minimize risk/complexity so close to release.
            if (CondaUtils.IsCondaEnvironment(config.Interpreter.GetPrefixPath()))
            {
                var condaExe   = CondaUtils.GetRootCondaExecutablePath(serviceProvider);
                var prefixPath = config.Interpreter.GetPrefixPath();
                if (File.Exists(condaExe) && Directory.Exists(prefixPath))
                {
                    var condaEnv = CondaUtils.CaptureActivationEnvironmentVariablesForPrefix(condaExe, prefixPath);
                    baseEnv = PathUtils.MergeEnvironments(baseEnv.AsEnumerable <string, string>(), condaEnv, "Path", pathVar);
                }
            }

            var env = PathUtils.MergeEnvironments(
                baseEnv.AsEnumerable <string, string>(),
                config.GetEnvironmentVariables(),
                "Path", pathVar
                );

            if (config.SearchPaths != null && config.SearchPaths.Any())
            {
                env = PathUtils.MergeEnvironments(
                    env,
                    new[] {
                    new KeyValuePair <string, string>(
                        pathVar,
                        PathUtils.JoinPathList(config.SearchPaths)
                        )
                },
                    pathVar
                    );
            }
            return(env);
        }