forked from dotnet/format
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodeFormatter.cs
372 lines (314 loc) · 16 KB
/
CodeFormatter.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
// 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.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Tools.Formatters;
using Microsoft.CodeAnalysis.Tools.Utilities;
using Microsoft.CodeAnalysis.Tools.Workspaces;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.CodingConventions;
namespace Microsoft.CodeAnalysis.Tools
{
internal static class CodeFormatter
{
private static readonly ImmutableArray<ICodeFormatter> s_codeFormatters = new ICodeFormatter[]
{
new WhitespaceFormatter(),
new FinalNewlineFormatter(),
new EndOfLineFormatter(),
new CharsetFormatter(),
}.ToImmutableArray();
public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(
FormatOptions options,
ILogger logger,
CancellationToken cancellationToken)
{
var (workspaceFilePath, workspaceType, logLevel, saveFormattedFiles, _, pathsToInclude, pathsToExclude, reportPath) = options;
var logWorkspaceWarnings = logLevel == LogLevel.Trace;
logger.LogInformation(string.Format(Resources.Formatting_code_files_in_workspace_0, workspaceFilePath));
logger.LogTrace(Resources.Loading_workspace);
var workspaceStopwatch = Stopwatch.StartNew();
using (var workspace = await OpenWorkspaceAsync(
workspaceFilePath, workspaceType, pathsToInclude, logWorkspaceWarnings, logger, cancellationToken).ConfigureAwait(false))
{
if (workspace is null)
{
return new WorkspaceFormatResult(filesFormatted: 0, fileCount: 0, exitCode: 1);
}
var loadWorkspaceMS = workspaceStopwatch.ElapsedMilliseconds;
logger.LogTrace(Resources.Complete_in_0_ms, workspaceStopwatch.ElapsedMilliseconds);
var projectPath = workspaceType == WorkspaceType.Project ? workspaceFilePath : string.Empty;
var solution = workspace.CurrentSolution;
logger.LogTrace(Resources.Determining_formattable_files);
var (fileCount, formatableFiles) = await DetermineFormattableFiles(
solution, projectPath, pathsToInclude, pathsToExclude, logger, cancellationToken).ConfigureAwait(false);
var determineFilesMS = workspaceStopwatch.ElapsedMilliseconds - loadWorkspaceMS;
logger.LogTrace(Resources.Complete_in_0_ms, determineFilesMS);
logger.LogTrace(Resources.Running_formatters);
var formattedFiles = new List<FormattedFile>();
var formattedSolution = await RunCodeFormattersAsync(
solution, formatableFiles, options, logger, formattedFiles, cancellationToken).ConfigureAwait(false);
var formatterRanMS = workspaceStopwatch.ElapsedMilliseconds - loadWorkspaceMS - determineFilesMS;
logger.LogTrace(Resources.Complete_in_0_ms, formatterRanMS);
var solutionChanges = formattedSolution.GetChanges(solution);
var filesFormatted = 0;
foreach (var projectChanges in solutionChanges.GetProjectChanges())
{
foreach (var changedDocumentId in projectChanges.GetChangedDocuments())
{
var changedDocument = solution.GetDocument(changedDocumentId);
logger.LogInformation(Resources.Formatted_code_file_0, Path.GetFileName(changedDocument.FilePath));
filesFormatted++;
}
}
var exitCode = 0;
if (saveFormattedFiles && !workspace.TryApplyChanges(formattedSolution))
{
logger.LogError(Resources.Failed_to_save_formatting_changes);
exitCode = 1;
}
if (exitCode == 0 && !string.IsNullOrWhiteSpace(reportPath))
{
var reportFilePath = GetReportFilePath(reportPath);
logger.LogInformation(Resources.Writing_formatting_report_to_0, reportFilePath);
var seralizerOptions = new JsonSerializerOptions
{
WriteIndented = true
};
var formattedFilesJson = JsonSerializer.Serialize(formattedFiles, seralizerOptions);
File.WriteAllText(reportFilePath, formattedFilesJson);
}
logger.LogDebug(Resources.Formatted_0_of_1_files, filesFormatted, fileCount);
logger.LogInformation(Resources.Format_complete_in_0_ms, workspaceStopwatch.ElapsedMilliseconds);
return new WorkspaceFormatResult(filesFormatted, fileCount, exitCode);
}
}
private static string GetReportFilePath(string reportPath)
{
var defaultReportName = "format-report.json";
if (reportPath.EndsWith(".json"))
{
return reportPath;
}
else if (reportPath == ".")
{
return Path.Combine(Environment.CurrentDirectory, defaultReportName);
}
else
{
return Path.Combine(reportPath, defaultReportName);
}
}
private static async Task<Workspace> OpenWorkspaceAsync(
string workspacePath,
WorkspaceType workspaceType,
ImmutableHashSet<string> pathsToInclude,
bool logWorkspaceWarnings,
ILogger logger,
CancellationToken cancellationToken)
{
if (workspaceType == WorkspaceType.Folder)
{
var folderWorkspace = FolderWorkspace.Create();
await folderWorkspace.OpenFolder(workspacePath, pathsToInclude, cancellationToken);
return folderWorkspace;
}
return await OpenMSBuildWorkspaceAsync(workspacePath, workspaceType, logWorkspaceWarnings, logger, cancellationToken);
}
private static async Task<Workspace> OpenMSBuildWorkspaceAsync(
string solutionOrProjectPath,
WorkspaceType workspaceType,
bool logWorkspaceWarnings,
ILogger logger,
CancellationToken cancellationToken)
{
var properties = new Dictionary<string, string>(StringComparer.Ordinal)
{
// This property ensures that XAML files will be compiled in the current AppDomain
// rather than a separate one. Any tasks isolated in AppDomains or tasks that create
// AppDomains will likely not work due to https://github.com/Microsoft/MSBuildLocator/issues/16.
{ "AlwaysCompileMarkupFilesInSeparateDomain", bool.FalseString },
// This flag is used at restore time to avoid imports from packages changing the inputs to restore,
// without this it is possible to get different results between the first and second restore.
{ "ExcludeRestorePackageImports", bool.TrueString },
};
var workspace = MSBuildWorkspace.Create(properties);
if (workspaceType == WorkspaceType.Solution)
{
await workspace.OpenSolutionAsync(solutionOrProjectPath, cancellationToken: cancellationToken).ConfigureAwait(false);
}
else
{
try
{
await workspace.OpenProjectAsync(solutionOrProjectPath, cancellationToken: cancellationToken).ConfigureAwait(false);
}
catch (InvalidOperationException)
{
logger.LogError(Resources.Could_not_format_0_Format_currently_supports_only_CSharp_and_Visual_Basic_projects, solutionOrProjectPath);
workspace.Dispose();
return null;
}
}
LogWorkspaceDiagnostics(logger, logWorkspaceWarnings, workspace.Diagnostics);
return workspace;
}
private static void LogWorkspaceDiagnostics(ILogger logger, bool logWorkspaceWarnings, ImmutableList<WorkspaceDiagnostic> diagnostics)
{
if (!logWorkspaceWarnings)
{
if (diagnostics.Count > 0)
{
logger.LogWarning(Resources.Warnings_were_encountered_while_loading_the_workspace_Set_the_verbosity_option_to_the_diagnostic_level_to_log_warnings);
}
return;
}
foreach (var diagnostic in diagnostics)
{
if (diagnostic.Kind == WorkspaceDiagnosticKind.Failure)
{
logger.LogError(diagnostic.Message);
}
else
{
logger.LogWarning(diagnostic.Message);
}
}
}
private static async Task<Solution> RunCodeFormattersAsync(
Solution solution,
ImmutableArray<(DocumentId, OptionSet, ICodingConventionsSnapshot)> formattableDocuments,
FormatOptions options,
ILogger logger,
List<FormattedFile> formattedFiles,
CancellationToken cancellationToken)
{
var formattedSolution = solution;
foreach (var codeFormatter in s_codeFormatters)
{
formattedSolution = await codeFormatter.FormatAsync(formattedSolution, formattableDocuments, options, logger, formattedFiles, cancellationToken).ConfigureAwait(false);
}
return formattedSolution;
}
internal static async Task<(int, ImmutableArray<(DocumentId, OptionSet, ICodingConventionsSnapshot)>)> DetermineFormattableFiles(
Solution solution,
string projectPath,
ImmutableHashSet<string> pathsToInclude,
ImmutableHashSet<string> pathsToExclude,
ILogger logger,
CancellationToken cancellationToken)
{
var codingConventionsManager = CodingConventionsManagerFactory.CreateCodingConventionsManager();
var optionsApplier = new EditorConfigOptionsApplier();
var fileCount = 0;
var getDocumentsAndOptions = new List<Task<(Document, OptionSet, ICodingConventionsSnapshot, bool)>>(solution.Projects.Sum(project => project.DocumentIds.Count));
foreach (var project in solution.Projects)
{
// If a project is used as a workspace, then ignore other referenced projects.
if (!string.IsNullOrEmpty(projectPath) && !project.FilePath.Equals(projectPath, StringComparison.OrdinalIgnoreCase))
{
logger.LogDebug(Resources.Skipping_referenced_project_0, project.Name);
continue;
}
// Ignore unsupported project types.
if (project.Language != LanguageNames.CSharp && project.Language != LanguageNames.VisualBasic)
{
logger.LogWarning(Resources.Could_not_format_0_Format_currently_supports_only_CSharp_and_Visual_Basic_projects, project.FilePath);
continue;
}
fileCount += project.DocumentIds.Count;
// Get project documents and options with .editorconfig settings applied.
var getProjectDocuments = project.DocumentIds.Select(documentId => GetDocumentAndOptions(
project, documentId, pathsToInclude, pathsToExclude, codingConventionsManager, optionsApplier, cancellationToken));
getDocumentsAndOptions.AddRange(getProjectDocuments);
}
var documentsAndOptions = await Task.WhenAll(getDocumentsAndOptions).ConfigureAwait(false);
var foundEditorConfig = documentsAndOptions.Any(documentAndOptions => documentAndOptions.Item4);
var addedFilePaths = new HashSet<string>(documentsAndOptions.Length);
var formattableFiles = ImmutableArray.CreateBuilder<(DocumentId, OptionSet, ICodingConventionsSnapshot)>(documentsAndOptions.Length);
foreach (var (document, options, codingConventions, hasEditorConfig) in documentsAndOptions)
{
if (document is null)
{
continue;
}
// If any code file has an .editorconfig, then we should ignore files without an .editorconfig entry.
if (foundEditorConfig && !hasEditorConfig)
{
continue;
}
// If we've already added this document, either via a link or multi-targeted framework, then ignore.
if (addedFilePaths.Contains(document.FilePath))
{
continue;
}
addedFilePaths.Add(document.FilePath);
formattableFiles.Add((document.Id, options, codingConventions));
}
return (fileCount, formattableFiles.ToImmutableArray());
}
private static async Task<(Document, OptionSet, ICodingConventionsSnapshot, bool)> GetDocumentAndOptions(
Project project,
DocumentId documentId,
ImmutableHashSet<string> pathsToInclude,
ImmutableHashSet<string> pathsToExclude,
ICodingConventionsManager codingConventionsManager,
EditorConfigOptionsApplier optionsApplier,
CancellationToken cancellationToken)
{
var document = project.Solution.GetDocument(documentId);
if (await ShouldIgnoreDocument(document, pathsToInclude, pathsToExclude, cancellationToken))
{
return (null, null, null, false);
}
var context = await codingConventionsManager.GetConventionContextAsync(
document.FilePath, cancellationToken).ConfigureAwait(false);
OptionSet options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
// Check whether an .editorconfig was found for this document.
if (context?.CurrentConventions is null)
{
return (document, options, null, false);
}
options = optionsApplier.ApplyConventions(options, context.CurrentConventions, project.Language);
return (document, options, context.CurrentConventions, true);
}
private static async Task<bool> ShouldIgnoreDocument(
Document document,
ImmutableHashSet<string> pathsToInclude,
ImmutableHashSet<string> pathsToExclude,
CancellationToken cancellationToken)
{
if (!pathsToInclude.IsEmpty && !pathsToInclude.Any(path => document.FilePath.StartsWith(path, StringComparison.OrdinalIgnoreCase)))
{
// If a files list was passed in, then ignore files not present in the list.
return true;
}
else if (!document.SupportsSyntaxTree)
{
return true;
}
else if (await GeneratedCodeUtilities.IsGeneratedCodeAsync(document, cancellationToken).ConfigureAwait(false))
{
// Ignore generated code files.
return true;
}
else if (!pathsToExclude.IsEmpty && pathsToExclude.Any(path => document.FilePath.StartsWith(path, StringComparison.OrdinalIgnoreCase)))
{
// Ignore file in, or under a folder in the list to exclude
return true;
}
else
{
return false;
}
}
}
}