Esempio n. 1
0
        public AddVirtualEnvironmentView(
            PythonProjectNode project,
            IInterpreterRegistryService interpreterService,
            IPythonInterpreterFactory selectInterpreter
            )
        {
            _interpreterService = interpreterService;
            _project            = project;
            VirtualEnvBasePath  = _projectHome = project.ProjectHome;
            Interpreters        = new ObservableCollection <InterpreterView>(InterpreterView.GetInterpreters(project.Site, project));
            var selection = Interpreters.FirstOrDefault(v => v.Interpreter == selectInterpreter);

            if (selection == null)
            {
                selection = Interpreters.FirstOrDefault(v => v.Interpreter == project.GetInterpreterFactory())
                            ?? Interpreters.LastOrDefault();
            }
            BaseInterpreter = selection;

            _project.InterpreterFactoriesChanged += OnInterpretersChanged;

            var venvName = "env";

            for (int i = 1; Directory.Exists(Path.Combine(_projectHome, venvName)); ++i)
            {
                venvName = "env" + i.ToString();
            }
            VirtualEnvName = venvName;

            CanInstallRequirementsTxt  = File.Exists(PathUtils.GetAbsoluteFilePath(_projectHome, "requirements.txt"));
            WillInstallRequirementsTxt = CanInstallRequirementsTxt;
        }
 public EnvironmentSwitcherFileContext(IServiceProvider serviceProvider, string filePath)
 {
     _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
     _optionsService  = serviceProvider.GetComponentModel().GetService <IInterpreterOptionsService>();
     _registryService = serviceProvider.GetComponentModel().GetService <IInterpreterRegistryService>();
     _filePath        = filePath ?? throw new ArgumentNullException(nameof(filePath));
 }
Esempio n. 3
0
        internal void LoadSettings()
        {
            _service = _propPage.Project.Site.GetComponentModel().GetService <IInterpreterRegistryService>();

            StartupFile      = _propPage.Project.GetProjectProperty(CommonConstants.StartupFile, false);
            WorkingDirectory = _propPage.Project.GetProjectProperty(CommonConstants.WorkingDirectory, false);
            if (string.IsNullOrEmpty(WorkingDirectory))
            {
                WorkingDirectory = ".";
            }
            IsWindowsApplication = Convert.ToBoolean(_propPage.Project.GetProjectProperty(CommonConstants.IsWindowsApplication, false));
            OnInterpretersChanged();

            if (_propPage.PythonProject.IsActiveInterpreterGlobalDefault)
            {
                // ActiveInterpreter will never be null, so we need to check
                // the property to find out if it's following the global
                // default.
                SetDefaultInterpreter(null);
            }
            else
            {
                SetDefaultInterpreter(_propPage.PythonProject.ActiveInterpreter);
            }
        }
Esempio n. 4
0
        private static IPythonInterpreterFactory FindBaseInterpreterFromVirtualEnv(
            string prefixPath,
            string libPath,
            IInterpreterRegistryService service
            )
        {
            IPythonInterpreterFactory match = null;
            string basePath = PathUtils.TrimEndSeparator(GetOrigPrefixPath(prefixPath, libPath));

            if (Directory.Exists(basePath))
            {
                match = service.Interpreters.FirstOrDefault(interp =>
                                                            PathUtils.IsSamePath(PathUtils.TrimEndSeparator(interp.Configuration.GetPrefixPath()), basePath));
            }

            // Special case, we may have the store installed interpreter. In this situation both
            // paths end with the same entry. Note, os.path.realpath can't seem to say these are the same anymore.
            if (match == null && Directory.Exists(basePath) && basePath.Contains("PythonSoftwareFoundation.Python"))
            {
                var baseDir = Path.GetFileName(basePath);
                var baseEnd = baseDir.Substring(Math.Max(0, baseDir.LastIndexOf('_')));
                match = service.Interpreters.FirstOrDefault(interp => {
                    var interpDir = Path.GetFileName(PathUtils.TrimEndSeparator(interp.Configuration.GetPrefixPath()));
                    var interpEnd = interpDir.Substring(Math.Max(0, interpDir.LastIndexOf('_')));
                    return(baseEnd == interpEnd);
                });
            }
            return(match);
        }
Esempio n. 5
0
 internal GlobalInterpreterOptions(PythonToolsService pyService, IInterpreterOptionsService interpreterOptions, IInterpreterRegistryService interpreters)
 {
     _pyService          = pyService;
     _interpreters       = interpreters;
     _interpreterOptions = interpreterOptions;
     Load();
 }
Esempio n. 6
0
        public AddVirtualEnvironmentView(
            PythonProjectNode project,
            IInterpreterRegistryService interpreterService,
            string selectInterpreterId,
            string requirementsPath
            )
        {
            _interpreterService = interpreterService;
            _project            = project;
            _requirementsPath   = requirementsPath;
            VirtualEnvBasePath  = _projectHome = project.ProjectHome;
            Interpreters        = new ObservableCollection <InterpreterView>(InterpreterView.GetInterpreters(project.Site, null, true));
            var selection = Interpreters.FirstOrDefault(v => v.Id == selectInterpreterId);

            if (selection == null)
            {
                selection = Interpreters.FirstOrDefault(v => v.Id == project.ActiveInterpreter?.Configuration.Id)
                            ?? Interpreters.LastOrDefault();
            }
            BaseInterpreter = selection;

            _project.InterpreterFactoriesChanged += OnInterpretersChanged;

            var venvName = "env";

            for (int i = 1; Directory.Exists(Path.Combine(_projectHome, venvName)); ++i)
            {
                venvName = "env" + i.ToString();
            }
            VirtualEnvName = venvName;

            CanInstallRequirementsTxt  = File.Exists(_requirementsPath);
            WillInstallRequirementsTxt = CanInstallRequirementsTxt;
        }
