Пример #1
0
        private void InitializeLogging()
        {
            try {
                var registry = ComponentModel.GetService <IInterpreterRegistryService>();
                if (registry != null)   // not available in some test cases...
                // log interesting stats on startup
                {
                    var installed   = registry.Configurations.Count();
                    var installedV2 = registry.Configurations.Count(c => c.Version.Major == 2);
                    var installedV3 = registry.Configurations.Count(c => c.Version.Major == 3);

                    _logger.LogEvent(PythonLogEvent.InstalledInterpreters, new Dictionary <string, object> {
                        { "Total", installed },
                        { "3x", installedV3 },
                        { "2x", installedV2 }
                    });
                }

                _logger.LogEvent(PythonLogEvent.Experiments, new Dictionary <string, object> {
                    { "NoDatabaseFactory", ExperimentalOptions.NoDatabaseFactory },
                    { "AutoDetectCondaEnvironments", ExperimentalOptions.AutoDetectCondaEnvironments },
                    { "UseCondaPackageManager", ExperimentalOptions.UseCondaPackageManager },
                    { "UseVsCodeDebugger", ExperimentalOptions.UseVsCodeDebugger }
                });
            } catch (Exception ex) {
                Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
            }
        }
Пример #2
0
        public void OnTelemetryEvent(JToken arg)
        {
            if (!(arg is JObject telemetry))
            {
                return;
            }

            Trace.WriteLine(telemetry.ToString());
            try {
                var te = telemetry.ToObject <PylanceTelemetryEvent>();
                if (te == null)
                {
                    return;
                }

                if (te.Exception == null)
                {
                    _logger.LogEvent(te.EventName, te.Properties, te.Measurements);
                }
                else
                {
                    _logger.LogFault(new PylanceException(te.EventName, te.Exception.stack), te.EventName, false);
                }

                // Special case language_server/analysis_complete. We need this for testing so we
                // know when it's okay to try to bring up intellisense
                if (te.EventName == "language_server/analysis_complete")
                {
                    AnalysisComplete.Invoke(this, EventArgs.Empty);
                }
            } catch {
            }
        }
Пример #3
0
        public override Task ApplyAsync()
        {
            _logger?.LogEvent(PythonLogEvent.InstallEnv, null);

            var ids = AvailablePackages.OfType <SetupPackageView>().Where(p => p.IsChecked).Select(p => p.PackageId).ToArray();

            if (ids.Length > 0)
            {
                IVsProjectAcquisitionSetupDriver driver;
                if (_retargeting != null &&
                    ErrorHandler.Succeeded(_retargeting.GetSetupDriver(VSConstants.SetupDrivers.SetupDriver_VS, out driver)) &&
                    driver != null)
                {
                    var task = driver.Install(ids);
                    if (task != null)
                    {
                        task.Start();
                    }
                }
            }
            else
            {
                Debug.Fail("Accept button should have been disabled");
            }

            return(Task.CompletedTask);
        }
Пример #4
0
        private void OnAnalysisProcessExited(object sender, AbnormalAnalysisExitEventArgs e)
        {
            _analyzerAbnormalExitCount++;

            if (_logger == null)
            {
                return;
            }

            var msg = new StringBuilder()
                      .AppendFormat("Exit Code: {0}", e.ExitCode)
                      .AppendLine()
                      .AppendLine(" ------ STD ERR ------ ")
                      .Append(e.StdErr)
                      .AppendLine(" ------ END STD ERR ------ ");

            _logger.LogEvent(
                PythonLogEvent.AnalysisExitedAbnormally,
                msg.ToString()
                );

            if (_analyzerAbnormalExitCount < 5)
            {
                // Start a new analyzer
                ReanalyzeAsync().HandleAllExceptions(_site).DoNotWait();
            }
        }
        public async override Task ApplyAsync()
        {
            bool failed = false;

            if (IsCustomInterpreter)
            {
                try {
                    await ApplyCustomAsync();
                } catch (Exception ex) when(!ex.IsCriticalException())
                {
                    failed = true;
                    throw;
                } finally {
                    _logger?.LogEvent(PythonLogEvent.AddExistingEnv, new AddExistingEnvInfo()
                    {
                        Failed          = failed,
                        LanguageVersion = VersionName,
                        Architecture    = ArchitectureName,
                        Custom          = true,
                        Global          = RegisterCustomEnv,
                    });
                }
            }
            else
            {
                try {
                    await ApplyExistingAsync();
                } catch (Exception ex) when(!ex.IsCriticalException())
                {
                    failed = true;
                    throw;
                } finally {
                    _logger?.LogEvent(PythonLogEvent.AddExistingEnv, new AddExistingEnvInfo()
                    {
                        Failed          = failed,
                        LanguageVersion = SelectedInterpreter.LanguageVersion,
                        Architecture    = SelectedInterpreter.Architecture,
                    });
                }
            }
        }
        public override Task ApplyAsync()
        {
            _logger?.LogEvent(PythonLogEvent.InstallEnv, null);

            var    setupService  = Site.GetService(typeof(SVsSetupCompositionService)) as IVsSetupCompositionService;
            string installerPath = setupService?.InstallerPath;

            if (File.Exists(installerPath))
            {
                Process.Start(installerPath)?.Dispose();
            }
            return(Task.CompletedTask);
        }
