public async Task InitializedAsync_StartsFileChangeDetectors()
        {
            // Arrange
            var initialWorkspaceDirectory = "\\\\testpath";

            var clientSettings = new InitializeParams()
            {
                RootUri = new DocumentUri("file", authority: null, path: initialWorkspaceDirectory, query: null, fragment: null),
            };
            var languageServer = new Mock <IClientLanguageServer>(MockBehavior.Strict);

            languageServer.SetupGet(s => s.ClientSettings)
            .Returns(clientSettings);
            var detector1 = new Mock <IFileChangeDetector>(MockBehavior.Strict);
            var expectedWorkspaceDirectory = "/" + initialWorkspaceDirectory;

            detector1.Setup(detector => detector.StartAsync(expectedWorkspaceDirectory, It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask)
            .Verifiable();
            var detector2 = new Mock <IFileChangeDetector>(MockBehavior.Strict);

            detector2.Setup(detector => detector.StartAsync(expectedWorkspaceDirectory, It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask)
            .Verifiable();
            var workspaceDirectoryPathResolver = new DefaultWorkspaceDirectoryPathResolver(languageServer.Object);
            var detectorManager = new RazorFileChangeDetectorManager(workspaceDirectoryPathResolver, new[] { detector1.Object, detector2.Object });

            // Act
            await detectorManager.InitializedAsync();

            // Assert
            detector1.VerifyAll();
            detector2.VerifyAll();
            languageServer.VerifyAll();
        }
 private void RegisterServices(InitializeParams initParams)
 {
     // we need to register cache service first.
     // optimization service consumes the cache info.
     CacheService.Register(_services, initParams?.initializationOptions?.cacheFolderPath);
     _services.AddService(new ProfileOptimizationService(_services));
 }
 public async Task <InitializeResult> Initialize(JToken token, CancellationToken cancellationToken)
 {
     _initParams = token.ToObject <InitializeParams>();
     MonitorParentProcess(_initParams);
     using (await _prioritizer.InitializePriorityAsync(cancellationToken)) {
         // Force the next handled request to be "initialized", where the work actually happens.
         _initializedPriorityTask = _prioritizer.InitializePriorityAsync(default);
예제 #4
0
        public async Task InitializedAsync_Disposed_ReStopsFileChangeDetectors()
        {
            // Arrange
            var expectedWorkspaceDirectory = "\\\\testpath";
            var clientSettings             = new InitializeParams()
            {
                RootUri = new Uri(expectedWorkspaceDirectory),
            };
            var languageServer = Mock.Of <ILanguageServer>(server => server.ClientSettings == clientSettings);
            var detector       = new Mock <IFileChangeDetector>(MockBehavior.Strict);
            var cts            = new TaskCompletionSource <bool>();

            detector.Setup(d => d.StartAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(cts.Task);
            var stopCount = 0;

            detector.Setup(d => d.Stop()).Callback(() => stopCount++);
            var workspaceDirectoryPathResolver = new DefaultWorkspaceDirectoryPathResolver(languageServer);
            var detectorManager = new RazorFileChangeDetectorManager(workspaceDirectoryPathResolver, new[] { detector.Object });

            // Act
            var initializeTask = detectorManager.InitializedAsync();

            detectorManager.Dispose();

            // Unblock the detector start
            cts.SetResult(true);
            await initializeTask;

            // Assert
            Assert.Equal(2, stopCount);
        }
        private void MonitorParentProcess(InitializeParams p)
        {
            // Monitor parent process
            Process parentProcess = null;

            if (p.processId.HasValue)
            {
                try {
                    parentProcess = Process.GetProcessById(p.processId.Value);
                } catch (ArgumentException) { }

                Debug.Assert(parentProcess != null, "Parent process does not exist");
                if (parentProcess != null)
                {
                    parentProcess.Exited += (s, e) => _sessionTokenSource.Cancel();
                }
            }

            if (parentProcess != null)
            {
                Task.Run(async() => {
                    while (!_sessionTokenSource.IsCancellationRequested)
                    {
                        await Task.Delay(2000);
                        if (parentProcess.HasExited)
                        {
                            _sessionTokenSource.Cancel();
                        }
                    }
                }).DoNotWait();
            }
        }
        /// <summary>
        ///     Update the configuration from the specified initialisation request.
        /// </summary>
        /// <param name="configuration">
        ///     The <see cref="Configuration"/> to update.
        /// </param>
        /// <param name="request">
        ///     The initialisation request.
        /// </param>
        public static void UpdateFrom(this Configuration configuration, InitializeParams request)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

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

            JToken initializationParameters = request.InitializationOptions as JToken;

            if (initializationParameters == null)
            {
                return;
            }

            JObject json = initializationParameters.SelectToken(Configuration.SectionName) as JObject;

            if (json == null)
            {
                return;
            }

            configuration.UpdateFrom(json);
        }
예제 #7
0
        public override async Task <InitializeResult> Initialize(InitializeParams @params, CancellationToken cancellationToken)
        {
            _disposableBag.ThrowIfDisposed();
            await DoInitializeAsync(@params, cancellationToken);

            return(GetInitializeResult());
        }
        public async Task InitializeAsync_InvokesHandlerWithParamsAndCapabilities()
        {
            // Arrange
            var originalInitParams = new InitializeParams()
            {
                Capabilities = new ClientCapabilities()
                {
                    Experimental = true
                },
                RootUri = new Uri("C:/path/to/workspace"),
            };
            var initializeResult = new InitializeResult();
            var handler          = new Mock <IRequestHandler <InitializeParams, InitializeResult> >(MockBehavior.Strict);

            handler.Setup(h => h.HandleRequestAsync(It.IsAny <InitializeParams>(), It.IsAny <ClientCapabilities>(), It.IsAny <CancellationToken>()))
            .Callback <InitializeParams, ClientCapabilities, CancellationToken>((initParams, clientCapabilities, token) =>
            {
                Assert.True((bool)initParams.Capabilities.Experimental);
                Assert.Equal(originalInitParams.RootUri.AbsoluteUri, initParams.RootUri.AbsoluteUri);
            })
            .Returns(Task.FromResult(initializeResult))
            .Verifiable();
            var metadata = Mock.Of <IRequestHandlerMetadata>(rhm => rhm.MethodName == Methods.InitializeName, MockBehavior.Strict);

            using var languageServer = new RazorHtmlCSharpLanguageServer(new[] { new Lazy <IRequestHandler, IRequestHandlerMetadata>(() => handler.Object, metadata) });
            var serializedInitParams = JToken.FromObject(originalInitParams);

            // Act
            var result = await languageServer.InitializeAsync(serializedInitParams, CancellationToken.None).ConfigureAwait(false);

            // Assert
            Assert.Same(initializeResult, result);
            handler.VerifyAll();
        }
        private async Task HandleInitializeRequest(
            InitializeParams initializeParams,
            RequestContext <InitializeResult> requestContext)
        {
            // Grab the workspace path from the parameters
            _workspacePath = initializeParams.RootPath;

            await requestContext.SendResult(
                new InitializeResult
            {
                Capabilities = new ServerCapabilities
                {
                    TextDocumentSync   = TextDocumentSyncKind.Incremental,
                    DefinitionProvider = true,
                    //ReferencesProvider = true,
                    DocumentHighlightProvider = true,
                    DocumentSymbolProvider    = true,
                    WorkspaceSymbolProvider   = true,
                    HoverProvider             = true,
                    //CodeActionProvider = true,
                    CompletionProvider = new Protocol.LanguageServer.CompletionOptions
                    {
                        ResolveProvider   = false,
                        TriggerCharacters = new [] { ".", ":" }
                    },
                    SignatureHelpProvider = new SignatureHelpOptions
                    {
                        TriggerCharacters = new[] { "(" }
                    }
                }
            });
        }
예제 #10
0
        private async Task DoInitializeAsync(InitializeParams @params, CancellationToken token)
        {
            _disposableBag.ThrowIfDisposed();
            Analyzer = await AnalysisQueue.ExecuteInQueueAsync(ct => CreateAnalyzer(@params.initializationOptions.interpreter, token), AnalysisPriority.High);

            _disposableBag.ThrowIfDisposed();
            _clientCaps      = @params.capabilities;
            _traceLogging    = @params.initializationOptions.traceLogging;
            _analysisUpdates = @params.initializationOptions.analysisUpdates;

            Analyzer.EnableDiagnostics = _clientCaps?.python?.liveLinting ?? false;
            _reloadModulesQueueItem    = new ReloadModulesQueueItem(Analyzer);

            if (@params.initializationOptions.displayOptions != null)
            {
                DisplayOptions = @params.initializationOptions.displayOptions;
            }
            _displayTextBuilder = DocumentationBuilder.Create(DisplayOptions);

            DisplayStartupInfo();

            if (@params.rootUri != null)
            {
                _rootDir = @params.rootUri.ToAbsolutePath();
            }
            else if (!string.IsNullOrEmpty(@params.rootPath))
            {
                _rootDir = PathUtils.NormalizePath(@params.rootPath);
            }

            SetSearchPaths(@params.initializationOptions.searchPaths);
            SetTypeStubSearchPaths(@params.initializationOptions.typeStubSearchPaths);

            Analyzer.Interpreter.ModuleNamesChanged += Interpreter_ModuleNamesChanged;
        }
예제 #11
0
        public Task <InitializeResult> Initialize(JToken token, CancellationToken cancellationToken)
        {
            _initParams = token.ToObject <InitializeParams>();
            MonitorParentProcess(_initParams);

            return(_server.Initialize(_initParams, cancellationToken));
        }
예제 #12
0
        private static Task InitializeAsync(ILanguageServer server, InitializeParams request, CancellationToken cancellationToken)
        {
            var logger = server.GetRequiredService <ILogger <Program> >();

            logger.LogTrace("initializing service");
            return(Task.CompletedTask);
        }
        public async Task Initialize(CancellationToken token)
        {
            var @params = new InitializeParams {
                Trace                 = _trace,
                Capabilities          = _clientCapabilities,
                ClientInfo            = _clientInfo,
                RootUri               = _rootUri,
                RootPath              = _rootUri?.GetFileSystemPath(),
                WorkspaceFolders      = new Container <WorkspaceFolder>(_workspaceFoldersManager.CurrentWorkspaceFolders),
                InitializationOptions = _initializationOptions
            };

            RegisterCapabilities(@params.Capabilities);
            _workDoneManager.Initialize(@params.Capabilities.Window);

            ClientSettings = @params;

            _connection.Open();
            var serverParams = await this.RequestLanguageProtocolInitialize(ClientSettings, token);

            _receiver.Initialized();

            ServerSettings = serverParams;
            if (_collection.ContainsHandler(typeof(IRegisterCapabilityHandler)))
            {
                RegistrationManager.RegisterCapabilities(serverParams.Capabilities);
            }

            // TODO: pull supported fields and add any static registrations to the registration manager
            this.SendLanguageProtocolInitialized(new InitializedParams());
        }
예제 #14
0
        public async Task InitializedAsync_StartsFileChangeDetectors()
        {
            // Arrange
            var expectedWorkspaceDirectory = "\\\\testpath";
            var clientSettings             = new InitializeParams()
            {
                RootUri = new Uri(expectedWorkspaceDirectory),
            };
            var languageServer = Mock.Of <ILanguageServer>(server => server.ClientSettings == clientSettings);
            var detector1      = new Mock <IFileChangeDetector>(MockBehavior.Strict);

            detector1.Setup(detector => detector.StartAsync(expectedWorkspaceDirectory, It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask)
            .Verifiable();
            var detector2 = new Mock <IFileChangeDetector>(MockBehavior.Strict);

            detector2.Setup(detector => detector.StartAsync(expectedWorkspaceDirectory, It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask)
            .Verifiable();
            var workspaceDirectoryPathResolver = new DefaultWorkspaceDirectoryPathResolver(languageServer);
            var detectorManager = new RazorFileChangeDetectorManager(workspaceDirectoryPathResolver, new[] { detector1.Object, detector2.Object });

            // Act
            await detectorManager.InitializedAsync();

            // Assert
            detector1.VerifyAll();
            detector2.VerifyAll();
        }
 public async Task <InitializeResult> Initialize(JToken token, CancellationToken cancellationToken)
 {
     _initParams = token.ToObject <InitializeParams>();
     MonitorParentProcess(_initParams);
     using (await _prioritizer.InitializePriorityAsync(cancellationToken)) {
         return(await _server.InitializeAsync(_initParams, cancellationToken));
     }
 }
예제 #16
0
        public Task <InitializeResult> Initialize(JToken token)
        {
            var p = token.ToObject <InitializeParams>();

            MonitorParentProcess(p);

            _initParams = p;
            return(_server.Initialize(p));
        }
예제 #17
0
 public Task <InitializeResult> InitializeAsync(InitializeParams initializeParams, CancellationToken cancellationToken)
 {
     Contract.ThrowIfTrue(_clientCapabilities != null, $"{nameof(InitializeAsync)} called multiple times");
     _clientCapabilities = (VSClientCapabilities)initializeParams.Capabilities;
     return(Task.FromResult(new InitializeResult
     {
         Capabilities = _languageClient.GetCapabilities(),
     }));
 }
예제 #18
0
        public Task <InitializeResult> InitializeAsync(InitializeParams @params, CancellationToken cancellationToken = default)
        {
            _disposableBag.ThrowIfDisposed();
            _initParams = @params;
            _log        = _services.GetService <ILogger>();

            _log?.Log(TraceEventType.Information, Resources.LanguageServerVersion.FormatInvariant(Assembly.GetExecutingAssembly().GetName().Version));

            return(Task.FromResult(GetInitializeResult()));
        }
예제 #19
0
        // Internal for testing
        internal static string ResolveWorkspaceDirectory(InitializeParams clientSettings)
        {
            if (clientSettings.RootUri == null)
            {
                // RootUri was added in LSP3, fallback to RootPath
                return(clientSettings.RootPath);
            }

            return(clientSettings.RootUri.LocalPath);
        }
예제 #20
0
        public override InitializeResult OnInitialize(InitializeParams parameters)
        {
            this.RemoteConsole.NoLogsMessageNotification = NoLogsMessageNotification;
            var    rootDirectory = new DirectoryInfo(parameters.rootPath);
            string workspaceName = rootDirectory.Name + "#" + parameters.processId;

            // Initialize the workspace
            typeCobolWorkspace = new Workspace(rootDirectory.FullName, workspaceName, _MessagesActionsQueue, Logger);
            //Propagate LSR testing options.
            if (LsrSourceTesting)
            {
                typeCobolWorkspace.IsLsrSourceTesting = LsrSourceTesting;
            }
            if (LsrScannerTesting)
            {
                typeCobolWorkspace.IsLsrScannerTesting = LsrScannerTesting;
            }
            if (LsrPreprocessTesting)
            {
                typeCobolWorkspace.IsLsrPreprocessinTesting = LsrPreprocessTesting;
            }
            if (LsrParserTesting)
            {
                typeCobolWorkspace.IsLsrParserTesting = LsrParserTesting;
            }
            if (LsrSemanticTesting)
            {
                typeCobolWorkspace.IsLsrSemanticTesting = LsrSemanticTesting;
            }

            typeCobolWorkspace.UseAntlrProgramParsing = UseAntlrProgramParsing;
            typeCobolWorkspace.TimerDisabledOption    = TimerDisabledOption;
            typeCobolWorkspace.LoadingIssueEvent     += LoadingIssueDetected;
            typeCobolWorkspace.ExceptionTriggered    += ExceptionTriggered;
            typeCobolWorkspace.WarningTrigger        += WarningTrigger;
            // Return language server capabilities
            var initializeResult = base.OnInitialize(parameters);

            initializeResult.capabilities.textDocumentSync = TextDocumentSyncKind.Incremental;
            initializeResult.capabilities.hoverProvider    = true;
            CompletionOptions completionOptions = new CompletionOptions();

            completionOptions.resolveProvider   = false;
            completionOptions.triggerCharacters = new string[] { "::" };
            initializeResult.capabilities.completionProvider = completionOptions;
            SignatureHelpOptions sigHelpOptions = new SignatureHelpOptions {
                triggerCharacters = new string[0]
            };

            initializeResult.capabilities.signatureHelpProvider = sigHelpOptions;

            return(initializeResult);
        }
예제 #21
0
        public async Task <InitializeResult> InitializeAsync(InitializeParams initializeParams, CancellationToken cancellationToken)
        {
            _clientCapabilities = (VSClientCapabilities)initializeParams.Capabilities;

            var serverCapabilities = await _requestHandlerProvider.ExecuteRequestAsync <InitializeParams, InitializeResult>(Methods.InitializeName,
                                                                                                                            initializeParams, _clientCapabilities, _clientName, cancellationToken).ConfigureAwait(false);

            // Always support hover - if any LSP client for a content type advertises support,
            // then the liveshare provider is disabled.  So we must provide for both C# and razor
            // until https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1106064/ is fixed
            // or we have different content types.
            serverCapabilities.Capabilities.HoverProvider = true;
            return(serverCapabilities);
        }
예제 #22
0
        /// <summary>
        ///     Initialise the language server.
        /// </summary>
        /// <param name="workspaceRoot">
        ///     The workspace root.
        /// </param>
        /// <param name="initializationOptions">
        ///     An optional <see cref="object"/> representing additional options to send to the server.
        /// </param>
        /// <param name="cancellationToken">
        ///     An optional <see cref="CancellationToken"/> that can be used to cancel the operation.
        /// </param>
        /// <returns>
        ///     A <see cref="Task"/> representing initialisation.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        ///     <see cref="Initialize(string, object, CancellationToken)"/> has already been called.
        ///
        ///     <see cref="Initialize(string, object, CancellationToken)"/> can only be called once per <see cref="LanguageClient"/>; if you have called <see cref="Shutdown"/>, you will need to use a new <see cref="LanguageClient"/>.
        /// </exception>
        public async Task Initialize(string workspaceRoot, object initializationOptions = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (IsInitialized)
            {
                throw new InvalidOperationException("Client has already been initialised.");
            }

            try
            {
                await Start();

                var initializeParams = new InitializeParams
                {
                    RootPath              = workspaceRoot,
                    RootUri               = new Uri(workspaceRoot), // ho changed
                    Capabilities          = ClientCapabilities,
                    ProcessId             = Process.GetCurrentProcess().Id,
                    InitializationOptions = initializationOptions
                };

                Log.LogDebug("Sending 'initialize' message to language server...");

                var result = await SendRequest <InitializeResult>("initialize", initializeParams, cancellationToken).ConfigureAwait(false);

                if (result == null)
                {
                    throw new LspException("Server replied to 'initialize' request with a null response.");
                }

                _dynamicRegistrationHandler.ServerCapabilities = result.Capabilities;

                Log.LogDebug("Sent 'initialize' message to language server.");

                Log.LogDebug("Sending 'initialized' notification to language server...");

                SendNotification("initialized");

                Log.LogDebug("Sent 'initialized' notification to language server.");

                IsInitialized = true;
                _readyCompletion.TrySetResult(null);
            }
            catch (Exception initializationError)
            {
                // Capture the initialisation error so anyone awaiting IsReady will also see it.
                _readyCompletion.TrySetException(initializationError);

                throw;
            }
        }
예제 #23
0
        public Task <InitializeResult> Handle(InitializeParams request, CancellationToken cancellationToken)
        {
            _router.Window.Log("Initialize received: " + request.RootPath);

            return(Task.FromResult(new InitializeResult()
            {
                Capabilities = new ServerCapabilities()
                {
                    TextDocumentSync =
                    {
                        Kind = TextDocumentSyncKind.Incremental,
                    }
                }
            }));
        }
        public void ResolveWorkspaceDirectory_RootUriUnavailable_UsesRootPath()
        {
            // Arrange
            var expectedWorkspaceDirectory = "/testpath";
            var clientSettings             = new InitializeParams()
            {
                RootPath = expectedWorkspaceDirectory
            };

            // Act
            var workspaceDirectory = RazorFileChangeDetectorManager.ResolveWorkspaceDirectory(clientSettings);

            // Assert
            Assert.Equal(expectedWorkspaceDirectory, workspaceDirectory);
        }
        public async Task <InitializeResult> Initialize(JToken token, CancellationToken cancellationToken)
        {
            _initParams = token.ToObject <InitializeParams>();
            MonitorParentProcess(_initParams);
            RegisterServices(_initParams);

            using (await _prioritizer.InitializePriorityAsync(cancellationToken)) {
                Debug.Assert(!_initialized);
                // Force the next handled request to be "initialized", where the work actually happens.
                _initializedPriorityTask = _prioritizer.InitializedPriorityAsync();
                var result = await _server.InitializeAsync(_initParams, cancellationToken);

                return(result);
            }
        }
예제 #26
0
        private static Task OnInitializedAsync(ILanguageServer languageServer, InitializeParams request, InitializeResult response, CancellationToken cancellationToken)
        {
            response.Capabilities.TextDocumentSync.Kind             = TextDocumentSyncKind.Full;
            response.Capabilities.TextDocumentSync.Options !.Change = TextDocumentSyncKind.Full;
            languageServer.Services.GetRequiredService <PublishDiagnosticsRunner>().Start();
            languageServer.Services.GetRequiredService <RhetosProjectMonitor>().Start();

            if (request.ProcessId.HasValue)
            {
                var orphanedProcessMonitor = languageServer.Services.GetRequiredService <OrphanedProcessMonitor>();
                orphanedProcessMonitor.SetHostProcessId((int)request.ProcessId.Value);
                orphanedProcessMonitor.Start();
            }

            return(Task.CompletedTask);
        }
        public void ResolveWorkspaceDirectory_RootUriPrefered()
        {
            // Arrange
            var expectedWorkspaceDirectory = "\\\\testpath";
            var clientSettings             = new InitializeParams()
            {
                RootPath = "/somethingelse",
                RootUri  = new Uri(expectedWorkspaceDirectory),
            };

            // Act
            var workspaceDirectory = RazorFileChangeDetectorManager.ResolveWorkspaceDirectory(clientSettings);

            // Assert
            Assert.Equal(expectedWorkspaceDirectory, workspaceDirectory);
        }
예제 #28
0
        public void Resolve_RootUriUnavailable_UsesRootPath()
        {
            // Arrange
            var expectedWorkspaceDirectory = "/testpath";
            var clientSettings             = new InitializeParams()
            {
                RootPath = expectedWorkspaceDirectory
            };
            var server = Mock.Of <IClientLanguageServer>(server => server.ClientSettings == clientSettings, MockBehavior.Strict);
            var workspaceDirectoryPathResolver = new DefaultWorkspaceDirectoryPathResolver(server);

            // Act
            var workspaceDirectoryPath = workspaceDirectoryPathResolver.Resolve();

            // Assert
            Assert.Equal(expectedWorkspaceDirectory, workspaceDirectoryPath);
        }
예제 #29
0
        private static (IServiceProvider serviceProvider, CompositionHost compositionHost) CreateCompositionHost(
            ILanguageServer server,
            InitializeParams initializeParams,
            CommandLineApplication application,
            IServiceCollection services,
            Action <ILoggingBuilder> configureLogging)
        {
            var logLevel    = GetLogLevel(initializeParams.Trace);
            var environment = new OmniSharpEnvironment(
                // TODO: Support solution selection from the server side in the future
                // For now selection can be done by passing -s to the server
                !string.IsNullOrEmpty(application.ApplicationRoot) ? application.ApplicationRoot : Helpers.FromUri(initializeParams.RootUri),
                Convert.ToInt32(initializeParams.ProcessId ?? application.HostPid),
                application.LogLevel < logLevel ? application.LogLevel : logLevel,
                application.OtherArgs.ToArray());

            var configurationRoot = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
                                    .AddConfiguration(new ConfigurationBuilder(environment).Build())
                                    .AddConfiguration(server.Configuration.GetSection("csharp"))
                                    .AddConfiguration(server.Configuration.GetSection("omnisharp"))
                                    .Build()
            ;

            var eventEmitter = new LanguageServerEventEmitter(server);

            services.AddSingleton(server)
            .AddSingleton <ILanguageServerFacade>(server);

            var serviceProvider =
                CompositionHostBuilder.CreateDefaultServiceProvider(environment, configurationRoot, eventEmitter,
                                                                    services, GetLogBuilderAction(configureLogging, environment.LogLevel));

            var loggerFactory = serviceProvider.GetService <ILoggerFactory>();
            var logger        = loggerFactory.CreateLogger <LanguageServerHost>();

            var options = serviceProvider.GetRequiredService <IOptionsMonitor <OmniSharpOptions> >();
            var plugins = application.CreatePluginAssemblies(options.CurrentValue, environment);

            var assemblyLoader         = serviceProvider.GetRequiredService <IAssemblyLoader>();
            var compositionHostBuilder = new CompositionHostBuilder(serviceProvider)
                                         .WithOmniSharpAssemblies()
                                         .WithAssemblies(typeof(LanguageServerHost).Assembly)
                                         .WithAssemblies(assemblyLoader.LoadByAssemblyNameOrPath(logger, plugins.AssemblyNames).ToArray());

            return(serviceProvider, compositionHostBuilder.Build(environment.TargetDirectory));
        }
예제 #30
0
        protected override Task Initialize()
        {
            // Add handlers for common events
            this.SetEventHandler(PublishDiagnosticsNotification.Type, HandlePublishDiagnosticsEvent);

            // Send the 'initialize' request and wait for the response
            var initializeParams = new InitializeParams
            {
                RootPath     = "",
                Capabilities = new ClientCapabilities()
            };

            return(this.SendRequest(
                       InitializeRequest.Type,
                       initializeParams,
                       true));
        }