Esempio n. 7
0
        public InterpretersNode(
            PythonProjectNode project,
            IPythonInterpreterFactory factory,
            bool isInterpreterReference,
            bool canDelete,
            bool isGlobalDefault = false,
            bool?canRemove       = null
            )
            : base(project, MakeElement(project))
        {
            ExcludeNodeFromScc = true;

            _interpreterService = project.Site.GetComponentModel().GetService <IInterpreterRegistryService>();
            _factory            = factory;
            _isReference        = isInterpreterReference;
            _canDelete          = canDelete;
            _isGlobalDefault    = isGlobalDefault;
            _canRemove          = canRemove.HasValue ? canRemove.Value : !isGlobalDefault;
            _captionSuffix      = isGlobalDefault ? Strings.GlobalDefaultSuffix : "";

            var interpreterOpts = project.Site.GetComponentModel().GetService <IInterpreterOptionsService>();

            _packageManager = interpreterOpts?.GetPackageManagers(factory).FirstOrDefault();
            if (_packageManager != null)
            {
                _packageManager.InstalledPackagesChanged += InstalledPackagesChanged;
                _packageManager.EnableNotifications();
            }
        }
 public AddVirtualEnvironmentOperation(
     IServiceProvider site,
     PythonProjectNode project,
     string virtualEnvPath,
     string baseInterpreterId,
     bool useVEnv,
     bool installRequirements,
     string requirementsPath,
     bool registerAsCustomEnv,
     string customEnvName,
     bool setAsCurrent,
     bool setAsDefault,
     bool viewInEnvWindow,
     Redirector output = null
     )
 {
     _site                = site ?? throw new ArgumentNullException(nameof(site));
     _project             = project;
     _virtualEnvPath      = virtualEnvPath ?? throw new ArgumentNullException(nameof(virtualEnvPath));
     _baseInterpreter     = baseInterpreterId ?? throw new ArgumentNullException(nameof(baseInterpreterId));
     _useVEnv             = useVEnv;
     _installReqs         = installRequirements;
     _reqsPath            = requirementsPath;
     _registerAsCustomEnv = registerAsCustomEnv;
     _customEnvName       = customEnvName;
     _setAsCurrent        = setAsCurrent;
     _setAsDefault        = setAsDefault;
     _viewInEnvWindow     = viewInEnvWindow;
     _output              = output;
     _statusCenter        = _site.GetService(typeof(SVsTaskStatusCenterService)) as IVsTaskStatusCenterService;
     _registry            = _site.GetComponentModel().GetService <IInterpreterRegistryService>();
     _options             = _site.GetComponentModel().GetService <IInterpreterOptionsService>();
     _logger              = _site.GetService(typeof(IPythonToolsLogger)) as IPythonToolsLogger;
 }
Esempio n. 9
0
        public AddVirtualEnvironmentView(
            PythonProjectNode project,
            IInterpreterRegistryService interpreterService,
            IPythonInterpreterFactory selectInterpreter
        ) {
            _interpreterService = interpreterService;
            _project = project;
            VirtualEnvBasePath = _projectHome = project.ProjectHome;
            Interpreters = new ObservableCollection<InterpreterView>(InterpreterView.GetInterpreters(project.Site, project));
            var selection = Interpreters.FirstOrDefault(v => v.Interpreter == selectInterpreter);
            if (selection == null) {
                selection = Interpreters.FirstOrDefault(v => v.Interpreter == project.GetInterpreterFactory())
                    ?? Interpreters.LastOrDefault();
            }
            BaseInterpreter = selection;

            _project.InterpreterFactoriesChanged += OnInterpretersChanged;

            var venvName = "env";
            for (int i = 1; Directory.Exists(Path.Combine(_projectHome, venvName)); ++i) {
                venvName = "env" + i.ToString();
            }
            VirtualEnvName = venvName;

            CanInstallRequirementsTxt = File.Exists(PathUtils.GetAbsoluteFilePath(_projectHome, "requirements.txt"));
            WillInstallRequirementsTxt = CanInstallRequirementsTxt;
        }
Esempio n. 10
0
        internal EnvironmentView(
            IInterpreterOptionsService service,
            IInterpreterRegistryService registry,
            IPythonInterpreterFactory factory,
            Redirector redirector
            )
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }
            if (registry == null)
            {
                throw new ArgumentNullException(nameof(registry));
            }
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }
            if (factory.Configuration == null)
            {
                throw new ArgumentException("factory must include a configuration");
            }

            _service                 = service;
            _registry                = registry;
            Factory                  = factory;
            Configuration            = Factory.Configuration;
            LocalizedDisplayName     = Configuration.Description;
            IsBroken                 = !Configuration.IsRunnable();
            LocalizedAutomationName  = !IsBroken ? LocalizedDisplayName : String.Format(Resources.BrokenEnvironmentAutomationNameFormat, LocalizedDisplayName);
            BrokenEnvironmentHelpUrl = "https://go.microsoft.com/fwlink/?linkid=863373";

            if (_service.IsConfigurable(Factory.Configuration.Id))
            {
                IsConfigurable = true;
            }

            Description = Factory.Configuration.Description;
            IsDefault   = (_service != null && _service.DefaultInterpreterId == Configuration.Id);

            PrefixPath             = Factory.Configuration.GetPrefixPath();
            InterpreterPath        = Factory.Configuration.InterpreterPath;
            WindowsInterpreterPath = Factory.Configuration.GetWindowsInterpreterPath();

            Extensions = new ObservableCollection <object>();
            Extensions.Add(new EnvironmentPathsExtensionProvider());
            if (IsConfigurable)
            {
                Extensions.Add(new ConfigurationExtensionProvider(_service, alwaysCreateNew: false));
            }

            CanBeDefault = Factory.CanBeDefault();
            CanBeDeleted = Factory.CanBeDeleted();

            Company    = _registry.GetProperty(Factory.Configuration.Id, CompanyKey) as string ?? "";
            SupportUrl = _registry.GetProperty(Factory.Configuration.Id, SupportUrlKey) as string ?? "";

            LocalizedHelpText = Company;
        }
Esempio n. 11
0
 private static bool CondaEnvExists(IInterpreterRegistryService interpreterService, string prefixName)
 {
     // Known shortcoming:
     // Interpreter service only tracks conda envs that have Python in them,
     // so our check here will report no conflicts for conda envs without Python.
     return(interpreterService.Configurations.Where(c => HasPrefixName(c, prefixName)).Any());
 }