Пример #7
0
        public override void Invoke(object inArg, IntPtr outArg, OLECMDEXECOPT options)
        {
            // getting the current value
            if (outArg != IntPtr.Zero)
            {
                var text = _envSwitchMgr.CurrentFactory?.Configuration.Description ?? string.Empty;
                Marshal.GetNativeVariantForObject(text, outArg);
            }

            // setting the current value
            if (inArg != null)
            {
                var text    = inArg as string;
                var factory = _envSwitchMgr.AllFactories.SingleOrDefault(f => f.Configuration.Description == text);
                if (factory != null)
                {
                    _logger?.LogEvent(PythonLogEvent.SelectEnvFromToolbar, new SelectEnvFromToolbarInfo()
                    {
                        InterpreterId = factory.Configuration.Id,
                        Architecture  = factory.Configuration.Architecture.ToString(),
                        Version       = factory.Configuration.Version.ToString(),
                        IsIronPython  = factory.Configuration.IsIronPython(),
                    });

                    SwitchToFactoryAsync(factory).HandleAllExceptions(_serviceProvider, GetType()).DoNotWait();
                }
                else
                {
                    // The special "Add Environment..." entry, or any entry that no longer exists brings up the add dialog
                    _logger?.LogEvent(PythonLogEvent.AddEnvFromToolbar, null);
                    AddEnvironmentCommand
                    .AddEnvironmentAsync(_envSwitchMgr, _serviceProvider, AddEnvironmentDialog.PageKind.VirtualEnvironment)
                    .HandleAllExceptions(_serviceProvider, GetType())
                    .DoNotWait();
                }
            }
        }
Пример #8
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,
            });
        }
Пример #9
0
        private async void Listener_ProgressUpdate(Dictionary <string, AnalysisProgress> status)
        {
            bool anyUpdates = status.Any();

            if (!anyUpdates)
            {
                lock (_environments) {
                    anyUpdates = _currentlyRefreshing.Count != 0;
                }
            }

            if (anyUpdates)
            {
                var updates = new List <DispatcherOperation>();

                lock (_environments) {
                    foreach (var env in _environments)
                    {
                        if (env.Factory == null)
                        {
                            continue;
                        }

                        AnalysisProgress progress;
                        if (status.TryGetValue(AnalyzerStatusUpdater.GetIdentifier(env.Factory), out progress))
                        {
                            _currentlyRefreshing[env.Factory] = progress;

                            updates.Add(env.Dispatcher.InvokeAsync(() => {
                                if (progress.Maximum > 0)
                                {
                                    var percent = progress.Progress * 100 / progress.Maximum;
                                    var current = env.RefreshDBProgress;
                                    // Filter out small instances of 'reverse'
                                    // progress, but allow big jumps backwards.
                                    if (percent > current || percent < current - 25)
                                    {
                                        env.RefreshDBProgress = percent;
                                    }
                                    env.IsRefreshDBProgressIndeterminate = false;
                                }
                                else
                                {
                                    env.IsRefreshDBProgressIndeterminate = true;
                                }
                                env.RefreshDBMessage = progress.Message;
                                env.IsRefreshingDB   = true;
                            }));
                        }
                        else if (_currentlyRefreshing.TryGetValue(env.Factory, out progress))
                        {
                            _currentlyRefreshing.Remove(env.Factory);
                            try {
                                TelemetryLogger?.LogEvent(PythonLogEvent.AnalysisCompleted, new AnalysisInfo {
                                    InterpreterId   = env.Factory.Configuration.Id,
                                    AnalysisSeconds = progress.Seconds
                                });
                            } catch (Exception ex) {
                                Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
                            }
                            updates.Add(env.Dispatcher.InvokeAsync(() => {
                                env.IsRefreshingDB = false;
                                env.IsRefreshDBProgressIndeterminate = false;
                                env.RefreshDBMessage = string.Empty;
                                CommandManager.InvalidateRequerySuggested();
                            }));
                        }
                    }
                }

                try {
                    await Task.WhenAll(updates.Select(d => d.Task).ToArray());
                } catch (OperationCanceledException) {
                    // Tasks were cancelled, which probably means we are closing.
                    // In this case, _timer will be disposed before the next update.
                }
            }

            if (Interlocked.Decrement(ref _listenerTimeToLive) == 0)
            {
                // It's time to reset the listener. We do this periodically in
                // case the global mutex has become abandoned. By releasing our
                // handle, it should go away and any errors (which may be caused
                // by users killing the analyzer) become transient rather than
                // permanent.

                // Because we are currently on the listener's thread, we need to
                // recreate on a separate thread so that this one can terminate.
                Task.Run((Action)CreateListener)
                .HandleAllExceptions(Site, GetType())
                .DoNotWait();
            }
        }