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
174 lines (154 loc) · 6.41 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
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.DotNet.CodeFormatting;
namespace CodeFormatter
{
internal static class Program
{
private static int Main(string[] args)
{
var result = CommandLineParser.Parse(args);
if (result.IsError)
{
Console.Error.WriteLine(result.Error);
CommandLineParser.PrintUsage();
return -1;
}
var options = result.Options;
int exitCode;
switch (options.Operation)
{
case Operation.ShowHelp:
CommandLineParser.PrintUsage();
exitCode = 0;
break;
case Operation.ListRules:
RunListRules();
exitCode = 0;
break;
case Operation.Format:
exitCode = RunFormat(options);
break;
default:
throw new Exception("Invalid enum value: " + options.Operation);
}
return exitCode;
}
private static void RunListRules()
{
var rules = FormattingEngine.GetFormattingRules();
Console.WriteLine("{0,-20} {1}", "Name", "Description");
Console.WriteLine("==============================================");
foreach (var rule in rules)
{
Console.WriteLine("{0,-20} :{1}", rule.Name, rule.Description);
}
}
private static int RunFormat(CommandLineOptions options)
{
using (var cts = new CancellationTokenSource())
{
var ct = cts.Token;
Console.CancelKeyPress += delegate { cts.Cancel(); };
try
{
RunFormatAsync(options, ct).Wait(ct);
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.");
Console.WriteLine(typeLoadException.StackTrace);
var messages = typeLoadException.LoaderExceptions.Select(e => e.Message).Distinct();
foreach (var message in messages)
Console.WriteLine("- {0}", message);
return 1;
}
}
}
private static async Task<int> RunFormatAsync(CommandLineOptions options, CancellationToken cancellationToken)
{
var engine = FormattingEngine.Create();
engine.PreprocessorConfigurations = options.PreprocessorConfigurations;
engine.FileNames = options.FileNames;
engine.CopyrightHeader = options.CopyrightHeader;
engine.AllowTables = options.AllowTables;
engine.Verbose = options.Verbose;
if (!SetRuleMap(engine, options.RuleMap))
{
return 1;
}
foreach (var item in options.FormatTargets)
{
await RunFormatItemAsync(engine, item, options.Language, cancellationToken);
}
return 0;
}
private static async Task RunFormatItemAsync(IFormattingEngine engine, string item, string language, CancellationToken cancellationToken)
{
Console.WriteLine(Path.GetFileName(item));
string extension = Path.GetExtension(item);
if (StringComparer.OrdinalIgnoreCase.Equals(extension, ".rsp"))
{
using (var workspace = CreateWorkspace(ResponseFileWorkspace.Create))
{
Project project = workspace.OpenCommandLineProject(item, language);
await engine.FormatProjectAsync(project, cancellationToken);
}
}
else if (StringComparer.OrdinalIgnoreCase.Equals(extension, ".sln"))
{
using (var workspace = CreateWorkspace(MSBuildWorkspace.Create))
{
workspace.LoadMetadataForReferencedProjects = true;
var solution = await workspace.OpenSolutionAsync(item, cancellationToken);
await engine.FormatSolutionAsync(solution, cancellationToken);
}
}
else
{
using (var workspace = CreateWorkspace(MSBuildWorkspace.Create))
{
workspace.LoadMetadataForReferencedProjects = true;
var project = await workspace.OpenProjectAsync(item, cancellationToken);
await engine.FormatProjectAsync(project, cancellationToken);
}
}
T CreateWorkspace<T>(Func<T> workspaceFunc) where T : Workspace
{
var workspace = workspaceFunc();
workspace.WorkspaceFailed += (sender, args) => Console.WriteLine($"ERROR: {args.Diagnostic.Message}");
return workspace;
}
}
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);
}
return true;
}
}
}