Esempio n. 12
0
        public void InitializeEnvironments(IInterpreterRegistryService interpreters, IInterpreterOptionsService options, bool synchronous = false)
        {
            if (_interpreters != null)
            {
                _interpreters.InterpretersChanged -= Service_InterpretersChanged;
            }
            _interpreters = interpreters;
            if (_interpreters != null)
            {
                _interpreters.InterpretersChanged += Service_InterpretersChanged;
            }

            if (_options != null)
            {
                _options.DefaultInterpreterChanged -= Service_DefaultInterpreterChanged;
            }
            _options = options;
            if (_options != null)
            {
                _options.DefaultInterpreterChanged += Service_DefaultInterpreterChanged;
            }

            if (_interpreters != null && _options != null)
            {
                if (synchronous)
                {
                    Dispatcher.Invoke(FirstUpdateEnvironments);
                }
                else
                {
                    Dispatcher.InvokeAsync(FirstUpdateEnvironments).Task.DoNotWait();
                }
            }
        }
 public EnvironmentSwitcherWorkspaceContext(IServiceProvider serviceProvider, IPythonWorkspaceContext pythonWorkspace)
 {
     _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
     _pythonWorkspace = pythonWorkspace ?? throw new ArgumentNullException(nameof(pythonWorkspace));
     _registryService = serviceProvider.GetComponentModel().GetService <IInterpreterRegistryService>();
     _pythonWorkspace.ActiveInterpreterChanged += OnActiveInterpreterChanged;
 }
Esempio n. 14
0
        public PythonWorkspaceContext(
            IWorkspace workspace,
            IPropertyEvaluatorService workspacePropertyEvaluator,
            IInterpreterOptionsService optionsService,
            IInterpreterRegistryService registryService)
        {
            _workspace                = workspace ?? throw new ArgumentNullException(nameof(workspace));
            _optionsService           = optionsService ?? throw new ArgumentNullException(nameof(optionsService));
            _registryService          = registryService ?? throw new ArgumentNullException(nameof(registryService));
            _workspaceSettingsMgr     = _workspace.GetSettingsManager();
            _propertyEvaluatorService = workspacePropertyEvaluator;


            // Initialization in 2 phases (Constructor + Initialize) is needed to
            // break a circular dependency.
            // We create a partially initialized object that can be used by
            // WorkspaceInterpreterFactoryProvider to discover the interpreters
            // in this workspace (it needs the interpreter setting to do that).
            // Once that is done, the IPythonInterpreterFactory on this object
            // can be resolved in Initialize.
            _interpreter           = ReadInterpreterSetting();
            _searchPaths           = ReadSearchPathsSetting();
            _testFramework         = GetStringProperty(TestFrameworkProperty);
            _unitTestRootDirectory = GetStringProperty(UnitTestRootDirectoryProperty);
            _unitTestPattern       = GetStringProperty(UnitTestPatternProperty);
        }
Esempio n. 15
0
 public EnvironmentSwitcherWorkspaceContext(IServiceProvider serviceProvider, IWorkspace workspace)
 {
     _serviceProvider      = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
     _optionsService       = serviceProvider.GetComponentModel().GetService <IInterpreterOptionsService>();
     _registryService      = serviceProvider.GetComponentModel().GetService <IInterpreterRegistryService>();
     _workspace            = workspace ?? throw new ArgumentNullException(nameof(workspace));
     _workspaceSettingsMgr = _workspace.GetSettingsManager();
     _workspaceSettingsMgr.OnWorkspaceSettingsChanged += OnSettingsChanged;
 }
