forked from dotnet/format
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
269 lines (231 loc) · 9.97 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
// 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.CommandLine;
using System.CommandLine.Invocation;
using System.CommandLine.Parsing;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Tools.Logging;
using Microsoft.CodeAnalysis.Tools.MSBuild;
using Microsoft.CodeAnalysis.Tools.Utilities;
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 ParseResult? s_parseResult;
private static async Task<int> Main(string[] args)
{
var rootCommand = FormatCommand.CreateCommandLineOptions();
rootCommand.Handler = CommandHandler.Create(typeof(Program).GetMethod(nameof(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 folder,
string? fixStyle,
string? fixAnalyzers,
string? verbosity,
bool check,
string[] include,
string[] exclude,
string? report,
bool includeGenerated,
IConsole console = null!)
{
if (s_parseResult == null)
{
return 1;
}
// Setup logging.
var logLevel = GetLogLevel(verbosity);
var logger = SetupLogging(console, logLevel);
// 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;
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}'");
}
}
// 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 fileMatcher = SourceFileMatcher.CreateMatcher(include, exclude);
var formatOptions = new FormatOptions(
workspacePath,
workspaceType,
logLevel,
fixCodeStyle: s_parseResult.WasOptionUsed("--fix-style", "-fs"),
codeStyleSeverity: GetSeverity(fixStyle ?? FixSeverity.Error),
fixAnalyzers: s_parseResult.WasOptionUsed("--fix-analyzers", "-fa"),
analyerSeverity: GetSeverity(fixAnalyzers ?? FixSeverity.Error),
saveFormattedFiles: !check,
changesAreErrors: check,
fileMatcher,
reportPath: report,
includeGenerated);
var formatResult = await CodeFormatter.FormatWorkspaceAsync(
formatOptions,
logger,
cancellationTokenSource.Token,
createBinaryLog: logLevel == LogLevel.Trace).ConfigureAwait(false);
return GetExitCode(formatResult, check);
}
catch (FileNotFoundException fex)
{
logger.LogError(fex.Message);
return UnhandledExceptionExitCode;
}
catch (OperationCanceledException)
{
return UnhandledExceptionExitCode;
}
finally
{
if (!string.IsNullOrEmpty(currentDirectory))
{
Environment.CurrentDirectory = currentDirectory;
}
}
}
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
{
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 logLevel)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(new LoggerFactory().AddSimpleConsole(console, logLevel));
serviceCollection.AddLogging();
var serviceProvider = serviceCollection.BuildServiceProvider();
var logger = serviceProvider.GetService<ILogger<Program>>();
return logger;
}
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.QueryVisualStudioInstances().First();
// Since we do not inherit msbuild.deps.json when referencing the SDK copy
// of MSBuild and because the SDK no longer ships with version matched assemblies, we
// register an assembly loader that will load assemblies from the msbuild path with
// equal or higher version numbers than requested.
LooseVersionAssemblyLoader.Register(msBuildInstance.MSBuildPath);
Build.Locator.MSBuildLocator.RegisterInstance(msBuildInstance);
msBuildPath = msBuildInstance.MSBuildPath;
return true;
}
catch
{
msBuildPath = null;
return false;
}
}
}
}