protected OmniSharpTestHost CreateMSBuildTestHost(string path, IEnumerable <ExportDescriptorProvider> additionalExports = null) { var environment = new OmniSharpEnvironment(path, logLevel: LogLevel.Trace); var serviceProvider = TestServiceProvider.Create(this.TestOutput, environment, this.LoggerFactory, _assemblyLoader, _msbuildLocator); return(OmniSharpTestHost.Create(serviceProvider, additionalExports)); }
public void FileArgsCanBeRead() { var env = new OmniSharpEnvironment(additionalArguments: new string[] { "key:nestedKey=value" }); var builder = new ConfigurationBuilder(env); var result = builder.Build(); Assert.False(result.HasError()); Assert.Equal("value", result.Configuration["key:nestedKey"]); }
public static OmniSharpTestHost Create( string path = null, ITestOutputHelper testOutput = null, IEnumerable <KeyValuePair <string, string> > configurationData = null, DotNetCliVersion dotNetCliVersion = DotNetCliVersion.Current, IEnumerable <ExportDescriptorProvider> additionalExports = null) { var environment = new OmniSharpEnvironment(path, logLevel: LogLevel.Trace); var loggerFactory = new LoggerFactory().AddXunit(testOutput); var logger = loggerFactory.CreateLogger <OmniSharpTestHost>(); var sharedTextWriter = new TestSharedTextWriter(testOutput); var dotNetCliService = CreateTestDotNetCliService(dotNetCliVersion, loggerFactory); var info = dotNetCliService.GetInfo(); logger.LogInformation($"Using .NET CLI: {info.Version}"); var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder(); builder.AddInMemoryCollection(configurationData); // We need to set the "UseLegacySdkResolver" for tests because // MSBuild's SDK resolver will not be able to locate the .NET Core SDKs // that we install locally in the ".dotnet" and ".dotnet-legacy" directories. // This property will cause the MSBuild project loader to set the // MSBuildSDKsPath environment variable to the correct path "Sdks" folder // within the appropriate .NET Core SDK. var msbuildProperties = new Dictionary <string, string>() { [$"MSBuild:{nameof(MSBuildOptions.UseLegacySdkResolver)}"] = "true", [$"MSBuild:{nameof(MSBuildOptions.MSBuildSDKsPath)}"] = Path.Combine(info.BasePath, "Sdks") }; builder.AddInMemoryCollection(msbuildProperties); var configuration = builder.Build(); var serviceProvider = new TestServiceProvider(environment, loggerFactory, sharedTextWriter, configuration, NullEventEmitter.Instance, dotNetCliService); var compositionHost = new CompositionHostBuilder(serviceProvider, s_lazyAssemblies.Value, additionalExports) .Build(); var workspace = compositionHost.GetExport <OmniSharpWorkspace>(); WorkspaceInitializer.Initialize(serviceProvider, compositionHost, configuration, logger); var host = new OmniSharpTestHost(serviceProvider, loggerFactory, workspace, compositionHost); // Force workspace to be updated var service = host.GetWorkspaceInformationService(); service.Handle(new WorkspaceInformationRequest()).Wait(); return(host); }
private FileSystemHelper CreateFileSystemHelper(params string[] excludePatterns) { var environment = new OmniSharpEnvironment(TestAssets.Instance.TestAssetsFolder, 1000, LogLevel.Information, null); var options = new OmniSharpOptions(); options.FileOptions.ExcludeSearchPatterns = excludePatterns; var helper = new FileSystemHelper(options, environment); return(helper); }
public void DoesNotCrashOnException() { var env = new OmniSharpEnvironment(); var builder = new ConfigurationBuilder(env); var result = builder.Build(c => throw new Exception("bad thing happened")); Assert.True(result.HasError()); Assert.NotNull(result.Configuration); Assert.Empty(result.Configuration.AsEnumerable()); }
public static OmniSharpTestHost Create(string path = null, ITestOutputHelper testOutput = null, IEnumerable <KeyValuePair <string, string> > configurationData = null, DotNetCliVersion dotNetCliVersion = DotNetCliVersion.Current) { var dotNetPath = Path.Combine( TestAssets.Instance.RootFolder, GetDotNetCliFolderName(dotNetCliVersion), "dotnet"); if (!File.Exists(dotNetPath)) { dotNetPath = Path.ChangeExtension(dotNetPath, ".exe"); } if (!File.Exists(dotNetPath)) { throw new InvalidOperationException($"Local .NET CLI path does not exist. Did you run build.(ps1|sh) from the command line?"); } var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder(); builder.AddInMemoryCollection(configurationData); var configuration = builder.Build(); var environment = new OmniSharpEnvironment(path, logLevel: LogLevel.Trace); var loggerFactory = new LoggerFactory().AddXunit(testOutput); var sharedTextWriter = new TestSharedTextWriter(testOutput); var serviceProvider = new TestServiceProvider(environment, loggerFactory, sharedTextWriter, configuration); var compositionHost = new CompositionHostBuilder(serviceProvider, environment, NullEventEmitter.Instance) .WithAssemblies(s_lazyAssemblies.Value) .Build(); var workspace = compositionHost.GetExport <OmniSharpWorkspace>(); var logger = loggerFactory.CreateLogger <OmniSharpTestHost>(); var dotNetCli = compositionHost.GetExport <DotNetCliService>(); dotNetCli.SetDotNetPath(dotNetPath); var version = dotNetCli.GetVersion(); logger.LogInformation($"Using .NET CLI: {version}"); var oldMSBuildSdksPath = SetMSBuildSdksPath(dotNetCli); WorkspaceInitializer.Initialize(serviceProvider, compositionHost, configuration, logger); var host = new OmniSharpTestHost(serviceProvider, loggerFactory, workspace, compositionHost, oldMSBuildSdksPath); // Force workspace to be updated var service = host.GetWorkspaceInformationService(); service.Handle(new WorkspaceInformationRequest()).Wait(); return(host); }
private PlugInHost CreatePlugInHost(params Assembly[] assemblies) { var environment = new OmniSharpEnvironment(); var sharedTextWriter = new TestSharedTextWriter(this.TestOutput); var serviceProvider = new TestServiceProvider(environment, this.LoggerFactory, sharedTextWriter, new Microsoft.Extensions.Configuration.ConfigurationBuilder().Build()); var compositionHost = new CompositionHostBuilder(serviceProvider, environment, sharedTextWriter, NullEventEmitter.Instance) .WithAssemblies(assemblies) .Build(); return(new PlugInHost(serviceProvider, compositionHost)); }
public void CustomConfigCanBeAdded() { var env = new OmniSharpEnvironment(); var builder = new ConfigurationBuilder(env); var result = builder.Build(c => c.AddInMemoryCollection(new Dictionary <string, string> { { "key", "value" } })); Assert.False(result.HasError()); Assert.Equal("value", result.Configuration["key"]); }
public void AddProvider(LanguageServer server, OmniSharpEnvironment environment) { if (environment.LogLevel <= LogLevel.Debug) { _provider.SetProvider(server, (category, level) => true); } else { _provider.SetProvider(server, (category, level) => LogFilter(category, level, environment)); } }
private PlugInHost CreatePlugInHost(params Assembly[] assemblies) { var environment = new OmniSharpEnvironment(); var sharedTextWriter = new TestSharedTextWriter(this.TestOutput); var serviceProvider = new TestServiceProvider(environment, this.LoggerFactory, sharedTextWriter); var compositionHost = Startup.CreateCompositionHost( serviceProvider: serviceProvider, options: new OmniSharpOptions(), assemblies: assemblies); return(new PlugInHost(serviceProvider, compositionHost)); }
public static OmniSharpTestHost Create( string path = null, ITestOutputHelper testOutput = null, IEnumerable <KeyValuePair <string, string> > configurationData = null, DotNetCliVersion dotNetCliVersion = DotNetCliVersion.Current, IEnumerable <ExportDescriptorProvider> additionalExports = null) { var environment = new OmniSharpEnvironment(path, logLevel: LogLevel.Trace); var serviceProvider = TestServiceProvider.Create(testOutput, environment, configurationData, dotNetCliVersion); return(Create(serviceProvider, additionalExports)); }
public static OmniSharpTestHost Create(string path = null, ITestOutputHelper testOutput = null, IEnumerable <KeyValuePair <string, string> > configurationData = null, bool useLegacyDotNetCli = false) { var dotNetPath = Path.Combine( TestAssets.Instance.RootFolder, useLegacyDotNetCli ? ".dotnet-legacy" : ".dotnet", "dotnet"); if (!File.Exists(dotNetPath)) { dotNetPath = Path.ChangeExtension(dotNetPath, ".exe"); } if (!File.Exists(dotNetPath)) { throw new InvalidOperationException($"Local .NET CLI path does not exist. Did you run build.(ps1|sh) from the command line?"); } var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(configurationData); var configuration = builder.Build(); var environment = new OmniSharpEnvironment(path); var loggerFactory = new LoggerFactory().AddXunit(testOutput); var sharedTextWriter = new TestSharedTextWriter(testOutput); var serviceProvider = new TestServiceProvider(environment, loggerFactory, sharedTextWriter); var omnisharpOptions = new OmniSharpOptions(); ConfigurationBinder.Bind(configuration, omnisharpOptions); var compositionHost = Startup.CreateCompositionHost( serviceProvider, options: omnisharpOptions, assemblies: s_lazyAssemblies.Value); var workspace = compositionHost.GetExport <OmniSharpWorkspace>(); var logger = loggerFactory.CreateLogger <OmniSharpTestHost>(); var dotNetCli = compositionHost.GetExport <DotNetCliService>(); dotNetCli.SetDotNetPath(dotNetPath); var workspaceHelper = new WorkspaceHelper(compositionHost, configuration, omnisharpOptions, loggerFactory); workspaceHelper.Initialize(workspace); return(new OmniSharpTestHost(serviceProvider, loggerFactory, workspace, compositionHost)); }
public static OmniSharpTestHost Create( string path = null, ITestOutputHelper testOutput = null, IConfiguration configurationData = null, DotNetCliVersion dotNetCliVersion = DotNetCliVersion.Current, IEnumerable <ExportDescriptorProvider> additionalExports = null, [CallerMemberName] string callerName = "", IEventEmitter eventEmitter = null) { var environment = new OmniSharpEnvironment(path, logLevel: LogLevel.Trace); var serviceProvider = TestServiceProvider.Create(testOutput, environment, configurationData, dotNetCliVersion, eventEmitter); return(Create(serviceProvider, additionalExports, callerName)); }
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)); }
public void EnvironmentVariableCanBeRead() { var tempValue = Guid.NewGuid().ToString("d"); try { Environment.SetEnvironmentVariable("OMNISHARP_testValue", tempValue); var env = new OmniSharpEnvironment(); var builder = new ConfigurationBuilder(env); var result = builder.Build(c => c.AddInMemoryCollection()); Assert.False(result.HasError()); Assert.Equal(tempValue, result.Configuration["testValue"]); } finally { Environment.SetEnvironmentVariable("OMNISHARP_testValue", null); } }
private Host BuildTestServerAndStart(TextReader reader, ISharedTextWriter writer, Action <Host> programDelegate = null) { var configuration = new Microsoft.Extensions.Configuration.ConfigurationBuilder().Build(); var environment = new OmniSharpEnvironment(); var serviceProvider = CompositionHostBuilder.CreateDefaultServiceProvider(environment, configuration, NullEventEmitter.Instance); var cancelationTokenSource = new CancellationTokenSource(); var host = new Host(reader, writer, environment, serviceProvider, new CompositionHostBuilder(serviceProvider), serviceProvider.GetRequiredService <ILoggerFactory>(), cancelationTokenSource); programDelegate?.Invoke(host); host.Start(); return(host); }
private static (IServiceProvider serviceProvider, CompositionHost compositionHost) CreateCompositionHost( ILanguageServer server, InitializeParams initializeParams, CommandLineApplication application, IServiceCollection services ) { var logLevel = GetLogLevel(initializeParams.Trace); var environment = new OmniSharpEnvironment( Helpers.FromUri(initializeParams.RootUri), Convert.ToInt32(initializeParams.ProcessId ?? -1L), 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); var serviceProvider = CompositionHostBuilder.CreateDefaultServiceProvider(environment, configurationRoot, eventEmitter, services); 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()); }
public void OmnisharpEnvironmentSetsPathCorrectly() { var environment = new OmniSharpEnvironment(TestAssets.Instance.OmniSharpSolutionPath, 1000, -1, LogLevel.Information, TransportType.Http, null); Assert.Equal(TestAssets.Instance.RootFolder, environment.TargetDirectory); }
private static int Run(string[] args) { Console.WriteLine($"OmniSharp: {string.Join(" ", args)}"); // omnisharp.json arguments should not be parsed by the CLI args parser // they will contain "=" so we should filter them out var omnisharpJsonArgs = args.Where(x => x.Contains("=")); var omnisharpApp = new CommandLineApplication(throwOnUnexpectedArg: false); omnisharpApp.HelpOption("-? | -h | --help"); var applicationRootOption = omnisharpApp.Option("-s | --source", "Solution or directory for OmniSharp to point at (defaults to current directory).", CommandOptionType.SingleValue); var portOption = omnisharpApp.Option("-p | --port", "OmniSharp port (defaults to 2000).", CommandOptionType.SingleValue); var logLevelOption = omnisharpApp.Option("-l | --loglevel", "Level of logging (defaults to 'Information').", CommandOptionType.SingleValue); var verboseOption = omnisharpApp.Option("-v | --verbose", "Explicitly set 'Debug' log level.", CommandOptionType.NoValue); var hostPidOption = omnisharpApp.Option("-hpid | --hostPID", "Host process ID.", CommandOptionType.SingleValue); var stdioOption = omnisharpApp.Option("-stdio | --stdio", "Use STDIO over HTTP as OmniSharp commincation protocol.", CommandOptionType.NoValue); var zeroBasedIndicesOption = omnisharpApp.Option("-z | --zero-based-indices", "Use zero based indices in request/responses (defaults to 'false').", CommandOptionType.NoValue); var serverInterfaceOption = omnisharpApp.Option("-i | --interface", "Server interface address (defaults to 'localhost').", CommandOptionType.SingleValue); var encodingOption = omnisharpApp.Option("-e | --encoding", "Input / output encoding for STDIO protocol.", CommandOptionType.SingleValue); var pluginOption = omnisharpApp.Option("-pl | --plugin", "Plugin name(s).", CommandOptionType.MultipleValue); omnisharpApp.OnExecute(() => { var applicationRoot = applicationRootOption.GetValueOrDefault(Directory.GetCurrentDirectory()); var serverPort = portOption.GetValueOrDefault(2000); var logLevel = verboseOption.HasValue() ? LogLevel.Debug : logLevelOption.GetValueOrDefault(LogLevel.Information); var hostPid = hostPidOption.GetValueOrDefault(-1); var transportType = stdioOption.HasValue() ? TransportType.Stdio : TransportType.Http; var serverInterface = serverInterfaceOption.GetValueOrDefault("localhost"); var encodingString = encodingOption.GetValueOrDefault <string>(null); var plugins = pluginOption.Values; var otherArgs = omnisharpApp.RemainingArguments.Union(omnisharpJsonArgs).Distinct(); Configuration.ZeroBasedIndices = zeroBasedIndicesOption.HasValue(); var env = new OmniSharpEnvironment(applicationRoot, serverPort, hostPid, logLevel, transportType, otherArgs.ToArray()); var config = new ConfigurationBuilder() .AddCommandLine(new[] { "--server.urls", $"http://{serverInterface}:{serverPort}" }); // If the --encoding switch was specified, we need to set the InputEncoding and OutputEncoding before // constructing the SharedConsoleWriter. Otherwise, it might be created with the wrong encoding since // it wraps around Console.Out, which gets recreated when OutputEncoding is set. if (transportType == TransportType.Stdio && encodingString != null) { var encoding = Encoding.GetEncoding(encodingString); Console.InputEncoding = encoding; Console.OutputEncoding = encoding; } var writer = new SharedConsoleWriter(); var builder = new WebHostBuilder() .UseConfiguration(config.Build()) .UseEnvironment("OmniSharp") .ConfigureServices(serviceCollection => { serviceCollection.AddSingleton <IOmniSharpEnvironment>(env); serviceCollection.AddSingleton <ISharedTextWriter>(writer); serviceCollection.AddSingleton <PluginAssemblies>(new PluginAssemblies(plugins)); serviceCollection.AddSingleton <IAssemblyLoader, AssemblyLoader>(); }) .UseStartup(typeof(Startup)); if (transportType == TransportType.Stdio) { builder.UseServer(new StdioServer(Console.In, writer)); } else { builder.UseKestrel(); } using (var app = builder.Build()) { app.Start(); var appLifeTime = app.Services.GetRequiredService <IApplicationLifetime>(); Console.CancelKeyPress += (sender, e) => { appLifeTime.StopApplication(); e.Cancel = true; }; if (hostPid != -1) { try { var hostProcess = Process.GetProcessById(hostPid); hostProcess.EnableRaisingEvents = true; hostProcess.OnExit(() => appLifeTime.StopApplication()); } catch { // If the process dies before we get here then request shutdown // immediately appLifeTime.StopApplication(); } } appLifeTime.ApplicationStopping.WaitHandle.WaitOne(); } return(0); }); return(omnisharpApp.Execute(args.Except(omnisharpJsonArgs).ToArray())); }
private void CreateCompositionHost(InitializeParams initializeParams) { _environment = new OmniSharpEnvironment( Helpers.FromUri(initializeParams.RootUri), Convert.ToInt32(initializeParams.ProcessId ?? -1L), GetLogLevel(initializeParams.Trace), _application.OtherArgs.ToArray()); // TODO: Make this work with logger factory differently // Maybe create a child logger factory? _loggerFactory.AddProvider(_server, _environment); _logger = _loggerFactory.CreateLogger <LanguageServerHost>(); var configurationRoot = new ConfigurationBuilder(_environment).Build(); var eventEmitter = new LanguageServerEventEmitter(_server); _serviceProvider = CompositionHostBuilder.CreateDefaultServiceProvider(_environment, configurationRoot, eventEmitter, _services); var plugins = _application.CreatePluginAssemblies(); var assemblyLoader = _serviceProvider.GetRequiredService <IAssemblyLoader>(); var compositionHostBuilder = new CompositionHostBuilder(_serviceProvider) .WithOmniSharpAssemblies() .WithAssemblies(typeof(LanguageServerHost).Assembly) .WithAssemblies(assemblyLoader.LoadByAssemblyNameOrPath(plugins.AssemblyNames).ToArray()); _compositionHost = compositionHostBuilder.Build(); var projectSystems = _compositionHost.GetExports <IProjectSystem>(); var documentSelectors = projectSystems .GroupBy(x => x.Language) .Select(x => ( language: x.Key, selector: new DocumentSelector(x .SelectMany(z => z.Extensions) .Distinct() .Select(z => new DocumentFilter() { Pattern = $"**/*{z}" })) )); _logger.LogTrace( "Configured Document Selectors {@DocumentSelectors}", documentSelectors.Select(x => new { x.language, x.selector }) ); // TODO: Get these with metadata so we can attach languages // This will thne let us build up a better document filter, and add handles foreach type of handler // This will mean that we will have a strategy to create handlers from the interface type _handlers = new RequestHandlers( _compositionHost.GetExports <Lazy <IRequestHandler, OmniSharpRequestHandlerMetadata> >(), documentSelectors ); _logger.LogTrace("--- Handler Definitions ---"); foreach (var handlerCollection in _handlers) { foreach (var handler in handlerCollection) { _logger.LogTrace( "Handler: {Language}:{DocumentSelector}:{Handler}", handlerCollection.Language, handlerCollection.DocumentSelector.ToString(), handler.GetType().FullName ); } } _logger.LogTrace("--- Handler Definitions ---"); }
public void OmnisharpEnvironmentSetsPortCorrectly() { var environment = new OmniSharpEnvironment(TestAssets.Instance.OmniSharpSolutionPath, 1000, -1, LogLevel.Information, TransportType.Http, null); Assert.Equal(1000, environment.Port); }
public void OmnisharpEnvironmentHasNullSolutionFilePathIfDirectorySet() { var environment = new OmniSharpEnvironment(TestAssets.Instance.RootFolder, 1000, -1, LogLevel.Information, TransportType.Http, null); Assert.Null(environment.SolutionFilePath); }
public static PluginAssemblies CreatePluginAssemblies(this CommandLineApplication application, OmniSharpOptions options, OmniSharpEnvironment environment) { return(new PluginAssemblies(application.Plugin.Concat(options.Plugins.GetNormalizedLocationPaths(environment)))); }
public void OmnisharpEnvironmentSetsSolutionPathCorrectly() { var environment = new OmniSharpEnvironment(TestAssets.Instance.OmniSharpSolutionPath, 1000, LogLevel.Information, null); Assert.Equal(TestAssets.Instance.OmniSharpSolutionPath, environment.SolutionFilePath); }