Esempio n. 16
0
        internal EnvironmentView(
            IInterpreterOptionsService service,
            IInterpreterRegistryService registry,
            IPythonInterpreterFactory factory,
            Redirector redirector
            )
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }
            if (registry == null)
            {
                throw new ArgumentNullException(nameof(registry));
            }
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            _service  = service;
            _registry = registry;
            Factory   = factory;

            _withDb = factory as IPythonInterpreterFactoryWithDatabase;
            if (_withDb != null)
            {
                _withDb.IsCurrentChanged += Factory_IsCurrentChanged;
                IsCheckingDatabase        = _withDb.IsCheckingDatabase;
                IsCurrent = _withDb.IsCurrent;
            }


            if (_service.IsConfigurable(factory.Configuration.Id))
            {
                IsConfigurable = true;
            }

            Description = Factory.Configuration.Description;
            IsDefault   = (_service != null && _service.DefaultInterpreter == Factory);

            PrefixPath             = Factory.Configuration.PrefixPath;
            InterpreterPath        = Factory.Configuration.InterpreterPath;
            WindowsInterpreterPath = Factory.Configuration.WindowsInterpreterPath;

            Extensions = new ObservableCollection <object>();
            Extensions.Add(new EnvironmentPathsExtensionProvider());
            if (IsConfigurable)
            {
                Extensions.Add(new ConfigurationExtensionProvider(_service));
            }

            CanBeDefault = Factory.CanBeDefault();

            Company    = _registry.GetProperty(Factory.Configuration.Id, CompanyKey) as string ?? "";
            SupportUrl = _registry.GetProperty(Factory.Configuration.Id, SupportUrlKey) as string ?? "";
        }
 public PythonReplEvaluatorProvider(
     [Import] IInterpreterRegistryService interpreterService,
     [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider
     )
 {
     Debug.Assert(interpreterService != null);
     _interpreterService = interpreterService;
     _serviceProvider    = serviceProvider;
 }
 public PythonWorkspaceContext(
     IWorkspace workspace,
     IInterpreterOptionsService optionsService,
     IInterpreterRegistryService registryService)
 {
     _workspace            = workspace ?? throw new ArgumentNullException(nameof(workspace));
     _optionsService       = optionsService ?? throw new ArgumentNullException(nameof(optionsService));
     _registryService      = registryService ?? throw new ArgumentNullException(nameof(registryService));
     _workspaceSettingsMgr = _workspace.GetSettingsManager();
 }
 public EnvironmentSwitcherManager(IServiceProvider serviceProvider)
 {
     _serviceProvider  = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
     _optionsService   = serviceProvider.GetComponentModel().GetService <IInterpreterOptionsService>();
     _registryService  = serviceProvider.GetComponentModel().GetService <IInterpreterRegistryService>();
     _monitorSelection = serviceProvider.GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection;
     _shell            = serviceProvider.GetService(typeof(SVsShell)) as IVsShell;
     _workspaceService = serviceProvider.GetComponentModel().GetService <IVsFolderWorkspaceService>();
     AllFactories      = Enumerable.Empty <IPythonInterpreterFactory>();
 }
 private PythonInterpreterOptionsControl GetWindow()
 {
     if (_window == null)
     {
         _service = ComponentModel.GetService <IInterpreterRegistryService>();
         _service.InterpretersChanged += InterpretersChanged;
         _window = new PythonInterpreterOptionsControl(ComponentModel.GetService <SVsServiceProvider>());
     }
     return(_window);
 }
Esempio n. 21
0
 public PythonReplEvaluator(IPythonInterpreterFactory interpreter, IServiceProvider serviceProvider, PythonReplEvaluatorOptions options, IInterpreterRegistryService interpreterService = null)
     : base(serviceProvider, serviceProvider.GetPythonToolsService(), options)
 {
     _interpreter        = interpreter;
     _interpreterService = interpreterService;
     if (_interpreterService != null)
     {
         _interpreterService.InterpretersChanged += InterpretersChanged;
     }
 }
Esempio n. 22
0
        internal PythonToolsService(IServiceContainer container)
        {
            _container = container;

            var langService = new PythonLanguageInfo(container);

            _container.AddService(langService.GetType(), langService, true);

            IVsTextManager textMgr = (IVsTextManager)container.GetService(typeof(SVsTextManager));

            if (textMgr != null)
            {
                var langPrefs = new LANGPREFERENCES[1];
                langPrefs[0].guidLang = typeof(PythonLanguageInfo).GUID;
                ErrorHandler.ThrowOnFailure(textMgr.GetUserPreferences(null, null, langPrefs, null));
                _langPrefs = new LanguagePreferences(this, langPrefs[0]);

                Guid             guid = typeof(IVsTextManagerEvents2).GUID;
                IConnectionPoint connectionPoint;
                ((IConnectionPointContainer)textMgr).FindConnectionPoint(ref guid, out connectionPoint);
                connectionPoint.Advise(_langPrefs, out _langPrefsTextManagerCookie);
            }

            _optionsService = (IPythonToolsOptionsService)container.GetService(typeof(IPythonToolsOptionsService));
            var compModel = (IComponentModel)container.GetService(typeof(SComponentModel));

            _interpreterRegistry = compModel.GetService <IInterpreterRegistryService>();
            if (_interpreterRegistry != null)
            {
                _interpreterRegistry.InterpretersChanged += InterpretersChanged;
            }

            _interpreterOptionsService = compModel.GetService <IInterpreterOptionsService>();
            if (_interpreterOptionsService != null)     // not available in some test cases...
            {
                _interpreterOptionsService.DefaultInterpreterChanged += UpdateDefaultAnalyzer;
                LoadInterpreterOptions();
            }

            _idleManager              = new IdleManager(container);
            _advancedOptions          = new AdvancedEditorOptions(this);
            _debuggerOptions          = new DebuggerOptions(this);
            _generalOptions           = new GeneralOptions(this);
            _surveyNews               = new SurveyNewsService(container);
            _suppressDialogOptions    = new SuppressDialogOptions(this);
            _globalInterpreterOptions = new GlobalInterpreterOptions(this, _interpreterOptionsService, _interpreterRegistry);
            _globalInterpreterOptions.Load();
            _interactiveOptions = new PythonInteractiveOptions(this, "Interactive");
            _interactiveOptions.Load();
            _debugInteractiveOptions = new PythonInteractiveOptions(this, "Debug Interactive Window");
            _debuggerOptions.Load();
            _factoryProviders = ComponentModel.DefaultExportProvider.GetExports <IPythonInterpreterFactoryProvider, Dictionary <string, object> >();
            _logger           = new PythonToolsLogger(ComponentModel.GetExtensions <IPythonToolsLogger>().ToArray());
            InitializeLogging();
        }
Esempio n. 23
0
        internal EnvironmentView(
            IInterpreterOptionsService service,
            IInterpreterRegistryService registry,
            IPythonInterpreterFactory factory,
            Redirector redirector
        ) {
            if (service == null) {
                throw new ArgumentNullException(nameof(service));
            }
            if (registry == null) {
                throw new ArgumentNullException(nameof(registry));
            }
            if (factory == null) {
                throw new ArgumentNullException(nameof(factory));
            }
            if (factory.Configuration == null) {
                throw new ArgumentException("factory must include a configuration");
            }

            _service = service;
            _registry = registry;
            Factory = factory;
            Configuration = Factory.Configuration;

            _withDb = factory as IPythonInterpreterFactoryWithDatabase;
            if (_withDb != null) {
                _withDb.IsCurrentChanged += Factory_IsCurrentChanged;
                IsCheckingDatabase = _withDb.IsCheckingDatabase;
                IsCurrent = _withDb.IsCurrent;
            }
            

            if (_service.IsConfigurable(Factory.Configuration.Id)) {
                IsConfigurable = true;
            }

            Description = Factory.Configuration.Description;
            IsDefault = (_service != null && _service.DefaultInterpreterId == Configuration.Id);

            PrefixPath = Factory.Configuration.PrefixPath;
            InterpreterPath = Factory.Configuration.InterpreterPath;
            WindowsInterpreterPath = Factory.Configuration.WindowsInterpreterPath;

            Extensions = new ObservableCollection<object>();
            Extensions.Add(new EnvironmentPathsExtensionProvider());
            if (IsConfigurable) {
                Extensions.Add(new ConfigurationExtensionProvider(_service, alwaysCreateNew: false));
            }

            CanBeDefault = Factory.CanBeDefault();

            Company = _registry.GetProperty(Factory.Configuration.Id, CompanyKey) as string ?? "";
            SupportUrl = _registry.GetProperty(Factory.Configuration.Id, SupportUrlKey) as string ?? "";
        }
Esempio n. 24
0
        public static bool CanInstall(
            IPythonInterpreterFactory factory,
            IInterpreterRegistryService service
            )
        {
            if (!factory.IsRunnable())
            {
                return(false);
            }

            return(TryGetCondaFactoryAsync(factory, service).WaitAndUnwrapExceptions() != null);
        }
Esempio n. 25
0
        public void InitializeEnvironments(IInterpreterRegistryService interpreters, IInterpreterOptionsService options, bool synchronous = false)
        {
            if (_interpreters != null)
            {
                _interpreters.InterpretersChanged -= Service_InterpretersChanged;
            }
            _interpreters = interpreters;
            if (_interpreters != null)
            {
                _interpreters.InterpretersChanged += Service_InterpretersChanged;
            }

            if (_options != null)
            {
                _options.DefaultInterpreterChanged -= Service_DefaultInterpreterChanged;
            }
            _options = options;
            if (_options != null)
            {
                _options.DefaultInterpreterChanged += Service_DefaultInterpreterChanged;
            }

            if (_interpreters != null && _options != null)
            {
                _addNewEnvironmentView = EnvironmentView.CreateAddNewEnvironmentView(_options);
                if (ExperimentalOptions.AutoDetectCondaEnvironments)
                {
                    _condaEnvironmentView = EnvironmentView.CreateCondaEnvironmentView(_options, _interpreters);
                    var provider = _condaEnvironmentView.Extensions.FirstOrDefault() as CondaExtensionProvider;
                    OnProviderCreated(provider);
                }
                else
                {
                    _condaEnvironmentView = null;
                }
                _onlineHelpView = EnvironmentView.CreateOnlineHelpEnvironmentView();

                if (synchronous)
                {
                    Dispatcher.Invoke(FirstUpdateEnvironments);
                }
                else
                {
                    Dispatcher.InvokeAsync(FirstUpdateEnvironments).Task.DoNotWait();
                }
            }
            else
            {
                _addNewEnvironmentView = null;
                _condaEnvironmentView  = null;
                _onlineHelpView        = null;
            }
        }
Esempio n. 26
0
 public static InstallPythonPackageView ShowDialog(
     IServiceProvider serviceProvider,
     IPythonInterpreterFactory factory,
     IInterpreterRegistryService service
     )
 {
     var wnd = new InstallPythonPackage(serviceProvider, factory, service);
     if (wnd.ShowModal() ?? false) {
         return wnd._view;
     } else {
         return null;
     }
 }
Esempio n. 27
0
        public static InterpreterConfiguration FindInterpreterConfiguration(
            string id,
            string prefixPath,
            IInterpreterRegistryService service,
            IPythonInterpreterFactory baseInterpreter = null
            )
        {
            var libPath = DerivedInterpreterFactory.FindLibPath(prefixPath);

            if (baseInterpreter == null)
            {
                baseInterpreter = DerivedInterpreterFactory.FindBaseInterpreterFromVirtualEnv(
                    prefixPath,
                    libPath,
                    service
                    );

                if (baseInterpreter == null)
                {
                    return(null);
                }
            }

            // The interpreter name should be the same as the base interpreter.
            string interpExe  = Path.GetFileName(baseInterpreter.Configuration.InterpreterPath);
            string winterpExe = Path.GetFileName(baseInterpreter.Configuration.WindowsInterpreterPath);
            var    scripts    = new[] { "Scripts", "bin" };

            interpExe  = PathUtils.FindFile(prefixPath, interpExe, firstCheck: scripts);
            winterpExe = PathUtils.FindFile(prefixPath, winterpExe, firstCheck: scripts);
            string pathVar     = baseInterpreter.Configuration.PathEnvironmentVariable;
            string description = string.Format(
                "{0} ({1})",
                PathUtils.GetFileOrDirectoryName(prefixPath),
                baseInterpreter.Configuration.Description
                );

            return(new InterpreterConfiguration(
                       id ?? baseInterpreter.Configuration.Id,
                       description,
                       prefixPath,
                       interpExe,
                       winterpExe,
                       libPath,
                       pathVar,
                       baseInterpreter.Configuration.Architecture,
                       baseInterpreter.Configuration.Version,
                       InterpreterUIMode.CannotBeDefault | InterpreterUIMode.CannotBeConfigured | InterpreterUIMode.SupportsDatabase
                       ));
        }
Esempio n. 28
0
        public static InterpreterConfiguration FindInterpreterConfiguration(
            string id,
            string prefixPath,
            IInterpreterRegistryService registry,
            IPythonInterpreterFactory baseInterpreter = null
            )
        {
            if (string.IsNullOrEmpty(prefixPath))
            {
                throw new ArgumentNullException(nameof(prefixPath));
            }

            var libPath = FindLibPath(prefixPath);

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

                baseInterpreter = FindBaseInterpreterFromVirtualEnv(
                    prefixPath,
                    libPath,
                    registry
                    );

                if (baseInterpreter == null)
                {
                    return(null);
                }
            }

            // The interpreter name should be the same as the base interpreter.
            GetVirtualEnvConfig(prefixPath, baseInterpreter, out string interpExe, out string winterpExe, out string pathVar);
            string description = PathUtils.GetFileOrDirectoryName(prefixPath);

            return(new InterpreterConfiguration(
                       id ?? baseInterpreter.Configuration.Id,
                       baseInterpreter == null ? description : string.Format("{0} ({1})", description, baseInterpreter.Configuration.Description),
                       prefixPath,
                       interpExe,
                       winterpExe,
                       pathVar,
                       baseInterpreter.Configuration.Architecture,
                       baseInterpreter.Configuration.Version,
                       InterpreterUIMode.CannotBeDefault | InterpreterUIMode.CannotBeConfigured
                       ));
        }
