forked from ThreeMammals/Ocelot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.cake
549 lines (442 loc) · 16.4 KB
/
build.cake
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
#tool "dotnet:?package=GitVersion.Tool&version=5.8.1"
#tool "dotnet:?package=coveralls.net&version=3.0.0"
#addin nuget:?package=Cake.Json&version=4.0.0
#addin nuget:?package=Newtonsoft.Json
#addin nuget:?package=System.Text.Encodings.Web&version=4.7.1
#tool "nuget:?package=ReportGenerator"
#addin Cake.Coveralls&version=0.10.1
// compile
var compileConfig = Argument("configuration", "Release");
var slnFile = "./Ocelot.sln";
// build artifacts
var artifactsDir = Directory("artifacts");
// unit testing
var artifactsForUnitTestsDir = artifactsDir + Directory("UnitTests");
var unitTestAssemblies = @"./test/Ocelot.UnitTests/Ocelot.UnitTests.csproj";
var minCodeCoverage = 0.80d;
var coverallsRepoToken = "OCELOT_COVERALLS_TOKEN";
var coverallsRepo = "https://coveralls.io/github/ThreeMammals/Ocelot";
// acceptance testing
var artifactsForAcceptanceTestsDir = artifactsDir + Directory("AcceptanceTests");
var acceptanceTestAssemblies = @"./test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj";
// integration testing
var artifactsForIntegrationTestsDir = artifactsDir + Directory("IntegrationTests");
var integrationTestAssemblies = @"./test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj";
// benchmark testing
var artifactsForBenchmarkTestsDir = artifactsDir + Directory("BenchmarkTests");
var benchmarkTestAssemblies = @"./test/Ocelot.Benchmarks";
// packaging
var packagesDir = artifactsDir + Directory("Packages");
var releaseNotesFile = packagesDir + File("releasenotes.md");
var artifactsFile = packagesDir + File("artifacts.txt");
// stable releases
var tagsUrl = "https://api.github.com/repos/ThreeMammals/ocelot/releases/tags/";
var nugetFeedStableKey = EnvironmentVariable("OCELOT_NUTGET_API_KEY");
var nugetFeedStableUploadUrl = "https://www.nuget.org/api/v2/package";
var nugetFeedStableSymbolsUploadUrl = "https://www.nuget.org/api/v2/package";
// internal build variables - don't change these.
string committedVersion = "0.0.0-dev";
GitVersion versioning = null;
int releaseId = 0;
string gitHubUsername = "TomPallister";
string gitHubPassword = Environment.GetEnvironmentVariable("OCELOT_GITHUB_API_KEY");
var target = Argument("target", "Default");
Information("target is " + target);
Information("Build configuration is " + compileConfig);
Task("Default")
.IsDependentOn("Build");
Task("Build")
.IsDependentOn("RunTests");
Task("ReleaseNotes")
.IsDependentOn("CreateReleaseNotes");
Task("RunTests")
.IsDependentOn("RunUnitTests")
.IsDependentOn("RunAcceptanceTests")
.IsDependentOn("RunIntegrationTests");
Task("Release")
.IsDependentOn("Build")
.IsDependentOn("CreateArtifacts")
.IsDependentOn("PublishGitHubRelease")
.IsDependentOn("PublishToNuget");
Task("Compile")
.IsDependentOn("Clean")
.IsDependentOn("Version")
.Does(() =>
{
var settings = new DotNetBuildSettings
{
Configuration = compileConfig,
};
DotNetBuild(slnFile, settings);
});
Task("Clean")
.Does(() =>
{
if (DirectoryExists(artifactsDir))
{
DeleteDirectory(artifactsDir, new DeleteDirectorySettings {
Recursive = true,
Force = true
});
}
CreateDirectory(artifactsDir);
});
Task("CreateReleaseNotes")
.Does(() =>
{
Information("Generating release notes at " + releaseNotesFile);
IEnumerable<string> lastReleaseTag;
var lastReleaseTagExitCode = StartProcess(
"git",
new ProcessSettings {
Arguments = "describe --tags --abbrev=0",
RedirectStandardOutput = true
},
out lastReleaseTag
);
if (lastReleaseTagExitCode != 0)
{
throw new Exception("Failed to get latest release tag");
}
var lastRelease = lastReleaseTag.First();
Information("Last release tag is " + lastRelease);
IEnumerable<string> releaseNotes;
var releaseNotesExitCode = StartProcess(
"git",
new ProcessSettings {
Arguments = $"log --pretty=format:\"%h - %an - %s\" {lastRelease}..HEAD",
RedirectStandardOutput = true
},
out releaseNotes
);
if (releaseNotesExitCode != 0)
{
throw new Exception("Failed to generate release notes");
}
EnsureDirectoryExists(packagesDir);
System.IO.File.WriteAllLines(releaseNotesFile, releaseNotes);
if (string.IsNullOrEmpty(System.IO.File.ReadAllText(releaseNotesFile)))
{
System.IO.File.WriteAllText(releaseNotesFile, "No commits since last release");
}
Information("Release notes are\r\n" + System.IO.File.ReadAllText(releaseNotesFile));
});
Task("Version")
.IsDependentOn("CreateReleaseNotes")
.Does(() =>
{
versioning = GetNuGetVersionForCommit();
var nugetVersion = versioning.NuGetVersion;
Information("SemVer version number: " + nugetVersion);
if (IsRunningOnCircleCI())
{
Information("Persisting version number...");
PersistVersion(committedVersion, nugetVersion);
}
else
{
Information("We are not running on build server, so we won't persist the version number.");
}
});
Task("RunUnitTests")
.IsDependentOn("Compile")
.Does(() =>
{
var testSettings = new DotNetCoreTestSettings
{
Configuration = compileConfig,
ResultsDirectory = artifactsForUnitTestsDir,
ArgumentCustomization = args => args
// this create the code coverage report
.Append("--collect:\"XPlat Code Coverage\"")
};
EnsureDirectoryExists(artifactsForUnitTestsDir);
DotNetCoreTest(unitTestAssemblies, testSettings);
var coverageSummaryFile = GetSubDirectories(artifactsForUnitTestsDir).First().CombineWithFilePath(File("coverage.cobertura.xml"));
Information(coverageSummaryFile);
Information(artifactsForUnitTestsDir);
// todo bring back report generator to get a friendly report
// ReportGenerator(coverageSummaryFile, artifactsForUnitTestsDir);
// https://github.com/danielpalme/ReportGenerator
if (IsRunningOnCircleCI() && IsMain())
{
var repoToken = EnvironmentVariable(coverallsRepoToken);
if (string.IsNullOrEmpty(repoToken))
{
throw new Exception(string.Format("Coveralls repo token not found. Set environment variable '{0}'", coverallsRepoToken));
}
Information(string.Format("Uploading test coverage to {0}", coverallsRepo));
CoverallsNet(coverageSummaryFile, CoverallsNetReportType.OpenCover, new CoverallsNetSettings()
{
RepoToken = repoToken
});
}
else
{
Information("We are not running on the build server so we won't publish the coverage report to coveralls.io");
}
var sequenceCoverage = XmlPeek(coverageSummaryFile, "//coverage/@line-rate");
var branchCoverage = XmlPeek(coverageSummaryFile, "//coverage/@line-rate");
Information("Sequence Coverage: " + sequenceCoverage);
if(double.Parse(sequenceCoverage) < minCodeCoverage)
{
var whereToCheck = !IsRunningOnCircleCI() ? coverallsRepo : artifactsForUnitTestsDir;
throw new Exception(string.Format("Code coverage fell below the threshold of {0}%. You can find the code coverage report at {1}", minCodeCoverage, whereToCheck));
};
});
Task("RunAcceptanceTests")
.IsDependentOn("Compile")
.Does(() =>
{
var settings = new DotNetCoreTestSettings
{
Configuration = compileConfig,
ArgumentCustomization = args => args
.Append("--no-restore")
.Append("--no-build")
};
EnsureDirectoryExists(artifactsForAcceptanceTestsDir);
DotNetCoreTest(acceptanceTestAssemblies, settings);
});
Task("RunIntegrationTests")
.IsDependentOn("Compile")
.Does(() =>
{
var settings = new DotNetCoreTestSettings
{
Configuration = compileConfig,
ArgumentCustomization = args => args
.Append("--no-restore")
.Append("--no-build")
};
EnsureDirectoryExists(artifactsForIntegrationTestsDir);
DotNetCoreTest(integrationTestAssemblies, settings);
});
Task("CreateArtifacts")
.IsDependentOn("Compile")
.Does(() =>
{
EnsureDirectoryExists(packagesDir);
CopyFiles("./src/**/Release/Ocelot.*.nupkg", packagesDir);
var projectFiles = GetFiles("./src/**/Release/Ocelot.*.nupkg");
foreach(var projectFile in projectFiles)
{
System.IO.File.AppendAllLines(artifactsFile, new[]{
projectFile.GetFilename().FullPath,
"releasenotes.md"
});
}
var artifacts = System.IO.File
.ReadAllLines(artifactsFile)
.Distinct();
foreach(var artifact in artifacts)
{
var codePackage = packagesDir + File(artifact);
Information("Created package " + codePackage);
}
});
Task("PublishGitHubRelease")
.IsDependentOn("CreateArtifacts")
.Does(() =>
{
if (IsRunningOnCircleCI())
{
var path = packagesDir.ToString() + @"/**/*";
CreateGitHubRelease();
foreach (var file in GetFiles(path))
{
UploadFileToGitHubRelease(file);
}
CompleteGitHubRelease();
}
});
Task("EnsureStableReleaseRequirements")
.Does(() =>
{
Information("Check if stable release...");
if (!IsRunningOnCircleCI())
{
throw new Exception("Stable release should happen via circleci");
}
Information("Release is stable...");
});
Task("DownloadGitHubReleaseArtifacts")
.Does(() =>
{
try
{
// hack to let GitHub catch up, todo - refactor to poll
System.Threading.Thread.Sleep(5000);
EnsureDirectoryExists(packagesDir);
var releaseUrl = tagsUrl + versioning.NuGetVersion;
var assets_url = Newtonsoft.Json.Linq.JObject.Parse(GetResource(releaseUrl))
.Value<string>("assets_url");
var assets = GetResource(assets_url);
foreach(var asset in Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JArray>(assets))
{
var file = packagesDir + File(asset.Value<string>("name"));
DownloadFile(asset.Value<string>("browser_download_url"), file);
}
}
catch(Exception exception)
{
Information("There was an exception " + exception);
throw;
}
});
Task("PublishToNuget")
.IsDependentOn("DownloadGitHubReleaseArtifacts")
.Does(() =>
{
if (IsRunningOnCircleCI())
{
PublishPackages(packagesDir, artifactsFile, nugetFeedStableKey, nugetFeedStableUploadUrl, nugetFeedStableSymbolsUploadUrl);
}
});
RunTarget(target);
/// Gets unique nuget version for this commit
private GitVersion GetNuGetVersionForCommit()
{
GitVersion(new GitVersionSettings{
UpdateAssemblyInfo = false,
OutputType = GitVersionOutput.BuildServer
});
return GitVersion(new GitVersionSettings{ OutputType = GitVersionOutput.Json });
}
/// Updates project version in all of our projects
private void PersistVersion(string committedVersion, string newVersion)
{
Information(string.Format("We'll search all csproj files for {0} and replace with {1}...", committedVersion, newVersion));
var projectFiles = GetFiles("./**/*.csproj");
foreach(var projectFile in projectFiles)
{
var file = projectFile.ToString();
Information(string.Format("Updating {0}...", file));
var updatedProjectFile = System.IO.File.ReadAllText(file)
.Replace(committedVersion, newVersion);
System.IO.File.WriteAllText(file, updatedProjectFile);
}
}
/// Publishes code and symbols packages to nuget feed, based on contents of artifacts file
private void PublishPackages(ConvertableDirectoryPath packagesDir, ConvertableFilePath artifactsFile, string feedApiKey, string codeFeedUrl, string symbolFeedUrl)
{
Information("PublishPackages");
var artifacts = System.IO.File
.ReadAllLines(artifactsFile)
.Distinct();
foreach(var artifact in artifacts)
{
if (artifact == "releasenotes.md")
{
continue;
}
var codePackage = packagesDir + File(artifact);
Information("Pushing package " + codePackage);
Information("Calling NuGetPush");
DotNetNuGetPush(
codePackage,
new DotNetNuGetPushSettings {
ApiKey = feedApiKey,
Source = codeFeedUrl
});
}
}
private void CreateGitHubRelease()
{
var json = $"{{ \"tag_name\": \"{versioning.NuGetVersion}\", \"target_commitish\": \"main\", \"name\": \"{versioning.NuGetVersion}\", \"body\": \"{ReleaseNotesAsJson()}\", \"draft\": true, \"prerelease\": true }}";
var content = new System.Net.Http.StringContent(json, System.Text.Encoding.UTF8, "application/json");
using(var client = new System.Net.Http.HttpClient())
{
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"{gitHubUsername}:{gitHubPassword}")));
client.DefaultRequestHeaders.Add("User-Agent", "Ocelot Release");
var result = client.PostAsync("https://api.github.com/repos/ThreeMammals/Ocelot/releases", content).Result;
if(result.StatusCode != System.Net.HttpStatusCode.Created)
{
throw new Exception("CreateGitHubRelease result.StatusCode = " + result.StatusCode);
}
var returnValue = result.Content.ReadAsStringAsync().Result;
dynamic test = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(returnValue);
releaseId = test.id;
}
}
private string ReleaseNotesAsJson()
{
return System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(System.IO.File.ReadAllText(releaseNotesFile));
}
private void UploadFileToGitHubRelease(FilePath file)
{
var data = System.IO.File.ReadAllBytes(file.FullPath);
var content = new System.Net.Http.ByteArrayContent(data);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
using(var client = new System.Net.Http.HttpClient())
{
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"{gitHubUsername}:{gitHubPassword}")));
client.DefaultRequestHeaders.Add("User-Agent", "Ocelot Release");
var result = client.PostAsync($"https://uploads.github.com/repos/ThreeMammals/Ocelot/releases/{releaseId}/assets?name={file.GetFilename()}", content).Result;
if(result.StatusCode != System.Net.HttpStatusCode.Created)
{
throw new Exception("UploadFileToGitHubRelease result.StatusCode = " + result.StatusCode);
}
}
}
private void CompleteGitHubRelease()
{
var json = $"{{ \"tag_name\": \"{versioning.NuGetVersion}\", \"target_commitish\": \"main\", \"name\": \"{versioning.NuGetVersion}\", \"body\": \"{ReleaseNotesAsJson()}\", \"draft\": false, \"prerelease\": false }}";
var request = new System.Net.Http.HttpRequestMessage(new System.Net.Http.HttpMethod("Patch"), $"https://api.github.com/repos/ThreeMammals/Ocelot/releases/{releaseId}");
request.Content = new System.Net.Http.StringContent(json, System.Text.Encoding.UTF8, "application/json");
using(var client = new System.Net.Http.HttpClient())
{
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"{gitHubUsername}:{gitHubPassword}")));
client.DefaultRequestHeaders.Add("User-Agent", "Ocelot Release");
var result = client.SendAsync(request).Result;
if(result.StatusCode != System.Net.HttpStatusCode.OK)
{
throw new Exception("CompleteGitHubRelease result.StatusCode = " + result.StatusCode);
}
}
}
/// gets the resource from the specified url
private string GetResource(string url)
{
try
{
Information("Getting resource from " + url);
var assetsRequest = System.Net.WebRequest.CreateHttp(url);
assetsRequest.Method = "GET";
assetsRequest.Accept = "application/vnd.github.v3+json";
assetsRequest.UserAgent = "BuildScript";
using (var assetsResponse = assetsRequest.GetResponse())
{
var assetsStream = assetsResponse.GetResponseStream();
var assetsReader = new StreamReader(assetsStream);
var response = assetsReader.ReadToEnd();
Information("Response is " + response);
return response;
}
}
catch(Exception exception)
{
Information("There was an exception " + exception);
throw;
}
}
private bool IsRunningOnCircleCI()
{
return !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CIRCLECI"));
}
private bool IsMain()
{
return Environment.GetEnvironmentVariable("CIRCLE_BRANCH").ToLower() == "main";
}