This repository was archived by the owner on Jul 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 243
/
Copy pathProgram.cs
309 lines (272 loc) · 12.3 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using CommandLine;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.DotNet.CodeFormatting;
using Microsoft.DotNet.CodeFormatter.Analyzers;
using Microsoft.CodeAnalysis.Options;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics;
namespace CodeFormatter
{
internal static class Program
{
private const int FAILED = 1;
private const int SUCCEEDED = 0;
private static int Main(string[] args)
{
return Parser.Default.ParseArguments<
ListOptions,
ExportOptions,
FormatOptions,
AnalyzeOptions>(args)
.MapResult(
(ListOptions listOptions) => RunListCommand(listOptions),
(ExportOptions exportOptions) => RunExportOptionsCommand(exportOptions),
(FormatOptions formatOptions) => RunFormatCommand(formatOptions),
(AnalyzeOptions analyzeOptions) => RunAnalyzeCommand(analyzeOptions),
errs => FAILED);
}
private static int RunExportOptionsCommand(ExportOptions exportOptions)
{
int result = FAILED;
PropertyBag allOptions = OptionsHelper.BuildDefaultPropertyBag();
allOptions.SaveTo(exportOptions.OutputPath, id: "codeformatter-options");
Console.WriteLine("Options file saved to: " + Path.GetFullPath(exportOptions.OutputPath));
result = SUCCEEDED;
return result;
}
private static int RunListCommand(ListOptions options)
{
// If user did not explicitly reference either analyzers or
// rules in list command, we will dump both sets.
if (!options.Analyzers && !options.Rules)
{
options.Analyzers = true;
options.Rules = true;
}
ListRulesAndAnalyzers(options.Analyzers, options.Rules);
return SUCCEEDED;
}
private static void ListRulesAndAnalyzers(bool listAnalyzers, bool listRules)
{
Console.WriteLine("{0,-20} {1}", "Name", "Title");
Console.WriteLine("==============================================");
if (listAnalyzers)
{
ImmutableArray<DiagnosticDescriptor> diagnosticDescriptors = FormattingEngine.GetSupportedDiagnostics(OptionsHelper.DefaultCompositionAssemblies);
foreach (var diagnosticDescriptor in diagnosticDescriptors)
{
Console.WriteLine("{0,-20} :{1}", diagnosticDescriptor.Id, diagnosticDescriptor.Title);
}
}
if (listRules)
{
var rules = FormattingEngine.GetFormattingRules();
foreach (var rule in rules)
{
Console.WriteLine("{0,-20} :{1}", rule.Name, rule.Description);
}
}
}
private static int RunAnalyzeCommand(AnalyzeOptions options)
{
return RunCommand(options, false);
}
private static int RunFormatCommand(FormatOptions options)
{
return RunCommand(options, true);
}
private static int RunCommand(CommandLineOptions options, bool applyCodeFixes) {
var cts = new CancellationTokenSource();
var ct = cts.Token;
Console.CancelKeyPress += delegate { cts.Cancel(); };
var stopwatch = new Stopwatch();
stopwatch.Start();
try
{
RunAsync(options, ct).Wait(ct);
Console.WriteLine("Completed formatting.");
return SUCCEEDED;
}
catch (AggregateException ex)
{
var typeLoadException = ex.InnerExceptions.FirstOrDefault() as ReflectionTypeLoadException;
if (typeLoadException == null)
throw;
Console.WriteLine("ERROR: Type loading error detected. In order to run this tool you need either Visual Studio 2015 or Microsoft Build Tools 2015 tools installed.");
var messages = typeLoadException.LoaderExceptions.Select(e => e.Message).Distinct();
foreach (var message in messages)
Console.WriteLine("- {0}", message);
return FAILED;
}
finally
{
stopwatch.Stop();
Console.WriteLine("Total time: {0}", stopwatch.Elapsed);
}
}
private static ImmutableArray<DiagnosticAnalyzer> LoadAnalyzersFromAssembly(string path, string language, bool throwIfNoAnalyzersFound)
{
var analyzerRef = new AnalyzerFileReference(path, new BasicAnalyzerAssemblyLoader());
var newAnalyzers = analyzerRef.GetAnalyzers(language);
if (newAnalyzers.Count() == 0 && throwIfNoAnalyzersFound)
{
throw new Exception(String.Format("Specified analyzer assembly {0} contained no analyzers", analyzerRef.GetAssembly().FullName));
}
return newAnalyzers;
}
// Expects a list of paths to files or directories of DLLs containing analyzers and adds them to the engine
internal static ImmutableArray<DiagnosticAnalyzer> AddCustomAnalyzers(IFormattingEngine engine, ImmutableArray<string> analyzerList, string language)
{
foreach (var analyzerPath in analyzerList)
{
if (File.Exists(analyzerPath))
{
var newAnalyzers = LoadAnalyzersFromAssembly(analyzerPath, language, true);
engine.AddAnalyzers(newAnalyzers);
return newAnalyzers;
}
else if (Directory.Exists(analyzerPath))
{
var DLLs = Directory.GetFiles(analyzerPath, "*.dll");
var allAnalyzers = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>();
foreach (var dll in DLLs)
{
// allows specifying a folder that contains analyzers as well as non-analyzer DLLs without throwing
var newAnalyzers = LoadAnalyzersFromAssembly(dll, language, false);
if (newAnalyzers.Count() > 0)
{
engine.AddAnalyzers(newAnalyzers);
allAnalyzers.AddRange(newAnalyzers);
}
}
return allAnalyzers.ToImmutable();
}
}
return ImmutableArray<DiagnosticAnalyzer>.Empty;
}
private static async Task<int> RunAsync(CommandLineOptions options, CancellationToken cancellationToken)
{
var assemblies = OptionsHelper.DefaultCompositionAssemblies;
var engine = FormattingEngine.Create(assemblies);
var configBuilder = ImmutableArray.CreateBuilder<string[]>();
configBuilder.Add(options.PreprocessorConfigurations.ToArray());
engine.PreprocessorConfigurations = configBuilder.ToImmutableArray();
engine.FormattingOptionsFilePath = options.OptionsFilePath;
engine.Verbose = options.Verbose;
engine.AllowTables = options.DefineDotNetFormatter;
engine.FileNames = options.FileFilters.ToImmutableArray();
engine.CopyrightHeader = options.CopyrightHeaderText;
engine.ApplyFixes = options.ApplyFixes;
engine.LogOutputPath = options.LogOutputPath;
if (options.TargetAnalyzers != null && options.TargetAnalyzerText != null && options.TargetAnalyzerText.Count() > 0)
{
AddCustomAnalyzers(engine, options.TargetAnalyzerText, options.Language);
}
// Analyzers will hydrate rule enabled/disabled settings
// directly from the options referenced by file path
// in options.OptionsFilePath
if (!options.UseAnalyzers)
{
if (!SetRuleMap(engine, options.RuleMap))
{
return FAILED;
}
}
foreach (var item in options.Targets)
{
// target was a text file with a list of project files to run against
if (StringComparer.OrdinalIgnoreCase.Equals(Path.GetExtension(item), ".txt"))
{
var targets = File.ReadAllLines(item);
foreach (var target in targets)
{
try
{
await RunItemAsync(engine, target, options.Language, options.UseAnalyzers, cancellationToken);
}
catch (Exception e)
{
Console.WriteLine("Exception: {0} with project {1}", e.Message, target);
}
}
}
else
{
await RunItemAsync(engine, item, options.Language, options.UseAnalyzers, cancellationToken);
}
}
return SUCCEEDED;
}
private static async Task RunItemAsync(
IFormattingEngine engine,
string item,
string language,
bool useAnalyzers,
CancellationToken cancellationToken)
{
Console.WriteLine(Path.GetFileName(item));
string extension = Path.GetExtension(item);
try
{
if (StringComparer.OrdinalIgnoreCase.Equals(extension, ".rsp"))
{
using (var workspace = ResponseFileWorkspace.Create())
{
Project project = workspace.OpenCommandLineProject(item, language);
await engine.FormatProjectAsync(project, useAnalyzers, cancellationToken);
}
}
else if (StringComparer.OrdinalIgnoreCase.Equals(extension, ".sln"))
{
using (var workspace = MSBuildWorkspace.Create())
{
workspace.LoadMetadataForReferencedProjects = true;
var solution = await workspace.OpenSolutionAsync(item, cancellationToken);
await engine.FormatSolutionAsync(solution, useAnalyzers, cancellationToken);
}
}
else
{
using (var workspace = MSBuildWorkspace.Create())
{
workspace.LoadMetadataForReferencedProjects = true;
var project = await workspace.OpenProjectAsync(item, cancellationToken);
await engine.FormatProjectAsync(project, useAnalyzers, cancellationToken);
}
}
}
catch (Microsoft.Build.Exceptions.InvalidProjectFileException)
{
// Can occur if for example a Mono based project with unknown targets files is supplied
Console.WriteLine("Invalid project file in target {0}", item);
}
}
private static bool SetRuleMap(IFormattingEngine engine, ImmutableDictionary<string, bool> ruleMap)
{
var comparer = StringComparer.OrdinalIgnoreCase;
foreach (var entry in ruleMap)
{
var rule = engine.AllRules.Where(x => comparer.Equals(x.Name, entry.Key)).FirstOrDefault();
if (rule == null)
{
Console.WriteLine("Could not find rule with name {0}", entry.Key);
return false;
}
engine.ToggleRuleEnabled(rule, entry.Value);
}
Debug.Assert(ruleMap.Count == engine.AllRules.Count());
return true;
}
}
}