Esempio n. 29
0
        private static IPythonInterpreterFactory FindBaseInterpreterFromVirtualEnv(
            string prefixPath,
            string libPath,
            IInterpreterRegistryService service
            )
        {
            string basePath = PathUtils.TrimEndSeparator(GetOrigPrefixPath(prefixPath, libPath));

            if (Directory.Exists(basePath))
            {
                return(service.Interpreters.FirstOrDefault(interp =>
                                                           PathUtils.IsSamePath(PathUtils.TrimEndSeparator(interp.Configuration.PrefixPath), basePath)
                                                           ));
            }
            return(null);
        }
Esempio n. 30
0
        private InstallPythonPackage(
            IServiceProvider serviceProvider,
            IPythonInterpreterFactory factory,
            IInterpreterRegistryService service
            )
        {
            _view = new InstallPythonPackageView(
                serviceProvider,
                !Pip.IsSecureInstall(factory),
                Conda.CanInstall(factory, service)
            );
            DataContext = _view;

            InitializeComponent();
            _textBox.Focus();
        }
        private InstallPythonPackage(
            IServiceProvider serviceProvider,
            IPythonInterpreterFactory factory,
            IInterpreterRegistryService service
            )
        {
            _view = new InstallPythonPackageView(
                serviceProvider,
                !Pip.IsSecureInstall(factory),
                Conda.CanInstall(factory, service)
                );
            DataContext = _view;

            InitializeComponent();
            _textBox.Focus();
        }
