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
233 lines (214 loc) · 9.65 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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.DotNet.CodeFormatting;
namespace CodeFormatter
{
internal static class Program
{
private const string FileSwitch = "/file:";
private const string ConfigSwitch = "/c:";
private const string CopyrightSwitch = "/copyright:";
private const string SearchPatternSwitch = "/searchPattern:";
private static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("CodeFormatter <project or solution or directory> [/file:<filename>] [/nocopyright] [/nounicode] [/tables] [/c:<config1,config2> [/copyright:file] [/recursive] [/searchPattern:<searchPattern>] [/verbose]");
Console.WriteLine(" <filename> - Only apply changes to files with specified name.");
Console.WriteLine(" <configs> - Additional preprocessor configurations the formatter");
Console.WriteLine(" should run under.");
Console.WriteLine(" <copyright> - Specifies file containing copyright header.");
Console.WriteLine(" Use ConvertTests to convert MSTest tests to xUnit.");
Console.WriteLine(" <tables> - Let tables opt out of formatting by defining DOTNET_FORMATTER");
Console.WriteLine(" <verbose> - Verbose output");
Console.WriteLine(" <nounicode> - Do not convert unicode strings to escape sequences");
Console.WriteLine(" <nocopyright>- Do not update the copyright message.");
Console.WriteLine(" <searchPattern>- Pattern to look for projects/solutions within the folder. Default '*.??proj'.");
return -1;
}
var path = args[0];
string[] projectOrSolutionPath;
SearchOption searchOption = SearchOption.TopDirectoryOnly;
string searchPattern = "*.??proj";
if (!File.Exists(path))
{
if (!Directory.Exists(path))
{
Console.Error.WriteLine("Project or solution or directory \"{0}\" doesn't exist.", path);
return -1;
}
else
{
projectOrSolutionPath = null;
}
}
else
{
projectOrSolutionPath = new[] { path };
}
var fileNamesBuilder = ImmutableArray.CreateBuilder<string>();
var ruleTypeBuilder = ImmutableArray.CreateBuilder<string>();
var configBuilder = ImmutableArray.CreateBuilder<string[]>();
var copyrightHeader = FormattingConstants.DefaultCopyrightHeader;
var convertUnicode = true;
var allowTables = false;
var verbose = false;
var comparer = StringComparer.OrdinalIgnoreCase;
for (int i = 1; i < args.Length; i++)
{
string arg = args[i];
if (arg.StartsWith(FileSwitch, StringComparison.OrdinalIgnoreCase))
{
var all = arg.Substring(FileSwitch.Length);
var files = all.Split(new[] { ','}, StringSplitOptions.RemoveEmptyEntries);
fileNamesBuilder.AddRange(files);
}
else if (arg.StartsWith(ConfigSwitch, StringComparison.OrdinalIgnoreCase))
{
var all = arg.Substring(ConfigSwitch.Length);
var configs = all.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
configBuilder.Add(configs);
}
else if (arg.StartsWith(CopyrightSwitch, StringComparison.OrdinalIgnoreCase))
{
var fileName = arg.Substring(CopyrightSwitch.Length);
try
{
copyrightHeader = ImmutableArray.CreateRange(File.ReadAllLines(fileName));
}
catch (Exception ex)
{
Console.Error.WriteLine("Could not read {0}", fileName);
Console.Error.WriteLine(ex.Message);
return -1;
}
}
else if (arg.StartsWith(SearchPatternSwitch, StringComparison.OrdinalIgnoreCase))
{
var pattern = arg.Substring(SearchPatternSwitch.Length);
if (pattern.Length > 0)
{
searchPattern = pattern;
}
}
else if (comparer.Equals(arg, "/nocopyright"))
{
copyrightHeader = ImmutableArray<string>.Empty;
}
else if (comparer.Equals(arg, "/nounicode"))
{
convertUnicode = false;
}
else if (comparer.Equals(arg, "/verbose"))
{
verbose = true;
}
else if (comparer.Equals(arg, "/tables"))
{
allowTables = true;
}
else if (comparer.Equals(arg, "/recursive") || comparer.Equals(arg, "/r"))
{
searchOption = SearchOption.AllDirectories;
}
else
{
ruleTypeBuilder.Add(arg);
}
}
if (projectOrSolutionPath == null)
{
projectOrSolutionPath = Directory.EnumerateFiles(path, searchPattern, searchOption).ToArray();
if (projectOrSolutionPath.Length == 0)
{
Console.Error.WriteLine("Projects or solutions are not found.");
return -1;
}
}
var cts = new CancellationTokenSource();
var ct = cts.Token;
Console.CancelKeyPress += delegate { cts.Cancel(); };
try
{
var rules = ruleTypeBuilder.ToImmutableArray();
var fileNames = fileNamesBuilder.ToImmutableArray();
var config = configBuilder.ToImmutableArray();
foreach (string projectOrSolution in projectOrSolutionPath)
{
RunAsync(
projectOrSolution,
rules,
fileNames,
config,
copyrightHeader,
allowTables,
convertUnicode,
verbose,
ct).Wait(ct);
}
if (projectOrSolutionPath.Length > 1)
{
Console.WriteLine("Completed formatting {0} projects/solutions.", projectOrSolutionPath.Length);
}
else
{
Console.WriteLine("Completed formatting.");
}
return 0;
}
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 1;
}
}
private static async Task RunAsync(
string projectOrSolutionPath,
ImmutableArray<string> ruleTypes,
ImmutableArray<string> fileNames,
ImmutableArray<string[]> preprocessorConfigurations,
ImmutableArray<string> copyrightHeader,
bool allowTables,
bool convertUnicode,
bool verbose,
CancellationToken cancellationToken)
{
var workspace = MSBuildWorkspace.Create();
var engine = FormattingEngine.Create(ruleTypes);
engine.PreprocessorConfigurations = preprocessorConfigurations;
engine.FileNames = fileNames;
engine.CopyrightHeader = copyrightHeader;
engine.AllowTables = allowTables;
engine.ConvertUnicodeCharacters = convertUnicode;
engine.Verbose = verbose;
Console.WriteLine(Path.GetFileName(projectOrSolutionPath));
string extension = Path.GetExtension(projectOrSolutionPath);
if (StringComparer.OrdinalIgnoreCase.Equals(extension, ".sln"))
{
var solution = await workspace.OpenSolutionAsync(projectOrSolutionPath, cancellationToken);
await engine.FormatSolutionAsync(solution, cancellationToken);
}
else
{
workspace.LoadMetadataForReferencedProjects = true;
var project = await workspace.OpenProjectAsync(projectOrSolutionPath, cancellationToken);
await engine.FormatProjectAsync(project, cancellationToken);
}
}
}
}