/
Program.cs
383 lines (327 loc) · 13.9 KB
/
Program.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
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.CommandLine.Parsing;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Tools.Logging;
using Microsoft.CodeAnalysis.Tools.Utilities;
using Microsoft.CodeAnalysis.Tools.Workspaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.CodeAnalysis.Tools
{
internal class Program
{
internal const int UnhandledExceptionExitCode = 1;
internal const int CheckFailedExitCode = 2;
internal const int UnableToLocateMSBuildExitCode = 3;
internal const int UnableToLocateDotNetCliExitCode = 4;
private static readonly string[] s_standardInputKeywords = { "/dev/stdin", "-" };
private static ParseResult? s_parseResult;
private static async Task<int> Main(string[] args)
{
var rootCommand = FormatCommand.CreateCommandLineOptions();
rootCommand.Handler = CommandHandler.Create(new FormatCommand.Handler(Run));
// Parse the incoming args so we can give warnings when deprecated options are used.
s_parseResult = rootCommand.Parse(args);
return await rootCommand.InvokeAsync(args);
}
public static async Task<int> Run(
string? workspace,
bool noRestore,
bool folder,
bool fixWhitespace,
string fixStyle,
string fixAnalyzers,
string[] diagnostics,
string? verbosity,
bool check,
string[] include,
string[] exclude,
string? report,
bool includeGenerated,
string? binarylog,
IConsole console = null!)
{
if (s_parseResult == null)
{
return 1;
}
// Setup logging.
var logLevel = GetLogLevel(verbosity);
var logger = SetupLogging(console, minimalLogLevel: logLevel, minimalErrorLevel: LogLevel.Warning);
// Hook so we can cancel and exit when ctrl+c is pressed.
var cancellationTokenSource = new CancellationTokenSource();
Console.CancelKeyPress += (sender, e) =>
{
e.Cancel = true;
cancellationTokenSource.Cancel();
};
var currentDirectory = string.Empty;
try
{
currentDirectory = Environment.CurrentDirectory;
var formatVersion = GetVersion();
logger.LogDebug(Resources.The_dotnet_format_version_is_0, formatVersion);
string? workspaceDirectory;
string workspacePath;
WorkspaceType workspaceType;
// The folder option means we should treat the project path as a folder path.
if (folder)
{
// If folder isn't populated, then use the current directory
workspacePath = Path.GetFullPath(workspace ?? ".", Environment.CurrentDirectory);
workspaceDirectory = workspacePath;
workspaceType = WorkspaceType.Folder;
}
else
{
var (isSolution, workspaceFilePath) = MSBuildWorkspaceFinder.FindWorkspace(currentDirectory, workspace);
workspacePath = workspaceFilePath;
workspaceType = isSolution
? WorkspaceType.Solution
: WorkspaceType.Project;
// To ensure we get the version of MSBuild packaged with the dotnet SDK used by the
// workspace, use its directory as our working directory which will take into account
// a global.json if present.
workspaceDirectory = Path.GetDirectoryName(workspacePath);
if (workspaceDirectory is null)
{
throw new Exception($"Unable to find folder at '{workspacePath}'");
}
}
if (workspaceType != WorkspaceType.Folder)
{
var runtimeVersion = GetRuntimeVersion();
logger.LogDebug(Resources.The_dotnet_runtime_version_is_0, runtimeVersion);
// Load MSBuild
Environment.CurrentDirectory = workspaceDirectory;
if (!TryGetDotNetCliVersion(out var dotnetVersion))
{
logger.LogError(Resources.Unable_to_locate_dotnet_CLI_Ensure_that_it_is_on_the_PATH);
return UnableToLocateDotNetCliExitCode;
}
logger.LogTrace(Resources.The_dotnet_CLI_version_is_0, dotnetVersion);
if (!TryLoadMSBuild(out var msBuildPath))
{
logger.LogError(Resources.Unable_to_locate_MSBuild_Ensure_the_NET_SDK_was_installed_with_the_official_installer);
return UnableToLocateMSBuildExitCode;
}
logger.LogTrace(Resources.Using_msbuildexe_located_in_0, msBuildPath);
}
var fixType = FixCategory.None;
if (s_parseResult.WasOptionUsed("--fix-style", "-s"))
{
fixType |= FixCategory.CodeStyle;
}
if (s_parseResult.WasOptionUsed("--fix-analyzers", "-a"))
{
fixType |= FixCategory.Analyzers;
}
if (fixType == FixCategory.None && diagnostics.Length > 0)
{
logger.LogWarning(Resources.The_diagnostics_option_only_applies_when_fixing_style_or_running_analyzers);
}
if (fixType == FixCategory.None || fixWhitespace)
{
fixType |= FixCategory.Whitespace;
}
HandleStandardInput(logger, ref include, ref exclude);
var fileMatcher = SourceFileMatcher.CreateMatcher(include, exclude);
var formatOptions = new FormatOptions(
workspacePath,
workspaceType,
noRestore,
logLevel,
fixType,
codeStyleSeverity: GetSeverity(fixStyle),
analyzerSeverity: GetSeverity(fixAnalyzers),
diagnostics: diagnostics.ToImmutableHashSet(),
saveFormattedFiles: !check,
changesAreErrors: check,
fileMatcher,
reportPath: report,
includeGenerated);
var formatResult = await CodeFormatter.FormatWorkspaceAsync(
formatOptions,
logger,
cancellationTokenSource.Token,
binaryLogPath: GetBinaryLogPath(s_parseResult, binarylog)).ConfigureAwait(false);
return GetExitCode(formatResult, check);
static string? GetBinaryLogPath(ParseResult parseResult, string? binarylog)
{
if (parseResult.WasOptionUsed("--binarylog"))
{
if (binarylog is null)
{
return Path.Combine(Directory.GetCurrentDirectory(), "format.binlog");
}
else if (Path.GetExtension(binarylog)?.Equals(".binlog") == false)
{
return Path.ChangeExtension(binarylog, ".binlog");
}
return binarylog;
}
return null;
}
}
catch (FileNotFoundException fex)
{
logger.LogError(fex.Message);
return UnhandledExceptionExitCode;
}
catch (OperationCanceledException)
{
return UnhandledExceptionExitCode;
}
finally
{
if (!string.IsNullOrEmpty(currentDirectory))
{
Environment.CurrentDirectory = currentDirectory;
}
}
}
private static void HandleStandardInput(ILogger logger, ref string[] include, ref string[] exclude)
{
var isStandardMarkerUsed = false;
if (include.Length == 1 && s_standardInputKeywords.Contains(include[0]))
{
if (TryReadFromStandardInput(ref include))
{
isStandardMarkerUsed = true;
}
}
if (exclude.Length == 1 && s_standardInputKeywords.Contains(exclude[0]))
{
if (isStandardMarkerUsed)
{
logger.LogCritical(Resources.Standard_input_used_multiple_times);
Environment.Exit(CheckFailedExitCode);
}
TryReadFromStandardInput(ref exclude);
}
static bool TryReadFromStandardInput(ref string[] subject)
{
if (!Console.IsInputRedirected)
{
return false; // pass
}
// reset the subject array
Array.Clear(subject, 0, subject.Length);
Array.Resize(ref subject, 0);
Console.InputEncoding = Encoding.UTF8;
using var reader = new StreamReader(Console.OpenStandardInput(8192));
Console.SetIn(reader);
for (var i = 0; Console.In.Peek() != -1; ++i)
{
Array.Resize(ref subject, subject.Length + 1);
subject[i] = Console.In.ReadLine();
}
return true;
}
}
internal static int GetExitCode(WorkspaceFormatResult formatResult, bool check)
{
if (!check)
{
return formatResult.ExitCode;
}
return formatResult.FilesFormatted == 0 ? 0 : CheckFailedExitCode;
}
internal static LogLevel GetLogLevel(string? verbosity)
{
switch (verbosity)
{
case "q":
case "quiet":
return LogLevel.Error;
case "m":
case "minimal":
return LogLevel.Warning;
case "n":
case "normal":
return LogLevel.Information;
case "d":
case "detailed":
return LogLevel.Debug;
case "diag":
case "diagnostic":
return LogLevel.Trace;
default:
return LogLevel.Information;
}
}
internal static DiagnosticSeverity GetSeverity(string? severity)
{
return severity?.ToLowerInvariant() switch
{
"" => DiagnosticSeverity.Error,
FixSeverity.Error => DiagnosticSeverity.Error,
FixSeverity.Warn => DiagnosticSeverity.Warning,
FixSeverity.Info => DiagnosticSeverity.Info,
_ => throw new ArgumentOutOfRangeException(nameof(severity)),
};
}
private static ILogger<Program> SetupLogging(IConsole console, LogLevel minimalLogLevel, LogLevel minimalErrorLevel)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(new LoggerFactory().AddSimpleConsole(console, minimalLogLevel, minimalErrorLevel));
serviceCollection.AddLogging();
var serviceProvider = serviceCollection.BuildServiceProvider();
var logger = serviceProvider.GetService<ILogger<Program>>();
return logger!;
}
private static string GetVersion()
{
return Assembly.GetExecutingAssembly()
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
.InformationalVersion;
}
private static bool TryGetDotNetCliVersion([NotNullWhen(returnValue: true)] out string? dotnetVersion)
{
try
{
var processInfo = ProcessRunner.CreateProcess("dotnet", "--version", captureOutput: true, displayWindow: false);
var versionResult = processInfo.Result.GetAwaiter().GetResult();
dotnetVersion = versionResult.OutputLines[0].Trim();
return true;
}
catch
{
dotnetVersion = null;
return false;
}
}
private static bool TryLoadMSBuild([NotNullWhen(returnValue: true)] out string? msBuildPath)
{
try
{
// Since we are running as a dotnet tool we should be able to find an instance of
// MSBuild in a .NET Core SDK.
var msBuildInstance = Build.Locator.MSBuildLocator.RegisterDefaults();
msBuildPath = msBuildInstance.MSBuildPath;
return true;
}
catch
{
msBuildPath = null;
return false;
}
}
internal static string GetRuntimeVersion()
{
var pathParts = typeof(string).Assembly.Location.Split('\\', '/');
var netCoreAppIndex = Array.IndexOf(pathParts, "Microsoft.NETCore.App");
return pathParts[netCoreAppIndex + 1];
}
}
}