Esempio n. 32
0
 public PythonReplEvaluatorProvider(
     [Import] IInterpreterRegistryService interpreterService,
     [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider
 ) {
     Debug.Assert(interpreterService != null);
     _interpreterService = interpreterService;
     _serviceProvider = serviceProvider;
     _solution = (IVsSolution)_serviceProvider.GetService(typeof(SVsSolution));
     _solutionEvents = new SolutionEventsListener(_solution);
     _solutionEvents.ProjectLoaded += ProjectChanged;
     _solutionEvents.ProjectClosing += ProjectChanged;
     _solutionEvents.ProjectRenamed += ProjectChanged;
     _solutionEvents.SolutionOpened += SolutionChanged;
     _solutionEvents.SolutionClosed += SolutionChanged;
     _solutionEvents.StartListeningForChanges();
 }
Esempio n. 33
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);
        }
        public static InstallPythonPackageView ShowDialog(
            IServiceProvider serviceProvider,
            IPythonInterpreterFactory factory,
            IInterpreterRegistryService service
            )
        {
            var wnd = new InstallPythonPackage(serviceProvider, factory, service);

            if (wnd.ShowModal() ?? false)
            {
                return(wnd._view);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 35
0
 public PythonReplEvaluatorProvider(
     [Import] IInterpreterRegistryService interpreterService,
     [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider
     )
 {
     Debug.Assert(interpreterService != null);
     _interpreterService             = interpreterService;
     _serviceProvider                = serviceProvider;
     _solution                       = (IVsSolution)_serviceProvider.GetService(typeof(SVsSolution));
     _solutionEvents                 = new SolutionEventsListener(_solution);
     _solutionEvents.ProjectLoaded  += ProjectChanged;
     _solutionEvents.ProjectClosing += ProjectChanged;
     _solutionEvents.ProjectRenamed += ProjectChanged;
     _solutionEvents.SolutionOpened += SolutionChanged;
     _solutionEvents.SolutionClosed += SolutionChanged;
     _solutionEvents.StartListeningForChanges();
 }
Esempio n. 36
0
        public InterpretersNode(
            PythonProjectNode project,
            IPythonInterpreterFactory factory,
            bool isInterpreterReference,
            bool canDelete,
            bool isGlobalDefault = false,
            bool? canRemove = null
        )
            : base(project, MakeElement(project)) {
            ExcludeNodeFromScc = true;

            _interpreterService = project.Site.GetComponentModel().GetService<IInterpreterRegistryService>();
            _factory = factory;
            _isReference = isInterpreterReference;
            _canDelete = canDelete;
            _isGlobalDefault = isGlobalDefault;
            _canRemove = canRemove.HasValue ? canRemove.Value : !isGlobalDefault;
            _captionSuffix = isGlobalDefault ? Strings.GlobalDefaultSuffix : "";

            if (Directory.Exists(_factory.Configuration.LibraryPath)) {
                // TODO: Need to handle watching for creation
                try {
                    _fileWatcher = new FileSystemWatcher(_factory.Configuration.LibraryPath);
                } catch (ArgumentException) {
                    // Path was not actually valid, despite Directory.Exists
                    // returning true.
                }
                if (_fileWatcher != null) {
                    try {
                        _fileWatcher.IncludeSubdirectories = true;
                        _fileWatcher.Deleted += PackagesChanged;
                        _fileWatcher.Created += PackagesChanged;
                        _fileWatcher.EnableRaisingEvents = true;
                        // Only create the timer if the file watcher is running.
                        _timer = new Timer(CheckPackages);
                    } catch (IOException) {
                        // Raced with directory deletion
                        _fileWatcher.Dispose();
                        _fileWatcher = null;
                    }
                }
            }
        }
Esempio n. 37
0
        public ImportSettings(IServiceProvider site, IInterpreterRegistryService service) {
            _site = site;
            _service = service;

            if (_service != null) {
                AvailableInterpreters = new ObservableCollection<PythonInterpreterView>(
                    Enumerable.Repeat(_defaultInterpreter, 1)
                    .Concat(_service.Configurations.Select(fact => new PythonInterpreterView(fact)))
                );
            } else {
                AvailableInterpreters = new ObservableCollection<PythonInterpreterView>();
                AvailableInterpreters.Add(_defaultInterpreter);
            }

            SelectedInterpreter = AvailableInterpreters[0];
            TopLevelPythonFiles = new BulkObservableCollection<string>();
            Customization = _projectCustomizations.First();

            Filters = "*.pyw;*.txt;*.htm;*.html;*.css;*.djt;*.js;*.ini;*.png;*.jpg;*.gif;*.bmp;*.ico;*.svg";
        }
        internal void LoadSettings() {
            _service = _propPage.Project.Site.GetComponentModel().GetService<IInterpreterRegistryService>();

            StartupFile = _propPage.Project.GetProjectProperty(CommonConstants.StartupFile, false);
            WorkingDirectory = _propPage.Project.GetProjectProperty(CommonConstants.WorkingDirectory, false);
            if (string.IsNullOrEmpty(WorkingDirectory)) {
                WorkingDirectory = ".";
            }
            IsWindowsApplication = Convert.ToBoolean(_propPage.Project.GetProjectProperty(CommonConstants.IsWindowsApplication, false));
            OnInterpretersChanged();

            if (_propPage.PythonProject.IsActiveInterpreterGlobalDefault) {
                // ActiveInterpreter will never be null, so we need to check
                // the property to find out if it's following the global
                // default.
                SetDefaultInterpreter(null);
            } else {
                SetDefaultInterpreter(_propPage.PythonProject.ActiveInterpreter);
            }

        }
Esempio n. 39
0
        public InterpretersNode(
            PythonProjectNode project,
            IPythonInterpreterFactory factory,
            bool isInterpreterReference,
            bool canDelete,
            bool isGlobalDefault = false,
            bool? canRemove = null
        )
            : base(project, MakeElement(project)) {
            ExcludeNodeFromScc = true;

            _interpreterService = project.Site.GetComponentModel().GetService<IInterpreterRegistryService>();
            _factory = factory;
            _isReference = isInterpreterReference;
            _canDelete = canDelete;
            _isGlobalDefault = isGlobalDefault;
            _canRemove = canRemove.HasValue ? canRemove.Value : !isGlobalDefault;
            _captionSuffix = isGlobalDefault ? Strings.GlobalDefaultSuffix : "";

            if (_factory.PackageManager != null) {
                _factory.PackageManager.InstalledPackagesChanged += InstalledPackagesChanged;
            }
        }
Esempio n. 40
0
        public static async Task ShowDialog(
            PythonProjectNode project,
            IInterpreterRegistryService service,
            bool browseForExisting = false
        ) {
            using (var view = new AddVirtualEnvironmentView(project, service, project.ActiveInterpreter)) {
                var wnd = new AddVirtualEnvironment(project.Site, view);

                if (browseForExisting) {
                    var path = project.Site.BrowseForDirectory(IntPtr.Zero, project.ProjectHome);
                    if (string.IsNullOrEmpty(path)) {
                        throw new OperationCanceledException();
                    }
                    view.VirtualEnvName = path;
                    view.WillInstallRequirementsTxt = false;
                    await view.WaitForReady();
                    if (view.WillAddVirtualEnv) {
                        await view.Create().HandleAllExceptions(project.Site, typeof(AddVirtualEnvironment));
                        return;
                    }

                    view.ShowBrowsePathError = true;
                    view.BrowseOrigPrefix = DerivedInterpreterFactory.GetOrigPrefixPath(path);
                }

                wnd.VirtualEnvPathTextBox.ScrollToEnd();
                wnd.VirtualEnvPathTextBox.SelectAll();
                wnd.VirtualEnvPathTextBox.Focus();

                wnd.ShowModal();
                var op = wnd._currentOperation;
                if (op != null) {
                    await op;
                }
            }
        }
Esempio n. 41
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;
        }
Esempio n. 42
0
        internal EnvironmentView(
            IInterpreterOptionsService service,
            IInterpreterRegistryService registry,
            IPythonInterpreterFactory factory,
            Redirector redirector
            )
        {
            if (service == null) {
                throw new ArgumentNullException(nameof(service));
            }
            if (registry == null) {
                throw new ArgumentNullException(nameof(registry));
            }
            if (factory == null) {
                throw new ArgumentNullException(nameof(factory));
            }

            _service = service;
            _registry = registry;
            Factory = factory;

            _withDb = factory as IPythonInterpreterFactoryWithDatabase;
            if (_withDb != null) {
                _withDb.IsCurrentChanged += Factory_IsCurrentChanged;
                IsCheckingDatabase = _withDb.IsCheckingDatabase;
                IsCurrent = _withDb.IsCurrent;
            }

            if (_service.IsConfigurable(factory.Configuration.Id)) {
                IsConfigurable = true;
            }

            Description = Factory.Configuration.FullDescription;
            IsDefault = (_service != null && _service.DefaultInterpreter == Factory);

            PrefixPath = Factory.Configuration.PrefixPath;
            InterpreterPath = Factory.Configuration.InterpreterPath;
            WindowsInterpreterPath = Factory.Configuration.WindowsInterpreterPath;
            LibraryPath = Factory.Configuration.LibraryPath;

            Extensions = new ObservableCollection<object>();
            Extensions.Add(new EnvironmentPathsExtensionProvider());
            if (IsConfigurable) {
                Extensions.Add(new ConfigurationExtensionProvider(_service));
            }

            CanBeDefault = Factory.CanBeDefault();

            Vendor = _registry.GetProperty(Factory.Configuration.Id, "Vendor") as string;
            SupportUrl = _registry.GetProperty(Factory.Configuration.Id, "SupportUrl") as string;
        }
Esempio n. 43
0
 internal GlobalInterpreterOptions(PythonToolsService pyService, IInterpreterOptionsService interpreterOptions, IInterpreterRegistryService interpreters) {
     _pyService = pyService;
     _interpreters = interpreters;
     _interpreterOptions = interpreterOptions;
     Load();
 }
Esempio n. 44
0
        public static IPythonInterpreterFactory FindBaseInterpreterFromVirtualEnv(
            string prefixPath,
            string libPath,
            IInterpreterRegistryService service
            )
        {
            string basePath = PathUtils.TrimEndSeparator(GetOrigPrefixPath(prefixPath, libPath));

            if (Directory.Exists(basePath)) {
                return service.Interpreters.FirstOrDefault(interp =>
                    PathUtils.IsSamePath(PathUtils.TrimEndSeparator(interp.Configuration.PrefixPath), basePath)
                );
            }
            return null;
        }
Esempio n. 45
0
        public static InterpreterConfiguration FindInterpreterConfiguration(
            string id,
            string prefixPath,
            IInterpreterRegistryService service,
            IPythonInterpreterFactory baseInterpreter = null
        ) {

            var libPath = DerivedInterpreterFactory.FindLibPath(prefixPath);

            if (baseInterpreter == null) {
                baseInterpreter = DerivedInterpreterFactory.FindBaseInterpreterFromVirtualEnv(
                    prefixPath,
                    libPath,
                    service
                );

                if (baseInterpreter == null) {
                    return null;
                }
            }

            // The interpreter name should be the same as the base interpreter.
            string interpExe = Path.GetFileName(baseInterpreter.Configuration.InterpreterPath);
            string winterpExe = Path.GetFileName(baseInterpreter.Configuration.WindowsInterpreterPath);
            var scripts = new[] { "Scripts", "bin" };
            interpExe = PathUtils.FindFile(prefixPath, interpExe, firstCheck: scripts);
            winterpExe = PathUtils.FindFile(prefixPath, winterpExe, firstCheck: scripts);
            string pathVar = baseInterpreter.Configuration.PathEnvironmentVariable;
            string description = PathUtils.GetFileOrDirectoryName(prefixPath);

            return new InterpreterConfiguration(
                id ?? baseInterpreter.Configuration.Id,
                description,
                prefixPath,
                interpExe,
                winterpExe,
                libPath,
                pathVar,
                baseInterpreter.Configuration.Architecture,
                baseInterpreter.Configuration.Version,
                InterpreterUIMode.CannotBeDefault | InterpreterUIMode.CannotBeConfigured | InterpreterUIMode.SupportsDatabase,
                baseInterpreter != null ? string.Format("({0})", baseInterpreter.Configuration.FullDescription) : ""
            );
        }
Esempio n. 46
0
        internal static void WriteProjectXml(
            IInterpreterRegistryService service,
            TextWriter writer,
            string projectPath,
            string sourcePath,
            string filters,
            string searchPaths,
            string startupFile,
            PythonInterpreterView selectedInterpreter,
            ProjectCustomization customization,
            bool detectVirtualEnv
        ) {
            var projectHome = PathUtils.GetRelativeDirectoryPath(Path.GetDirectoryName(projectPath), sourcePath);

            var project = ProjectRootElement.Create();

            project.DefaultTargets = "Build";
            project.ToolsVersion = "4.0";

            var globals = project.AddPropertyGroup();
            globals.AddProperty("Configuration", "Debug").Condition = " '$(Configuration)' == '' ";
            globals.AddProperty("SchemaVersion", "2.0");
            globals.AddProperty("ProjectGuid", Guid.NewGuid().ToString("B"));
            globals.AddProperty("ProjectHome", projectHome);
            if (PathUtils.IsValidPath(startupFile)) {
                globals.AddProperty("StartupFile", startupFile);
            } else {
                globals.AddProperty("StartupFile", "");
            }
            globals.AddProperty("SearchPath", searchPaths);
            globals.AddProperty("WorkingDirectory", ".");
            globals.AddProperty("OutputPath", ".");

            globals.AddProperty("ProjectTypeGuids", "{888888a0-9f3d-457c-b088-3a5042f75d52}");
            globals.AddProperty("LaunchProvider", DefaultLauncherProvider.DefaultLauncherName);

            var interpreterId = globals.AddProperty(PythonConstants.InterpreterId, "");

            if (selectedInterpreter != null && !String.IsNullOrWhiteSpace(selectedInterpreter.Id)) {
                interpreterId.Value = selectedInterpreter.Id;
            }

            // VS requires property groups with conditions for Debug
            // and Release configurations or many COMExceptions are
            // thrown.
            var debugGroup = project.AddPropertyGroup();
            var releaseGroup = project.AddPropertyGroup();
            debugGroup.Condition = "'$(Configuration)' == 'Debug'";
            releaseGroup.Condition = "'$(Configuration)' == 'Release'";


            var folders = new HashSet<string>();
            var virtualEnvPaths = detectVirtualEnv ? new List<string>() : null;

            foreach (var unescapedFile in EnumerateAllFiles(sourcePath, filters, virtualEnvPaths)) {
                var file = ProjectCollection.Escape(unescapedFile);
                var ext = Path.GetExtension(file);
                var fileType = "Content";
                if (PythonConstants.FileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase) ||
                    PythonConstants.WindowsFileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)) {
                    fileType = "Compile";
                }
                folders.Add(Path.GetDirectoryName(file));
                
                project.AddItem(fileType, file);
            }

            foreach (var folder in folders.Where(s => !string.IsNullOrWhiteSpace(s)).OrderBy(s => s)) {
                project.AddItem("Folder", folder);
            }

            if (selectedInterpreter != null && !String.IsNullOrWhiteSpace(selectedInterpreter.Id)) {
                project.AddItem(
                    MSBuildConstants.InterpreterReferenceItem,
                    selectedInterpreter.Id
                );
            }
            if (virtualEnvPaths != null && virtualEnvPaths.Any() && service != null) {
                foreach (var path in virtualEnvPaths) {
                    var id = MSBuildProjectInterpreterFactoryProvider.GetInterpreterId("$(MSBuildProjectFullPath)", Path.GetFileName(sourcePath));
                    var config = VirtualEnv.FindInterpreterConfiguration(id, path, service);
                    if (config != null) {
                        AddVirtualEnvironment(project, sourcePath, config);

                        if (string.IsNullOrEmpty(interpreterId.Value)) {
                            interpreterId.Value = id;
                        }
                    }
                }
            }

            var imports = project.AddPropertyGroup();
            imports.AddProperty("VisualStudioVersion", "10.0").Condition = " '$(VisualStudioVersion)' == '' ";

            (customization ?? DefaultProjectCustomization.Instance).Process(
                project,
                new Dictionary<string, ProjectPropertyGroupElement> {
                    { "Globals", globals },
                    { "Imports", imports },
                    { "Debug", debugGroup },
                    { "Release", releaseGroup }
                }
            );

            project.Save(writer);
        }
