-
Notifications
You must be signed in to change notification settings - Fork 3
/
DotnetBuildHelper.cs
225 lines (194 loc) · 7.61 KB
/
DotnetBuildHelper.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
// ReSharper disable ConvertIfStatementToReturnStatement
namespace Atc.DotNet;
public static class DotnetBuildHelper
{
private const int DefaultTimeoutInSec = 1200;
public static Task<Dictionary<string, int>> BuildAndCollectErrors(
DirectoryInfo rootPath,
int? runNumber = null,
FileInfo? buildFile = null,
bool useNugetRestore = true,
bool useConfigurationReleaseMode = true,
int timeoutInSec = DefaultTimeoutInSec,
string logPrefix = "",
CancellationToken cancellationToken = default)
{
if (rootPath is null)
{
throw new ArgumentNullException(nameof(rootPath));
}
return InvokeBuildAndCollectErrors(
NullLogger.Instance,
rootPath,
runNumber,
buildFile,
useNugetRestore,
useConfigurationReleaseMode,
timeoutInSec,
logPrefix,
cancellationToken);
}
[SuppressMessage("Major Code Smell", "S107:Methods should not have too many parameters", Justification = "OK.")]
public static Task<Dictionary<string, int>> BuildAndCollectErrors(
ILogger logger,
DirectoryInfo rootPath,
int? runNumber = null,
FileInfo? buildFile = null,
bool useNugetRestore = true,
bool useConfigurationReleaseMode = true,
int timeoutInSec = DefaultTimeoutInSec,
string logPrefix = "",
CancellationToken cancellationToken = default)
{
if (logger is null)
{
throw new ArgumentNullException(nameof(logger));
}
if (rootPath is null)
{
throw new ArgumentNullException(nameof(rootPath));
}
return InvokeBuildAndCollectErrors(
logger,
rootPath,
runNumber,
buildFile,
useNugetRestore,
useConfigurationReleaseMode,
timeoutInSec,
logPrefix,
cancellationToken);
}
[SuppressMessage("Major Code Smell", "S107:Methods should not have too many parameters", Justification = "OK.")]
private static async Task<Dictionary<string, int>> InvokeBuildAndCollectErrors(
ILogger logger,
DirectoryInfo rootPath,
int? runNumber,
FileInfo? buildFile,
bool useNugetRestore,
bool useConfigurationReleaseMode,
int timeoutInSec,
string logPrefix,
CancellationToken cancellationToken)
{
logger.LogInformation(runNumber is > 0
? $"{logPrefix}Build ({runNumber})"
: $"{logPrefix}Build");
var stopwatch = Stopwatch.StartNew();
(_, string output) = await RunBuildCommand(
rootPath,
buildFile,
useNugetRestore,
useConfigurationReleaseMode,
timeoutInSec,
cancellationToken)
.ConfigureAwait(false);
if (output.StartsWith("Please specify which", StringComparison.Ordinal) &&
output.Contains("option: --buildFile", StringComparison.Ordinal))
{
stopwatch.Stop();
throw new IOException(output);
}
var parsedErrors = ParseBuildOutput(output);
int totalErrors = parsedErrors.Sum(parsedError => parsedError.Value);
stopwatch.Stop();
if (totalErrors > 0)
{
logger.LogError(runNumber is > 0
? $"{logPrefix}Found {totalErrors} errors divided into {parsedErrors.Count} rules in Build ({runNumber})"
: $"{logPrefix}Found {totalErrors} errors divided into {parsedErrors.Count} rules");
}
logger.LogInformation(runNumber is > 0
? $"{logPrefix}Build ({runNumber}) time: {stopwatch.Elapsed.GetPrettyTime()}"
: $"{logPrefix}Build time: {stopwatch.Elapsed.GetPrettyTime()}");
return parsedErrors;
}
private static async Task<(bool IsSuccessful, string Output)> RunBuildCommand(
DirectoryInfo rootPath,
FileInfo? buildFile,
bool useNugetRestore,
bool useConfigurationReleaseMode,
int timeoutInSec,
CancellationToken cancellationToken)
{
var argumentNugetRestore = useNugetRestore
? string.Empty
: " --no-restore";
var argumentConfigurationReleaseMode = useConfigurationReleaseMode
? " -c Release"
: " -c Debug";
string arguments;
if (buildFile is not null && buildFile.Exists)
{
arguments = $"build {buildFile.FullName}{argumentNugetRestore}{argumentConfigurationReleaseMode} -v q -clp:NoSummary";
}
else
{
arguments = $"build{argumentNugetRestore}{argumentConfigurationReleaseMode} -v q -clp:NoSummary";
var slnFiles = Directory.GetFiles(rootPath.FullName, "*.sln");
if (slnFiles.Length > 1)
{
var files = slnFiles.Select(x => new FileInfo(x).Name).ToList();
return (
IsSuccessful: false,
Output: $"Please specify which solution file to use:{Environment.NewLine} - {string.Join($"{Environment.NewLine} - ", files)}{Environment.NewLine} Specify the solution file using this option: --buildFile");
}
var csprojFiles = Directory.GetFiles(rootPath.FullName, "*.csproj");
if (csprojFiles.Length > 1)
{
var files = csprojFiles.Select(x => new FileInfo(x).Name).ToList();
return (
IsSuccessful: false,
Output: $"Please specify which C# project file to use:{Environment.NewLine} - {string.Join($"{Environment.NewLine} - ", files)}{Environment.NewLine} Specify the C# project file using this option: --buildFile");
}
}
var dotnetFile = DotnetHelper.GetDotnetExecutable();
return await ProcessHelper
.Execute(rootPath, dotnetFile, arguments, runAsAdministrator: false, (ushort)timeoutInSec, cancellationToken)
.ConfigureAwait(false);
}
private static Dictionary<string, int> ParseBuildOutput(string buildResult)
{
const string? regexPatternMsBuild = @": error MSB(\S+?): (.*)";
const string? regexPatternNuget = @": error NU(\S+?): (.*)";
const string? regexPatternGeneral = @": error ([A-Z]\S+?): (.*) \[";
var errors = ParseBuildOutputHelper(buildResult, regexPatternMsBuild, "MSB");
if (errors.Any())
{
return errors;
}
errors = ParseBuildOutputHelper(buildResult, regexPatternNuget, "NU");
if (errors.Any())
{
return errors;
}
return ParseBuildOutputHelper(buildResult, regexPatternGeneral);
}
private static Dictionary<string, int> ParseBuildOutputHelper(
string buildResult,
string regexPattern,
string? keyPrefix = null)
{
var errors = new Dictionary<string, int>(StringComparer.Ordinal);
var regex = new Regex(
regexPattern,
RegexOptions.Multiline | RegexOptions.Compiled,
TimeSpan.FromMinutes(2));
var matchCollection = regex.Matches(buildResult);
foreach (var matchGroups in matchCollection.Select(x => x.Groups))
{
if (matchGroups.Count != 3)
{
continue;
}
var key = keyPrefix is null
? matchGroups[1].Value
: keyPrefix + matchGroups[1].Value;
if (!errors.TryAdd(key, 1))
{
errors[key] += 1;
}
}
return errors;
}
}