This repository was archived by the owner on Nov 3, 2025. It is now read-only.
forked from camunda-community-hub/zeebe-client-csharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.cake
More file actions
441 lines (381 loc) · 12.7 KB
/
Copy pathbuild.cake
File metadata and controls
441 lines (381 loc) · 12.7 KB
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// add-ins
#addin nuget:?package=Cake.Git&version=3.0.0
// tools - nuget
#addin nuget:?package=Cake.Incubator&version=8.0.0
// tools - dotnet
#tool dotnet:?package=GitVersion.Tool&version=6.4.0
#tool dotnet:?package=dotnet-reportgenerator-globaltool&version=5.1.26
///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var targets = Argument("targets", "");
var configuration = Argument("configuration", "Release");
var buildCounter = Argument("buildcounter", "0");
var nugetPublishServerUrl = "carweb";
var nugetPublishServerApiKey = "arbitrary";
var pushPreRelease = Argument("pushPreRelease", false);
///////////////////////////////////////////////////////////////////////////////
// SETTINGS
///////////////////////////////////////////////////////////////////////////////
var distDirectory = Directory("./.dist");
var packageDirectory = Directory("./.pack");
var testOutputDir = Context.MakeAbsolute(Directory("./.test-results"));
var testCoverageOutPutDir = testOutputDir + "/.coverage";
var testCoverageReportOutPutDir = $"{testOutputDir}/.coverage-report";
var mergedCoverageResults = "";
var isMainBranch = false;
var currentBranch = "";
var currentVersion = "1.0.0.0";
var currentVersionNuGet = "1.0.0.0";
var preReleaseTag = "";
using System.Text.RegularExpressions;
///////////////////////////////////////////////////////////////////////////////
// TASKS
///////////////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Build")
.IsDependentOn("Test");
Task("Build")
.IsDependentOn("BranchInfo")
.IsDependentOn("Version")
.IsDependentOn("Clean")
.IsDependentOn("Build-Solution");
Task("Test")
.IsDependentOn("Test-All")
.IsDependentOn("Generate-CoverageReport")
.IsDependentOn("Update-Status");
var deploy = Task("Deploy")
.IsDependentOn("Build")
.IsDependentOn("Test")
.IsDependentOn("Pack")
.IsDependentOn("Push-Nuget")
;
#region Build
///////////////////////////////////////////////////////////////////////////////
// BUILD TASKS
///////////////////////////////////////////////////////////////////////////////
Task("BranchInfo")
.Does(()=>
{
WriteProgressMessage("Getting branch info...");
var gitBranch = GitBranchCurrent("./");
Information($"CanonicalName: {gitBranch.CanonicalName}");
Information($"FriendlyName: {gitBranch.FriendlyName}");
Information($"IsRemote: {gitBranch.IsRemote}");
currentBranch = gitBranch.FriendlyName;
isMainBranch = StringComparer.OrdinalIgnoreCase.Equals("main",currentBranch);
Information($"isMainBranch: {isMainBranch}");
});
Task("Version")
.Does(()=>
{
WriteProgressMessage("Calculating semantic version...");
GitVersion(new GitVersionSettings(){
OutputType = GitVersionOutput.BuildServer
});
var gitVersion = GitVersion(new GitVersionSettings(){
OutputType = GitVersionOutput.Json,
Verbosity = GitVersionVerbosity.Verbose
});
currentVersion = gitVersion.SemVer;
currentVersionNuGet = currentVersion;
preReleaseTag = gitVersion.PreReleaseTag;
Information($"Current version: {currentVersion}");
Information($"Current version NuGet: {currentVersionNuGet}");
Information($"##teamcity[buildNumber '{currentVersion}']");
});
Task("Clean")
.Does(()=>
{
WriteProgressMessage("Cleaning directories...");
CleanDirectory(distDirectory);
CleanDirectory(packageDirectory);
CleanDirectory(testOutputDir);
});
Task("Build-Solution")
.Does(()=>
{
var solutions = GetFiles("*.sln");
foreach ( var solution in solutions) {
WriteProgressMessage($"Building {solution.GetFilenameWithoutExtension()} v{currentVersion}");
DotNetBuild(solution.FullPath, new DotNetBuildSettings()
{
Configuration = configuration,
NoIncremental = true,
MSBuildSettings = new DotNetMSBuildSettings()
.WithProperty("Version", currentVersion)
});
}
});
#endregion // build
#region Test
///////////////////////////////////////////////////////////////////////////////
// TEST TASKS
///////////////////////////////////////////////////////////////////////////////
Task("Test-Clean")
.Does(()=>{
CleanDirectory(testOutputDir);
Information($"Cleaned: {testOutputDir}");
});
Task("Test-Unit")
.IsDependentOn("Test-Clean")
.Does(()=>{
DetectTestFramework("Unit");
RunTestsByType("Unit", testFrameworksInUse.First().Key);
});
Task("Test-Service")
.IsDependentOn("Test-Clean")
.Does(()=>{
DetectTestFramework("Service");
RunTestsByType("Service", testFrameworksInUse.First().Key);
});
Task("Test-All")
.IsDependentOn("Test-Clean")
.Does(()=>{
DetectTestFramework("Unit");
// DetectTestFramework("Service");
if(testFrameworksInUse.Keys.Count > 1){
Information("Multiple test frameworks detected. Parallel test runs not possible.");
foreach (var testFx in testFrameworksInUse)
{
foreach (var testType in testFx.Value.TestsByType)
{
RunTestsByType(testType.Key, testFx.Key);
}
}
}
else{
Information($"Single test framework detected ({testFrameworksInUse.First().Key}). Running tests in parallel.");
RunTests(".");
}
});
private Dictionary<string, TestInfo> testFrameworksInUse = new Dictionary<string, TestInfo>();
private class TestInfo
{
public Dictionary<string, ICollection<FilePath>> TestsByType = new Dictionary<string, ICollection<FilePath>>();
public TestInfo AddTests(string testType, FilePath projectFile){
if(!TestsByType.ContainsKey(testType))
{
TestsByType.Add(testType, new List<FilePath>{projectFile});
}
else {
TestsByType[testType].Add(projectFile);
}
return this;
}
public override string ToString()
{
var info = "";
foreach (var testType in TestsByType)
{
info += $"{testType.Key}: {Environment.NewLine}";
foreach (var projFile in testType.Value)
{
info += $"- {projFile.FullPath}{Environment.NewLine}";
}
}
return info;
}
}
private void DetectTestFramework(string testType)
{
var folderPattern = GetTestFolderPattern(testType);
var projects = GetFiles($"./test/*{folderPattern}*/**/*.csproj");
foreach(var projFile in projects)
{
var proj = ParseProject(projFile, configuration).NetCore;
var packageRefs = proj.PackageReferences;
if (packageRefs.Any(r => r.Name.ToLower().Contains("nunit")))
AddToTestsByType(testFrameworksInUse, "NUnit", testType, projFile);
}
}
private void AddToTestsByType(Dictionary<string, TestInfo> testsByType, string testFramework, string testType, FilePath projectFile)
{
if(!testsByType.ContainsKey(testFramework))
{
var ti = new TestInfo().AddTests(testType, projectFile);
testsByType.Add(testFramework, ti);
}
else {
testsByType[testFramework].AddTests(testType, projectFile);
}
}
private void RunTestsByType(string testType = "unit", string testFramework = "nunit"){
WriteProgressMessage($"Running {testType} tests...");
var folderPattern = GetTestFolderPattern(testType);
var projects = GetFiles($"./test/*{folderPattern}*/**/*.csproj");
foreach(var project in projects)
{
Information("Testing project " + project);
RunTests(project.ToString(), testFramework);
}
}
private void RunTests(string path, string testFramework = "nunit"){
var testSettings = new DotNetTestSettings {
Configuration = configuration,
NoBuild = true,
ArgumentCustomization = args => args
.Append("--no-restore")
.Append($"--results-directory {testCoverageOutPutDir}")
.Append("--collect \"XPlat Code Coverage\"")
};
if (testFramework.ToLower() == "xunit") {
Information($"Adding console logger for {testFramework}...");
testSettings.Loggers.Add ("console;verbosity=normal");
}
DotNetTest(path, testSettings);
}
private string GetTestFolderPattern(string testType){
var folderPattern = testType;
if(testType.ToLower() == "unit"){
folderPattern = "[uU]nit";
}
if(testType.ToLower() == "service"){
folderPattern = "[sS]service";
}
return folderPattern;
}
Task("Generate-CoverageReport")
.Does(()=>{
WriteProgressMessage("Generating coverage reports...");
ReportGenerator(
report: $"{testCoverageOutPutDir}/**/*.cobertura.xml",
targetDir: testCoverageReportOutPutDir,
settings: new ReportGeneratorSettings{
ReportTypes = new [] { ReportGeneratorReportType.HtmlInline },
ToolPath = Context.Tools.Resolve("reportgenerator") ?? Context.Tools.Resolve("reportgenerator.exe"),
Verbosity = ReportGeneratorVerbosity.Info
});
});
Task("Update-Status")
.Does(() => {
var coverageStatus = "";
var covReportPath = $"{testCoverageReportOutPutDir}/index.htm";
Information($"Coverage report: {covReportPath}");
if(FileExists(covReportPath)){
var covReport = System.IO.File.ReadAllText(covReportPath);
Information($"Coverage report size: {covReport.Length}");
var branchCovRegExPattern = @"Branch coverage.*?(?<branchcov>\d+(\.\d)?)%\s";
decimal branchCoveragePct = GetCoveragePct(covReport, branchCovRegExPattern, "branchcov");
Information($"Branch coverage: {branchCoveragePct}");
var lineCovRegExPattern = @"Line coverage.*?(?<linecov>\d+(\.\d)?)%\s";
decimal lineCoveragePct = GetCoveragePct(covReport, lineCovRegExPattern, "linecov");
Information($"Line coverage: {lineCoveragePct}");
if (branchCoveragePct > 0 && lineCoveragePct > 0){
coverageStatus = $". Coverage: {branchCoveragePct.ToString("#")}/{lineCoveragePct.ToString("#")}% (b/l)";
}
else {
coverageStatus = ". No test coverage!";
}
Information("Coverage status: " + coverageStatus);
}
Information($"##teamcity[buildStatus text='{{build.status.text}}{coverageStatus}']");
});
private decimal GetCoveragePct(string covReport, string pattern, string matchedGroup){
decimal coveragePct = 0m;
foreach (Match match in Regex.Matches(covReport, pattern)){
var covStr = match.Groups[matchedGroup].Value;
coveragePct = Convert.ToDecimal(covStr, new System.Globalization.CultureInfo("en-US"));
}
return coveragePct;
}
#endregion // TEST
#region Deploy
///////////////////////////////////////////////////////////////////////////////
// DEPLOY TASKS
///////////////////////////////////////////////////////////////////////////////
Task("Pack")
.IsDependentOn("Version")
.Does(()=>
{
var projects = GetFiles($"./src/**/*.csproj");
foreach(var project in projects)
{
// Release package
WriteProgressMessage($"Packaging release NuGet package...");
DotNetPack(
project.ToString(),
new DotNetPackSettings
{
NoBuild = false,
Configuration = configuration,
OutputDirectory = packageDirectory,
DiagnosticOutput = true,
ArgumentCustomization = args => args
.Append($"/p:Version={currentVersionNuGet}")
}
);
WriteProgressMessage($"Packaging symbol NuGet package...");
DotNetPack(
project.ToString(),
new DotNetPackSettings
{
NoBuild = false,
Configuration = "Debug",
OutputDirectory = packageDirectory,
IncludeSymbols = true,
IncludeSource = true,
ArgumentCustomization = args => args
.Append($"/p:Version={currentVersionNuGet}")
}
);
}
});
Task("Push-Nuget")
.Does(()=>
{
var packages = GetFiles($"{packageDirectory}/*.nupkg");
foreach (var package in packages) {
if (!isMainBranch && !pushPreRelease) {
Information($"Not on main branch and 'pushPreRelease' is set to {pushPreRelease} so the following packages will not be pushed:");
Information($"Package: {package}");
continue;
}
// Push normal package
WriteProgressMessage($"Pushing {package} to nuget server");
DotNetNuGetPush(package.ToString(),new DotNetNuGetPushSettings{
Source = nugetPublishServerUrl,
ApiKey = nugetPublishServerApiKey
});
}
});
Task("Deploy-PreRelease")
.Does(() => {
pushPreRelease = true;
RunTarget(deploy.Task.Name);
});
#endregion // Deploy
private void WriteProgressMessage(string message)
{
if(TeamCity.IsRunningOnTeamCity)
{
TeamCity.WriteProgressMessage(message);
}
else
{
Information(message);
}
}
private void WriteStatusMessage(string message)
{
if(TeamCity.IsRunningOnTeamCity)
{
TeamCity.WriteStatus(message);
}
else
{
Information(message);
}
}
///////////////////////////////////////////////////////////////////////////////
// RUNNER
///////////////////////////////////////////////////////////////////////////////
if (string.IsNullOrEmpty(targets)) {
RunTarget(target);
}
else {
foreach (var t in targets.Split('+')) {
RunTarget(t);
}
}