Esempio n. 47
0
        public static async Task<bool> Install(
            IServiceProvider provider,
            IPythonInterpreterFactory factory,
            IInterpreterRegistryService service,
            string package,
            Redirector output = null
        ) {
            factory.ThrowIfNotRunnable("factory");

            var condaFactory = await TryGetCondaFactoryAsync(factory, service); ;
            if (condaFactory == null) {
                throw new InvalidOperationException("Cannot find conda");
            }
            condaFactory.ThrowIfNotRunnable();

            if (output != null) {
                output.WriteLine(Strings.PackageInstalling.FormatUI(package));
                if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation) {
                    output.ShowAndActivate();
                } else {
                    output.Show();
                }
            }

            using (var proc = ProcessOutput.Run(
                condaFactory.Configuration.InterpreterPath,
                new[] { "-m", "conda", "install", "--yes", "-n", factory.Configuration.PrefixPath, package },
                factory.Configuration.PrefixPath,
                UnbufferedEnv,
                false,
                output
            )) {
                var exitCode = await proc;
                if (output != null) {
                    if (exitCode == 0) {
                        output.WriteLine(Strings.PackageInstallSucceeded.FormatUI(package));
                    } else {
                        output.WriteLine(Strings.PackageInstallFailedExitCode.FormatUI(package, exitCode));
                    }
                    if (provider.GetPythonToolsService().GeneralOptions.ShowOutputWindowForPackageInstallation) {
                        output.ShowAndActivate();
                    } else {
                        output.Show();
                    }
                }
                return exitCode == 0;
            }
        }
Esempio n. 48
0
        public static bool CanInstall(
            IPythonInterpreterFactory factory,
            IInterpreterRegistryService service
        ) {
            if (!factory.IsRunnable()) {
                return false;
            }

            return TryGetCondaFactoryAsync(factory, service).WaitAndUnwrapExceptions() != null;
        }