-
-
Notifications
You must be signed in to change notification settings - Fork 95
/
ProjectAnalyzer.cs
397 lines (342 loc) · 19.1 KB
/
ProjectAnalyzer.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Buildalyzer.Construction;
using Buildalyzer.Environment;
using Buildalyzer.Logger;
using Buildalyzer.Logging;
using Microsoft.Build.Construction;
using Microsoft.Build.Logging;
using Microsoft.Extensions.Logging;
using MsBuildPipeLogger;
using ILogger = Microsoft.Build.Framework.ILogger;
namespace Buildalyzer
{
public class ProjectAnalyzer : IProjectAnalyzer
{
private readonly List<ILogger> _buildLoggers = new List<ILogger>();
// Project-specific global properties and environment variables
private readonly ConcurrentDictionary<string, string> _globalProperties = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<string, string> _environmentVariables = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
public AnalyzerManager Manager { get; }
public IProjectFile ProjectFile { get; }
public EnvironmentFactory EnvironmentFactory { get; }
public string SolutionDirectory { get; }
public ProjectInSolution ProjectInSolution { get; }
/// <summary>
/// Gets a GUID for the project. This checks for a GUID from the
/// solution (if originally provided). If this isn't available, it
/// will generate a UUID GUID by hashing the project path relative to the solution path (so it's repeatable).
/// </summary>
public Guid ProjectGuid { get; }
/// <summary>
/// The global properties for MSBuild to be used for every build from this analyzer.
/// </summary>
/// <remarks>
/// Additional global properties may be added or changed by individual build environment.
/// </remarks>
public IReadOnlyDictionary<string, string> GlobalProperties => GetEffectiveGlobalProperties(null);
/// <summary>
/// The environment variables for MSBuild to be used for every build from this analyzer.
/// </summary>
/// <remarks>
/// Additional environment variables may be added or changed by individual build environment.
/// </remarks>
public IReadOnlyDictionary<string, string> EnvironmentVariables => GetEffectiveEnvironmentVariables(null);
public IEnumerable<ILogger> BuildLoggers => _buildLoggers;
public ILogger<ProjectAnalyzer> Logger { get; set; }
/// <summary>
/// Controls whether empty, invalid, and missing targets should be ignored during project load.
/// </summary>
public bool IgnoreFaultyImports { get; set; } = true;
// The project file path should already be normalized
internal ProjectAnalyzer(AnalyzerManager manager, string projectFilePath, ProjectInSolution projectInSolution)
{
Manager = manager;
Logger = Manager.LoggerFactory?.CreateLogger<ProjectAnalyzer>();
ProjectFile = new ProjectFile(projectFilePath);
EnvironmentFactory = new EnvironmentFactory(Manager, ProjectFile);
ProjectInSolution = projectInSolution;
SolutionDirectory = string.IsNullOrEmpty(manager.SolutionFilePath)
? Path.GetDirectoryName(projectFilePath) : Path.GetDirectoryName(manager.SolutionFilePath);
// Get (or create) a project GUID
ProjectGuid = projectInSolution == null
? GuidUtility.Create(GuidUtility.UrlNamespace, ProjectFile.Path.Substring(SolutionDirectory.Length))
: Guid.Parse(projectInSolution.ProjectGuid);
// Set the solution directory global property
SetGlobalProperty(MsBuildProperties.SolutionDir, SolutionDirectory);
}
/// <summary>
/// Builds the requested target framework(s).
/// </summary>
/// <param name="targetFrameworks">The set of target frameworks to build.</param>
/// <returns>A dictionary of target frameworks to <see cref="AnalyzerResult"/>.</returns>
public IAnalyzerResults Build(string[] targetFrameworks) =>
Build(targetFrameworks, new EnvironmentOptions());
/// <summary>
/// Builds the requested target framework(s).
/// </summary>
/// <param name="targetFrameworks">The set of target frameworks to build.</param>
/// <param name="environmentOptions">The environment options to use for the build.</param>
/// <returns>A dictionary of target frameworks to <see cref="AnalyzerResult"/>.</returns>
public IAnalyzerResults Build(string[] targetFrameworks, EnvironmentOptions environmentOptions)
{
if (environmentOptions == null)
{
throw new ArgumentNullException(nameof(environmentOptions));
}
// If the set of target frameworks is empty, just build the default
if (targetFrameworks == null || targetFrameworks.Length == 0)
{
targetFrameworks = new string[] { null };
}
// Create a new build environment for each target
AnalyzerResults results = new AnalyzerResults();
foreach (string targetFramework in targetFrameworks)
{
BuildEnvironment buildEnvironment = EnvironmentFactory.GetBuildEnvironment(targetFramework, environmentOptions);
BuildTargets(buildEnvironment, targetFramework, buildEnvironment.TargetsToBuild, results);
}
return results;
}
/// <summary>
/// Builds the requested target framework(s).
/// </summary>
/// <param name="targetFrameworks">The set of target frameworks to build.</param>
/// <param name="buildEnvironment">The build environment to use for the build.</param>
/// <returns>A dictionary of target frameworks to <see cref="AnalyzerResult"/>.</returns>
public IAnalyzerResults Build(string[] targetFrameworks, BuildEnvironment buildEnvironment)
{
if (buildEnvironment == null)
{
throw new ArgumentNullException(nameof(buildEnvironment));
}
// If the set of target frameworks is empty, just build the default
if (targetFrameworks == null || targetFrameworks.Length == 0)
{
targetFrameworks = new string[] { null };
}
AnalyzerResults results = new AnalyzerResults();
foreach (string targetFramework in targetFrameworks)
{
BuildTargets(buildEnvironment, targetFramework, buildEnvironment.TargetsToBuild, results);
}
return results;
}
/// <summary>
/// Builds a specific target framework.
/// </summary>
/// <param name="targetFramework">The target framework to build.</param>
/// <returns>The result of the build process.</returns>
public IAnalyzerResults Build(string targetFramework) =>
Build(targetFramework, EnvironmentFactory.GetBuildEnvironment(targetFramework));
/// <summary>
/// Builds a specific target framework.
/// </summary>
/// <param name="targetFramework">The target framework to build.</param>
/// <param name="environmentOptions">The environment options to use for the build.</param>
/// <returns>The result of the build process.</returns>
public IAnalyzerResults Build(string targetFramework, EnvironmentOptions environmentOptions) =>
Build(
targetFramework,
EnvironmentFactory.GetBuildEnvironment(
targetFramework,
environmentOptions ?? throw new ArgumentNullException(nameof(environmentOptions))));
/// <summary>
/// Builds a specific target framework.
/// </summary>
/// <param name="targetFramework">The target framework to build.</param>
/// <param name="buildEnvironment">The build environment to use for the build.</param>
/// <returns>The result of the build process.</returns>
public IAnalyzerResults Build(string targetFramework, BuildEnvironment buildEnvironment) =>
BuildTargets(
buildEnvironment ?? throw new ArgumentNullException(nameof(buildEnvironment)),
targetFramework,
buildEnvironment.TargetsToBuild,
new AnalyzerResults());
/// <summary>
/// Builds the project without specifying a target framework. In a multi-targeted project this will return a <see cref="AnalyzerResult"/> for each target framework.
/// </summary>
/// <returns>The result of the build process.</returns>
public IAnalyzerResults Build() => Build((string)null);
/// <summary>
/// Builds the project without specifying a target framework. In a multi-targeted project this will return a <see cref="AnalyzerResult"/> for each target framework.
/// </summary>
/// <param name="environmentOptions">The environment options to use for the build.</param>
/// <returns>The result of the build process.</returns>
public IAnalyzerResults Build(EnvironmentOptions environmentOptions) => Build((string)null, environmentOptions);
/// <summary>
/// Builds the project without specifying a target framework. In a multi-targeted project this will return a <see cref="AnalyzerResult"/> for each target framework.
/// </summary>
/// <param name="buildEnvironment">The build environment to use for the build.</param>
/// <returns>The result of the build process.</returns>
public IAnalyzerResults Build(BuildEnvironment buildEnvironment) => Build((string)null, buildEnvironment);
// This is where the magic happens - returns one result per result target framework
private IAnalyzerResults BuildTargets(BuildEnvironment buildEnvironment, string targetFramework, string[] targetsToBuild, AnalyzerResults results)
{
using (CancellationTokenSource cancellation = new CancellationTokenSource())
{
using (AnonymousPipeLoggerServer pipeLogger = new AnonymousPipeLoggerServer(cancellation.Token))
{
using (EventProcessor eventProcessor = new EventProcessor(Manager, this, BuildLoggers, pipeLogger, results != null))
{
// Run MSBuild
int exitCode;
string fileName = GetCommand(buildEnvironment, targetFramework, targetsToBuild, pipeLogger.GetClientHandle(), out string arguments);
using (ProcessRunner processRunner = new ProcessRunner(fileName, arguments, Path.GetDirectoryName(ProjectFile.Path), GetEffectiveEnvironmentVariables(buildEnvironment), Manager.LoggerFactory))
{
processRunner.Exited = () => cancellation.Cancel();
processRunner.Start();
pipeLogger.ReadAll();
processRunner.WaitForExit();
exitCode = processRunner.ExitCode;
}
// Collect the results
results?.Add(eventProcessor.Results, exitCode == 0 && eventProcessor.OverallSuccess);
}
}
}
return results;
}
private string GetCommand(BuildEnvironment buildEnvironment, string targetFramework, string[] targetsToBuild, string pipeLoggerClientHandle, out string arguments)
{
// Get the executable and the initial set of arguments
string fileName = buildEnvironment.MsBuildExePath;
string initialArguments = string.Empty;
if (Path.GetExtension(buildEnvironment.MsBuildExePath).Equals(".dll", StringComparison.OrdinalIgnoreCase))
{
// .NET Core MSBuild .dll needs to be run with dotnet
fileName = buildEnvironment.DotnetExePath;
initialArguments = $"\"{buildEnvironment.MsBuildExePath}\"";
}
// Environment arguments
string environmentArguments = buildEnvironment.Arguments.Any()
? string.Join(" ", buildEnvironment.Arguments)
: string.Empty;
// Get the logger arguments (/l)
string loggerPath = typeof(BuildalyzerLogger).Assembly.Location;
bool logEverything = _buildLoggers.Count > 0;
string loggerArgument = $"/l:{nameof(BuildalyzerLogger)},{FormatArgument(loggerPath)};{pipeLoggerClientHandle};{logEverything}";
// Get the properties arguments (/property)
Dictionary<string, string> effectiveGlobalProperties = GetEffectiveGlobalProperties(buildEnvironment);
if (!string.IsNullOrEmpty(targetFramework))
{
// Setting the TargetFramework MSBuild property tells MSBuild which target framework to use for the outer build
effectiveGlobalProperties[MsBuildProperties.TargetFramework] = targetFramework;
}
if (Path.GetExtension(ProjectFile.Path).Equals(".fsproj", StringComparison.OrdinalIgnoreCase)
&& effectiveGlobalProperties.ContainsKey(MsBuildProperties.SkipCompilerExecution))
{
// We can't skip the compiler for design-time builds in F# (it causes strange errors regarding file copying)
effectiveGlobalProperties.Remove(MsBuildProperties.SkipCompilerExecution);
}
string propertyArgument = effectiveGlobalProperties.Count == 0 ? string.Empty : $"/property:{string.Join(";", effectiveGlobalProperties.Select(x => $"{x.Key}={FormatArgument(x.Value)}"))}";
// Get the target argument (/target)
string targetArgument = targetsToBuild == null || targetsToBuild.Length == 0 ? string.Empty : $"/target:{string.Join(";", targetsToBuild)}";
// Get the restore argument (/restore)
string restoreArgument = buildEnvironment.Restore ? "/restore" : string.Empty;
arguments = $"{initialArguments} /noconsolelogger {environmentArguments} {restoreArgument} {targetArgument} {propertyArgument} {loggerArgument} {FormatArgument(ProjectFile.Path)}";
return fileName;
}
private static string FormatArgument(string argument)
{
// Escape inner quotes
argument = argument.Replace("\"", "\\\"");
// Also escape trailing slashes so they don't escape the closing quote
if (argument.EndsWith("\\"))
{
argument = $"{argument}\\";
}
// Surround with quotes
return $"\"{argument}\"";
}
public void SetGlobalProperty(string key, string value)
{
_globalProperties[key] = value;
}
public void RemoveGlobalProperty(string key)
{
// Nulls are removed before passing to MSBuild and can be used to ignore values in lower-precedence collections
_globalProperties[key] = null;
}
public void SetEnvironmentVariable(string key, string value)
{
_environmentVariables[key] = value;
}
// Note the order of precedence (from least to most)
private Dictionary<string, string> GetEffectiveGlobalProperties(BuildEnvironment buildEnvironment)
=> GetEffectiveDictionary(
true, // Remove nulls to avoid passing null global properties. But null can be used in higher-precident dictionaries to ignore a lower-precident dictionary's value.
buildEnvironment?.GlobalProperties,
Manager.GlobalProperties,
_globalProperties);
// Note the order of precedence (from least to most)
private Dictionary<string, string> GetEffectiveEnvironmentVariables(BuildEnvironment buildEnvironment)
=> GetEffectiveDictionary(
false, // Don't remove nulls as a null value will unset the env var which may be set by a calling process.
buildEnvironment?.EnvironmentVariables,
Manager.EnvironmentVariables,
_environmentVariables);
private static Dictionary<string, string> GetEffectiveDictionary(
bool removeNulls,
params IReadOnlyDictionary<string, string>[] innerDictionaries)
{
Dictionary<string, string> effectiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (IReadOnlyDictionary<string, string> innerDictionary in innerDictionaries.Where(x => x != null))
{
foreach (KeyValuePair<string, string> pair in innerDictionary)
{
if (removeNulls && pair.Value == null)
{
effectiveDictionary.Remove(pair.Key);
}
else
{
effectiveDictionary[pair.Key] = pair.Value;
}
}
}
return effectiveDictionary;
}
public void AddBinaryLogger(
string binaryLogFilePath = null,
BinaryLogger.ProjectImportsCollectionMode collectProjectImports = BinaryLogger.ProjectImportsCollectionMode.Embed) =>
AddBuildLogger(new BinaryLogger
{
Parameters = binaryLogFilePath ?? Path.ChangeExtension(ProjectFile.Path, "binlog"),
CollectProjectImports = collectProjectImports,
Verbosity = Microsoft.Build.Framework.LoggerVerbosity.Diagnostic
});
/// <summary>
/// Adds an MSBuild logger to the build. Note that this may have a large penalty on build performance.
/// </summary>
/// <remarks>
/// Normally, the minimum required amount of log events are forwarded from the MSBuild process to Buildalyzer.
/// By attaching arbitrary loggers, MSBuild must forward every log event so the logger has a chance to handle it.
/// </remarks>
/// <param name="logger">The logger to add.</param>
public void AddBuildLogger(ILogger logger)
{
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
_buildLoggers.Add(logger);
}
/// <summary>
/// Removes an MSBuild logger from the build.
/// </summary>
/// <param name="logger">The logger to remove.</param>
public void RemoveBuildLogger(ILogger logger)
{
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
_buildLoggers.Remove(logger);
}
}
}