forked from OmniSharp/omnisharp-roslyn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProjectSystem.cs
269 lines (234 loc) · 12 KB
/
ProjectSystem.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
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using OmniSharp.Eventing;
using OmniSharp.FileSystem;
using OmniSharp.FileWatching;
using OmniSharp.Mef;
using OmniSharp.Models.WorkspaceInformation;
using OmniSharp.MSBuild.Discovery;
using OmniSharp.MSBuild.Models;
using OmniSharp.MSBuild.Notification;
using OmniSharp.MSBuild.ProjectFile;
using OmniSharp.MSBuild.SolutionParsing;
using OmniSharp.Options;
using OmniSharp.Roslyn.CSharp.Services.Diagnostics;
using OmniSharp.Roslyn.CSharp.Services.Refactoring.V2;
using OmniSharp.Services;
using System.Linq;
namespace OmniSharp.MSBuild
{
[ExportProjectSystem(ProjectSystemNames.MSBuildProjectSystem), Shared]
internal class ProjectSystem : IProjectSystem
{
private readonly IOmniSharpEnvironment _environment;
private readonly OmniSharpWorkspace _workspace;
private readonly ImmutableDictionary<string, string> _propertyOverrides;
private readonly IDotNetCliService _dotNetCli;
private readonly SdksPathResolver _sdksPathResolver;
private readonly MetadataFileReferenceCache _metadataFileReferenceCache;
private readonly IEventEmitter _eventEmitter;
private readonly IFileSystemWatcher _fileSystemWatcher;
private readonly FileSystemHelper _fileSystemHelper;
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger _logger;
private readonly IAnalyzerAssemblyLoader _assemblyLoader;
private readonly DotNetInfo _dotNetInfo;
private readonly ImmutableArray<IMSBuildEventSink> _eventSinks;
private PackageDependencyChecker _packageDependencyChecker;
private ProjectManager _manager;
private ProjectLoader _loader;
private MSBuildOptions _options;
private string _solutionFileOrRootPath;
public string Key { get; } = "MsBuild";
public string Language { get; } = LanguageNames.CSharp;
public IEnumerable<string> Extensions { get; } = new[] { ".cs" };
public bool EnabledByDefault { get; } = true;
public bool Initialized { get; private set; }
[ImportingConstructor]
public ProjectSystem(
IOmniSharpEnvironment environment,
OmniSharpWorkspace workspace,
IMSBuildLocator msbuildLocator,
IDotNetCliService dotNetCliService,
SdksPathResolver sdksPathResolver,
MetadataFileReferenceCache metadataFileReferenceCache,
IEventEmitter eventEmitter,
IFileSystemWatcher fileSystemWatcher,
FileSystemHelper fileSystemHelper,
ILoggerFactory loggerFactory,
CachingCodeFixProviderForProjects codeFixesForProjects,
IAnalyzerAssemblyLoader assemblyLoader,
[ImportMany] IEnumerable<IMSBuildEventSink> eventSinks,
DotNetInfo dotNetInfo)
{
_environment = environment;
_workspace = workspace;
_propertyOverrides = msbuildLocator.RegisteredInstance.PropertyOverrides;
_dotNetCli = dotNetCliService;
_sdksPathResolver = sdksPathResolver;
_metadataFileReferenceCache = metadataFileReferenceCache;
_eventEmitter = eventEmitter;
_fileSystemWatcher = fileSystemWatcher;
_fileSystemHelper = fileSystemHelper;
_loggerFactory = loggerFactory;
_eventSinks = eventSinks.ToImmutableArray();
_logger = loggerFactory.CreateLogger<ProjectSystem>();
_assemblyLoader = assemblyLoader;
_dotNetInfo = dotNetInfo;
}
public void Initalize(IConfiguration configuration)
{
if (Initialized) return;
_options = new MSBuildOptions();
ConfigurationBinder.Bind(configuration, _options);
_sdksPathResolver.Enabled = _options.UseLegacySdkResolver;
_sdksPathResolver.OverridePath = _options.MSBuildSDKsPath;
if (_environment.LogLevel < LogLevel.Information)
{
var buildEnvironmentInfo = MSBuildHelpers.GetBuildEnvironmentInfo();
_logger.LogDebug($"MSBuild environment: {Environment.NewLine}{buildEnvironmentInfo}");
}
_packageDependencyChecker = new PackageDependencyChecker(_loggerFactory, _eventEmitter, _dotNetCli, _options);
_loader = new ProjectLoader(_options, _environment.TargetDirectory, _propertyOverrides, _loggerFactory, _sdksPathResolver);
_manager = new ProjectManager(_loggerFactory, _options, _eventEmitter, _fileSystemWatcher, _metadataFileReferenceCache, _packageDependencyChecker, _loader, _workspace, _assemblyLoader, _eventSinks, _dotNetInfo);
Initialized = true;
if (_options.LoadProjectsOnDemand)
{
_logger.LogInformation($"Skip loading projects listed in solution file or under target directory because {Key}:{nameof(MSBuildOptions.LoadProjectsOnDemand)} is true.");
return;
}
var initialProjectPathsAndIds = GetInitialProjectPathsAndIds();
foreach (var (projectFilePath, projectIdInfo) in initialProjectPathsAndIds)
{
if (!File.Exists(projectFilePath))
{
_logger.LogWarning($"Found project that doesn't exist on disk: {projectFilePath}");
continue;
}
_manager.QueueProjectUpdate(projectFilePath, allowAutoRestore: true, projectIdInfo);
}
}
private IEnumerable<(string, ProjectIdInfo)> GetInitialProjectPathsAndIds()
{
// If a solution was provided, use it.
if (!string.IsNullOrEmpty(_environment.SolutionFilePath))
{
_solutionFileOrRootPath = _environment.SolutionFilePath;
return GetProjectPathsAndIdsFromSolution(_environment.SolutionFilePath);
}
// Otherwise, assume that the path provided is a directory and look for a solution there.
var solutionFilePath = FindSolutionFilePath(_environment.TargetDirectory, _logger);
if (!string.IsNullOrEmpty(solutionFilePath))
{
_solutionFileOrRootPath = solutionFilePath;
return GetProjectPathsAndIdsFromSolution(solutionFilePath);
}
// Finally, if there isn't a single solution immediately available,
// Just process all of the projects beneath the root path.
_solutionFileOrRootPath = _environment.TargetDirectory;
return _fileSystemHelper.GetFiles("**/*.csproj")
.Select(filepath =>
{
var projectIdInfo = new ProjectIdInfo(ProjectId.CreateNewId(debugName: filepath), isDefinedInSolution: false);
return (filepath, projectIdInfo);
});
}
private IEnumerable<(string, ProjectIdInfo)> GetProjectPathsAndIdsFromSolution(string solutionFilePath)
{
_logger.LogInformation($"Detecting projects in '{solutionFilePath}'.");
var solutionFile = SolutionFile.ParseFile(solutionFilePath);
var processedProjects = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var result = new List<(string, ProjectIdInfo)>();
var solutionConfigurations = new Dictionary<ProjectId, Dictionary<string, string>>();
foreach (var globalSection in solutionFile.GlobalSections)
{
// Try parse project configurations if they are remapped in solution file
if (globalSection.Name == "ProjectConfigurationPlatforms")
{
_logger.LogDebug($"Parsing ProjectConfigurationPlatforms of '{solutionFilePath}'.");
foreach (var entry in globalSection.Properties)
{
var guid = Guid.Parse(entry.Name.Substring(0, 38));
var projId = ProjectId.CreateFromSerialized(guid);
var solutionConfig = entry.Name.Substring(39);
if (!solutionConfigurations.TryGetValue(projId, out var dict))
{
dict = new Dictionary<string, string>();
solutionConfigurations.Add(projId, dict);
}
dict.Add(solutionConfig, entry.Value);
}
}
}
foreach (var project in solutionFile.Projects)
{
if (project.IsNotSupported)
{
continue;
}
// Solution files are assumed to contain relative paths to project files with Windows-style slashes.
var projectFilePath = project.RelativePath.Replace('\\', Path.DirectorySeparatorChar);
projectFilePath = Path.Combine(_environment.TargetDirectory, projectFilePath);
projectFilePath = Path.GetFullPath(projectFilePath);
// Have we seen this project? If so, move on.
if (processedProjects.Contains(projectFilePath))
{
continue;
}
if (string.Equals(Path.GetExtension(projectFilePath), ".csproj", StringComparison.OrdinalIgnoreCase))
{
var projectIdInfo = new ProjectIdInfo(ProjectId.CreateFromSerialized(new Guid(project.ProjectGuid)), true);
if (solutionConfigurations.TryGetValue(projectIdInfo.Id, out var configurations))
{
projectIdInfo.SolutionConfiguration = configurations;
}
result.Add((projectFilePath, projectIdInfo));
}
processedProjects.Add(projectFilePath);
}
return result;
}
private static string FindSolutionFilePath(string rootPath, ILogger logger)
{
// currently, Directory.GetFiles on Windows collects files that the file extension has 'sln' prefix, while
// GetFiles on Mono looks for an exact match. Use an approach that works for both.
// see https://docs.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles?view=netframework-4.7.2 ('Note' description)
var solutionsFilePaths = Directory.GetFiles(rootPath, "*.sln").Where(x => Path.GetExtension(x).Equals(".sln", StringComparison.OrdinalIgnoreCase)).ToArray();
var solutionFiltersFilePaths = Directory.GetFiles(rootPath, "*.slnf").Where(x => Path.GetExtension(x).Equals(".slnf", StringComparison.OrdinalIgnoreCase)).ToArray();
var result = SolutionSelector.Pick(solutionsFilePaths.Concat(solutionFiltersFilePaths).ToArray(), rootPath);
if (result.Message != null)
{
logger.LogInformation(result.Message);
}
return result.FilePath;
}
async Task<object> IProjectSystem.GetWorkspaceModelAsync(WorkspaceInformationRequest request)
{
await _manager.WaitForQueueEmptyAsync();
return new MSBuildWorkspaceInfo(
_solutionFileOrRootPath, _manager.GetAllProjects(),
excludeSourceFiles: request?.ExcludeSourceFiles ?? false);
}
async Task<object> IProjectSystem.GetProjectModelAsync(string filePath)
{
await _manager.WaitForQueueEmptyAsync();
var document = _workspace.GetDocument(filePath);
var projectFilePath = document != null
? document.Project.FilePath
: filePath;
if (!_manager.TryGetProject(projectFilePath, out var projectFileInfo))
{
_logger.LogDebug($"Could not locate project for '{projectFilePath}'");
return Task.FromResult<object>(null);
}
return new MSBuildProjectInfo(projectFileInfo);
}
}
}