-
Notifications
You must be signed in to change notification settings - Fork 416
/
Startup.cs
293 lines (249 loc) · 11.2 KB
/
Startup.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
using System;
using System.Collections.Generic;
using System.Composition.Hosting;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OmniSharp.Eventing;
using OmniSharp.FileWatching;
using OmniSharp.Host.Internal;
using OmniSharp.Mef;
using OmniSharp.Middleware;
using OmniSharp.Options;
using OmniSharp.Roslyn;
using OmniSharp.Roslyn.Options;
using OmniSharp.Services;
using OmniSharp.Stdio.Logging;
using OmniSharp.Stdio.Services;
using OmniSharp.Utilities;
namespace OmniSharp
{
public class Startup
{
private readonly IOmniSharpEnvironment _env;
public IConfiguration Configuration { get; }
public OmniSharpWorkspace Workspace { get; private set; }
public CompositionHost PluginHost { get; private set; }
public Startup(IOmniSharpEnvironment env)
{
_env = env;
var configBuilder = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile(Constants.ConfigFile, optional: true)
.AddEnvironmentVariables("OMNISHARP_");
if (env.AdditionalArguments?.Length > 0)
{
configBuilder.AddCommandLine(env.AdditionalArguments);
}
// Use the global omnisharp config if there's any in the shared path
configBuilder.CreateAndAddGlobalOptionsFile(env);
// Use the local omnisharp config if there's any in the root path
configBuilder.AddJsonFile(
new PhysicalFileProvider(env.TargetDirectory).WrapForPolling(),
Constants.OptionsFile,
optional: true,
reloadOnChange: true);
Configuration = configBuilder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
// Add the omnisharp workspace to the container
services.AddSingleton(typeof(OmniSharpWorkspace), _ => Workspace);
services.AddSingleton(typeof(CompositionHost), _ => PluginHost);
// Caching
services.AddSingleton<IMemoryCache, MemoryCache>();
services.AddOptions();
// Setup the options from configuration
services.Configure<OmniSharpOptions>(Configuration);
}
public static CompositionHost CreateCompositionHost(IServiceProvider serviceProvider, OmniSharpOptions options, IEnumerable<Assembly> assemblies)
{
var config = new ContainerConfiguration();
assemblies = assemblies
.Concat(new[] { typeof(OmniSharpWorkspace).GetTypeInfo().Assembly, typeof(IRequest).GetTypeInfo().Assembly })
.Distinct();
foreach (var assembly in assemblies)
{
config = config.WithAssembly(assembly);
}
var memoryCache = serviceProvider.GetService<IMemoryCache>();
var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
var env = serviceProvider.GetService<IOmniSharpEnvironment>();
var writer = serviceProvider.GetService<ISharedTextWriter>();
var loader = serviceProvider.GetService<IAssemblyLoader>();
var fileSystemWatcher = new ManualFileSystemWatcher();
var metadataHelper = new MetadataHelper(loader);
config = config
.WithProvider(MefValueProvider.From(serviceProvider))
.WithProvider(MefValueProvider.From<IFileSystemWatcher>(fileSystemWatcher))
.WithProvider(MefValueProvider.From(memoryCache))
.WithProvider(MefValueProvider.From(loggerFactory))
.WithProvider(MefValueProvider.From(env))
.WithProvider(MefValueProvider.From(writer))
.WithProvider(MefValueProvider.From(options))
.WithProvider(MefValueProvider.From(options.FormattingOptions))
.WithProvider(MefValueProvider.From(loader))
.WithProvider(MefValueProvider.From(metadataHelper));
if (env.TransportType == TransportType.Stdio)
{
config = config
.WithProvider(MefValueProvider.From<IEventEmitter>(new StdioEventEmitter(writer)));
}
else
{
config = config
.WithProvider(MefValueProvider.From(NullEventEmitter.Instance));
}
return config.CreateContainer();
}
public static void InitializeWorkspace(OmniSharpWorkspace workspace, CompositionHost compositionHost, IConfiguration configuration, ILogger logger, OmniSharpOptions options)
{
var projectEventForwarder = compositionHost.GetExport<ProjectEventForwarder>();
projectEventForwarder.Initialize();
// Initialize all the project systems
foreach (var projectSystem in compositionHost.GetExports<IProjectSystem>())
{
try
{
projectSystem.Initalize(configuration.GetSection(projectSystem.Key));
}
catch (Exception e)
{
var message = $"The project system '{projectSystem.GetType().FullName}' threw exception during initialization.";
// if a project system throws an unhandled exception it should not crash the entire server
logger.LogError(e, message);
}
}
ProvideWorkspaceOptions(workspace, compositionHost, logger, options);
// Mark the workspace as initialized
workspace.Initialized = true;
}
private static void ProvideWorkspaceOptions(OmniSharpWorkspace workspace, CompositionHost compositionHost, ILogger logger, OmniSharpOptions options)
{
// run all workspace options providers
foreach (var workspaceOptionsProvider in compositionHost.GetExports<IWorkspaceOptionsProvider>())
{
var providerName = workspaceOptionsProvider.GetType().FullName;
try
{
logger.LogInformation($"Invoking Workspace Options Provider: {providerName}");
workspace.Options = workspaceOptionsProvider.Process(workspace.Options, options.FormattingOptions);
}
catch (Exception e)
{
var message = $"The workspace options provider '{providerName}' threw exception during initialization.";
logger.LogError(e, message);
}
}
}
public void Configure(
IApplicationBuilder app,
IServiceProvider serviceProvider,
ILoggerFactory loggerFactory,
ISharedTextWriter writer,
IAssemblyLoader loader,
IOptionsMonitor<OmniSharpOptions> options)
{
if (_env.TransportType == TransportType.Stdio)
{
loggerFactory.AddStdio(writer, (category, level) => LogFilter(category, level, _env));
}
else
{
loggerFactory.AddConsole((category, level) => LogFilter(category, level, _env));
}
var logger = loggerFactory.CreateLogger<Startup>();
var assemblies = DiscoverOmniSharpAssemblies(loader, logger);
PluginHost = CreateCompositionHost(serviceProvider, options.CurrentValue, assemblies);
Workspace = PluginHost.GetExport<OmniSharpWorkspace>();
app.UseRequestLogging();
app.UseExceptionHandler("/error");
app.UseMiddleware<EndpointMiddleware>();
app.UseMiddleware<StatusMiddleware>();
app.UseMiddleware<StopServerMiddleware>();
if (_env.TransportType == TransportType.Stdio)
{
logger.LogInformation($"Omnisharp server running using {nameof(TransportType.Stdio)} at location '{_env.TargetDirectory}' on host {_env.HostProcessId}.");
}
else
{
logger.LogInformation($"Omnisharp server running on port '{_env.Port}' at location '{_env.TargetDirectory}' on host {_env.HostProcessId}.");
}
InitializeWorkspace(Workspace, PluginHost, Configuration, logger, options.CurrentValue);
// when configuration options change
// run workspace options providers automatically
options.OnChange(o =>
{
ProvideWorkspaceOptions(Workspace, PluginHost, logger, o);
});
logger.LogInformation("Configuration finished.");
}
private static List<Assembly> DiscoverOmniSharpAssemblies(IAssemblyLoader loader, ILogger logger)
{
// Iterate through all runtime libraries in the dependency context and
// load them if they depend on OmniSharp.
var assemblies = new List<Assembly>();
var dependencyContext = DependencyContext.Default;
foreach (var runtimeLibrary in dependencyContext.RuntimeLibraries)
{
if (DependsOnOmniSharp(runtimeLibrary))
{
foreach (var name in runtimeLibrary.GetDefaultAssemblyNames(dependencyContext))
{
var assembly = loader.Load(name);
if (assembly != null)
{
assemblies.Add(assembly);
logger.LogDebug($"Loaded {assembly.FullName}");
}
}
}
}
return assemblies;
}
private static bool DependsOnOmniSharp(RuntimeLibrary runtimeLibrary)
{
foreach (var dependency in runtimeLibrary.Dependencies)
{
if (dependency.Name == "OmniSharp.Abstractions" ||
dependency.Name == "OmniSharp.Roslyn")
{
return true;
}
}
return false;
}
private static bool LogFilter(string category, LogLevel level, IOmniSharpEnvironment environment)
{
if (environment.LogLevel > level)
{
return false;
}
if (string.Equals(category, typeof(ExceptionHandlerMiddleware).FullName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (!category.StartsWith("OmniSharp", StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (string.Equals(category, typeof(WorkspaceInformationService).FullName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (string.Equals(category, typeof(ProjectEventForwarder).FullName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return true;
}
}
}