Skip to content

Commit b0cdbd6

Browse files
committed
2254 GitHub Actions: Cake build job
Changes to be committed: modified: .github/workflows/develop.yml modified: build.cake modified: test/Ocelot.AcceptanceTests/AggregateTests.cs modified: test/Ocelot.AcceptanceTests/Authentication/AuthenticationSteps.cs modified: test/Ocelot.AcceptanceTests/Authentication/AuthenticationTests.cs modified: test/Ocelot.AcceptanceTests/Authentication/MultipleAuthSchemesFeatureTests.cs modified: test/Ocelot.AcceptanceTests/AuthorizationTests.cs modified: test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs modified: test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs modified: test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs modified: test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs modified: test/Ocelot.AcceptanceTests/Steps.cs modified: test/Ocelot.IntegrationTests/CacheManagerTests.cs modified: test/Ocelot.Testing/PortFinder.cs modified: test/Ocelot.UnitTests/Kubernetes/KubeTests.cs modified: test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs
1 parent 09de4ce commit b0cdbd6

16 files changed

+1765
-1683
lines changed

.github/workflows/develop.yml

+44
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ on:
66
branches: [ "develop" ]
77

88
jobs:
9+
#1 Official required job to run utilizing GitHub Actions infrastructure
910
build:
1011
runs-on: ubuntu-latest
1112
strategy:
@@ -33,3 +34,46 @@ jobs:
3334
run: dotnet test --no-restore --no-build --verbosity minimal --framework net${{ matrix.dotnet-version }} ./test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj
3435
- name: Acceptance Tests
3536
run: dotnet test --no-restore --no-build --verbosity minimal --framework net${{ matrix.dotnet-version }} ./test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj
37+
38+
#2 The build job to run in Docker container utilizing images from https://hub.docker.com/u/ocelot2
39+
# The main runnung script is build.cake, a cake-script which is hard to support because of slow and outdated integrated libs
40+
# docker-build:
41+
# runs-on: ubuntu-latest
42+
# container:
43+
# image: node:18
44+
# env:
45+
# NODE_ENV: development
46+
# ports:
47+
# - 80
48+
# volumes:
49+
# - my_docker_volume:/volume_mount
50+
# options: --cpus 1
51+
# container:
52+
# image: ghcr.io/owner/image
53+
# credentials:
54+
# username: ${{ github.actor }}
55+
# password: ${{ secrets.github_token }}
56+
# steps:
57+
# - name: Check for dockerenv file
58+
# run: (ls /.dockerenv && echo Found dockerenv) || (echo No dockerenv)
59+
build-cake:
60+
runs-on: ubuntu-latest
61+
steps:
62+
- name: .NET version
63+
run: dotnet --version
64+
- name: Checkout
65+
uses: actions/checkout@v4
66+
with:
67+
fetch-depth: 0
68+
- name: Setup .NET 9
69+
uses: actions/setup-dotnet@v3
70+
with:
71+
dotnet-version: 9.0.x
72+
- name: .NET version
73+
run: dotnet --version
74+
- name: Get branch name
75+
run: echo "Branch name is ${{ github.ref_name }}"
76+
- name: Cake build
77+
uses: cake-build/cake-action@v3
78+
with:
79+
target: Build

build.cake

+71-45
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#tool dotnet:?package=GitVersion.Tool&version=5.12.0 // 6.0.0-beta.7 supports .NET 8, 7, 6
1+
#tool dotnet:?package=GitVersion.Tool&version=6.2.0 // .NET 8-9
22
#tool dotnet:?package=coveralls.net&version=4.0.1
33
#tool nuget:?package=ReportGenerator&version=5.2.4
44
#addin nuget:?package=Newtonsoft.Json&version=13.0.3
@@ -14,8 +14,10 @@ using System.Linq;
1414
using System.Text.RegularExpressions;
1515

1616
const string Release = "Release"; // task name, target, and Release config name
17+
const string PullRequest = "PullRequest"; // task name, target, and PullRequest config name
1718
const string AllFrameworks = "net8.0;net9.0";
1819
const string LatestFramework = "net9.0";
20+
static string NL = Environment.NewLine;
1921

2022
var compileConfig = Argument("configuration", Release); // compile
2123

@@ -50,16 +52,16 @@ var releaseNotes = new List<string>();
5052
// internal build variables - don't change these.
5153
string committedVersion = "0.0.0-dev";
5254
GitVersion versioning = null;
53-
bool IsTechnicalRelease = false;
55+
bool IsTechnicalRelease = true;
5456

5557
var target = Argument("target", "Default");
5658
var slnFile = (target == Release) ? $"./Ocelot.{Release}.sln" : "./Ocelot.sln";
57-
Information("\nTarget: " + target);
58-
Information("Build: " + compileConfig);
59-
Information("Solution: " + slnFile);
59+
Information($"{NL}Target: {target}");
60+
Information($"Build: {compileConfig}");
61+
Information($"Solution: {slnFile}");
6062

6163
TaskTeardown(context => {
62-
AnsiConsole.Markup($"[green]DONE[/] {context.Task.Name}\n");
64+
AnsiConsole.Markup($"[green]DONE[/] {context.Task.Name}" + NL);
6365
});
6466

6567
Task("Default")
@@ -88,13 +90,14 @@ Task("Compile")
8890
.IsDependentOn("Version")
8991
.Does(() =>
9092
{
93+
Information("Branch: " + GetBranchName());
9194
Information("Build: " + compileConfig);
9295
Information("Solution: " + slnFile);
9396
var settings = new DotNetBuildSettings
9497
{
9598
Configuration = compileConfig,
9699
};
97-
if (target != Release)
100+
if (target == PullRequest)
98101
{
99102
settings.Framework = LatestFramework; // build using .NET 9 SDK only
100103
}
@@ -121,13 +124,20 @@ Task("Version")
121124
.Does(() =>
122125
{
123126
versioning = GetNuGetVersionForCommit();
124-
var nugetVersion = versioning.NuGetVersion;
125-
Information("SemVer version number: " + nugetVersion);
126-
127-
if (IsRunningOnCircleCI())
127+
Information("#########################");
128+
Information("# SemVer Information");
129+
Information("#========================");
130+
Information($"# {nameof(versioning.NuGetVersion)}: {versioning.NuGetVersion}");
131+
Information($"# {nameof(versioning.BranchName)}: {versioning.BranchName}");
132+
Information($"# {nameof(versioning.MajorMinorPatch)}: {versioning.MajorMinorPatch}");
133+
Information($"# {nameof(versioning.SemVer)}: {versioning.SemVer}");
134+
Information($"# {nameof(versioning.InformationalVersion)}: {versioning.InformationalVersion}");
135+
Information("#########################");
136+
137+
if (IsRunningInCICD())
128138
{
129139
Information("Persisting version number...");
130-
PersistVersion(committedVersion, nugetVersion);
140+
PersistVersion(committedVersion, versioning.SemVer);
131141
}
132142
else
133143
{
@@ -139,17 +149,17 @@ Task("GitLogUniqContributors")
139149
.Does(() =>
140150
{
141151
var command = "log --format=\"%aN|%aE\" ";
142-
// command += IsRunningOnCircleCI() ? "| sort | uniq" :
152+
// command += IsRunningInCICD() ? "| sort | uniq" :
143153
// IsRunningInPowershell() ? "| Sort-Object -Unique" : "| sort | uniq";
144154
List<string> output = GitHelper(command);
145155
output.Sort();
146156
List<string> contributors = output.Distinct().ToList();
147157
contributors.Sort();
148158
Information($"Detected {contributors.Count} unique contributors:");
149-
Information(string.Join(Environment.NewLine, contributors));
159+
Information(string.Join(NL, contributors));
150160
// TODO Search example in bash: curl -L -H "X-GitHub-Api-Version: 2022-11-28" "https://api.github.com/search/users?q=Chris+Swinchatt"
151-
Information(Environment.NewLine + "Unicode test: 1) Raynald Messié; 2) 彭伟 pengweiqhca");
152-
AnsiConsole.Markup("Unicode test: 1) Raynald Messié; 2) 彭伟 pengweiqhca" + Environment.NewLine);
161+
Information(NL + "Unicode test: 1) Raynald Messié; 2) 彭伟 pengweiqhca");
162+
AnsiConsole.Markup("Unicode test: 1) Raynald Messié; 2) 彭伟 pengweiqhca" + NL);
153163
// Powershell life hack: $OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding
154164
// https://stackoverflow.com/questions/40098771/changing-powershells-default-output-encoding-to-utf-8
155165
// https://stackoverflow.com/questions/49476326/displaying-unicode-in-powershell/49481797#49481797
@@ -164,7 +174,7 @@ Task("CreateReleaseNotes")
164174
Information($"Generating release notes at {releaseNotesFile}");
165175
var lastReleaseTags = GitHelper("describe --tags --abbrev=0 --exclude net*");
166176
var lastRelease = lastReleaseTags.First(t => !t.StartsWith("net")); // skip 'net*-vX.Y.Z' tag and take 'major.minor.build'
167-
var releaseVersion = versioning.NuGetVersion;
177+
var releaseVersion = versioning.SemVer;
168178

169179
// Read main header from Git file, substitute version in header, and add content further...
170180
Information("{0} New release tag is " + releaseVersion);
@@ -209,7 +219,7 @@ Task("CreateReleaseNotes")
209219
{
210220
starring.Add(CreateStars(contributor.Commits, contributor.Author));
211221
}
212-
Information(string.Join(Environment.NewLine, starring));
222+
Information(string.Join(NL, starring));
213223

214224
var commitsGrouping = summary
215225
.GroupBy(x => x.Commits)
@@ -223,7 +233,7 @@ Task("CreateReleaseNotes")
223233
byInsertions: (log, group, fGroup, insGroup) => CreateStars(group.Commits, insGroup.Contributors.First().Contributor),
224234
byDeletions: (log, group, fGroup, insGroup, contributor) => CreateStars(group.Commits, contributor.Contributor));
225235
Information("------==< New Starring >==------");
226-
Information(string.Join(Environment.NewLine, starring));
236+
Information(string.Join(NL, starring));
227237

228238
// Honoring aka Top Contributors
229239
var coreTeamNames = new List<string> { "Raman Maksimchuk", "Raynald Messié", "Guillaume Gnaegi" }; // Ocelot Core team members should not be in Top 3 Chart
@@ -266,7 +276,7 @@ Task("CreateReleaseNotes")
266276
return HonorForDeletions(place, contributor.Contributor, group.Commits, contributor.Files, contributor.Insertions, contributor.Deletions);
267277
});
268278
Information("---==< TOP Contributors >==---");
269-
Information(string.Join(Environment.NewLine, topContributors));
279+
Information(string.Join(NL, topContributors));
270280

271281
// local helpers
272282
static string Place(int i) => ++i == 1 ? "1st" : i == 2 ? "2nd" : i == 3 ? "3rd" : $"{i}th";
@@ -436,18 +446,14 @@ private List<string> GitHelper(string command)
436446
private void WriteReleaseNotes()
437447
{
438448
Information($"RUN {nameof(WriteReleaseNotes)} ...");
439-
440449
EnsureDirectoryExists(packagesDir);
441450
System.IO.File.WriteAllLines(releaseNotesFile, releaseNotes, Encoding.UTF8);
442-
443451
var content = System.IO.File.ReadAllText(releaseNotesFile, Encoding.UTF8);
444452
if (string.IsNullOrEmpty(content))
445453
{
446454
System.IO.File.WriteAllText(releaseNotesFile, "No commits since last release");
447455
}
448-
449-
Information("Release notes are >>>\n{0}<<<", content);
450-
//Information($"EXITED {nameof(WriteReleaseNotes)}");
456+
Information("Release notes are >>>{0}<<<", NL + content);
451457
}
452458

453459
Task("RunUnitTests")
@@ -465,7 +471,7 @@ Task("RunUnitTests")
465471
.Append("--verbosity:detailed")
466472
.Append("--consoleLoggerParameters:ErrorsOnly")
467473
};
468-
if (target != Release)
474+
if (target == PullRequest)
469475
{
470476
settings.Framework = LatestFramework; // .NET 9 SDK only
471477
}
@@ -482,7 +488,7 @@ Task("RunUnitTests")
482488

483489
GenerateReport(coverageSummaryFile);
484490

485-
if (IsRunningOnCircleCI() && IsMainOrDevelop())
491+
if (IsRunningInCICD() && IsMainOrDevelop())
486492
{
487493
var repoToken = EnvironmentVariable(coverallsRepoToken);
488494
if (string.IsNullOrEmpty(repoToken))
@@ -512,9 +518,9 @@ Task("RunUnitTests")
512518

513519
Information("Sequence Coverage: " + sequenceCoverage);
514520

515-
if(double.Parse(sequenceCoverage) < minCodeCoverage)
521+
if (double.Parse(sequenceCoverage) < minCodeCoverage)
516522
{
517-
var whereToCheck = !IsRunningOnCircleCI() ? coverallsRepo : artifactsForUnitTestsDir;
523+
var whereToCheck = !IsRunningInCICD() ? coverallsRepo : artifactsForUnitTestsDir;
518524
throw new Exception(string.Format("Code coverage fell below the threshold of {0}%. You can find the code coverage report at {1}", minCodeCoverage, whereToCheck));
519525
};
520526
});
@@ -530,7 +536,7 @@ Task("RunAcceptanceTests")
530536
.Append("--no-restore")
531537
.Append("--no-build")
532538
};
533-
if (target != Release)
539+
if (target == PullRequest)
534540
{
535541
settings.Framework = LatestFramework; // .NET 9 SDK only
536542
}
@@ -551,7 +557,7 @@ Task("RunIntegrationTests")
551557
.Append("--no-restore")
552558
.Append("--no-build")
553559
};
554-
if (target != Release)
560+
if (target == PullRequest)
555561
{
556562
settings.Framework = LatestFramework; // .NET 9 SDK only
557563
}
@@ -602,7 +608,7 @@ Task("PublishGitHubRelease")
602608
.IsDependentOn("CreateArtifacts")
603609
.Does(() =>
604610
{
605-
if (!IsRunningOnCircleCI()) return;
611+
if (!IsRunningInCICD()) return;
606612

607613
dynamic release = CreateGitHubRelease();
608614
var path = packagesDir.ToString() + @"/**/*";
@@ -619,9 +625,9 @@ Task("EnsureStableReleaseRequirements")
619625
{
620626
Information("Check if stable release...");
621627

622-
if (!IsRunningOnCircleCI())
628+
if (!IsRunningInCICD())
623629
{
624-
throw new Exception("Stable release should happen via circleci");
630+
throw new Exception("Stable release should happen via CI/CD");
625631
}
626632

627633
Information("Release is stable...");
@@ -636,7 +642,7 @@ Task("DownloadGitHubReleaseArtifacts")
636642
System.Threading.Thread.Sleep(5000);
637643
EnsureDirectoryExists(packagesDir);
638644

639-
var releaseUrl = "https://api.github.com/repos/ThreeMammals/ocelot/releases/tags/" + versioning.NuGetVersion;
645+
var releaseUrl = "https://api.github.com/repos/ThreeMammals/ocelot/releases/tags/" + versioning.SemVer;
640646
var releaseInfo = await GetResourceAsync(releaseUrl);
641647
var assets_url = Newtonsoft.Json.Linq.JObject.Parse(releaseInfo)
642648
.Value<string>("assets_url");
@@ -665,7 +671,7 @@ Task("PublishToNuget")
665671
return;
666672
}
667673

668-
if (IsRunningOnCircleCI())
674+
if (IsRunningInCICD())
669675
{
670676
// stable releases
671677
var nugetFeedStableKey = EnvironmentVariable("OCELOT_NUGET_API_KEY_3Mammals");
@@ -762,7 +768,7 @@ private void SetupGitHubClient(System.Net.Http.HttpClient client)
762768

763769
private dynamic CreateGitHubRelease()
764770
{
765-
var json = $"{{ \"tag_name\": \"{versioning.NuGetVersion}\", \"target_commitish\": \"main\", \"name\": \"{versioning.NuGetVersion}\", \"body\": \"{ReleaseNotesAsJson()}\", \"draft\": true, \"prerelease\": true, \"generate_release_notes\": false }}";
771+
var json = $"{{ \"tag_name\": \"{versioning.SemVer}\", \"target_commitish\": \"main\", \"name\": \"{versioning.SemVer}\", \"body\": \"{ReleaseNotesAsJson()}\", \"draft\": true, \"prerelease\": true, \"generate_release_notes\": false }}";
766772
var content = new System.Net.Http.StringContent(json, System.Text.Encoding.UTF8, "application/json");
767773

768774
using (var client = new System.Net.Http.HttpClient())
@@ -816,7 +822,7 @@ private void CompleteGitHubRelease(dynamic release)
816822
{
817823
int releaseId = release.id;
818824
string url = release.url.ToString();
819-
var json = $"{{ \"tag_name\": \"{versioning.NuGetVersion}\", \"target_commitish\": \"main\", \"name\": \"{versioning.NuGetVersion}\", \"body\": \"{ReleaseNotesAsJson()}\", \"draft\": false, \"prerelease\": false }}";
825+
var json = $"{{ \"tag_name\": \"{versioning.SemVer}\", \"target_commitish\": \"main\", \"name\": \"{versioning.SemVer}\", \"body\": \"{ReleaseNotesAsJson()}\", \"draft\": false, \"prerelease\": false }}";
820826
var request = new System.Net.Http.HttpRequestMessage(new System.Net.Http.HttpMethod("Patch"), url); // $"https://api.github.com/repos/ThreeMammals/Ocelot/releases/{releaseId}");
821827
request.Content = new System.Net.Http.StringContent(json, System.Text.Encoding.UTF8, "application/json");
822828

@@ -846,7 +852,7 @@ private async Task<string> GetResourceAsync(string url)
846852
using var response = await client.GetAsync(url);
847853
response.EnsureSuccessStatusCode();
848854
var content = await response.Content.ReadAsStringAsync();
849-
Information("Response is >>>" + Environment.NewLine + content + Environment.NewLine + "<<<");
855+
Information("Response is >>>" + NL + content + NL + "<<<");
850856
return content;
851857
}
852858
catch(Exception exception)
@@ -856,14 +862,34 @@ private async Task<string> GetResourceAsync(string url)
856862
}
857863
}
858864

865+
private bool IsRunningInCICD()
866+
=> IsRunningOnCircleCI() || IsRunningInGitHubActions();
859867
private bool IsRunningOnCircleCI()
860-
{
861-
return !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CIRCLECI"));
862-
}
868+
=> !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CIRCLECI"));
869+
private bool IsRunningInGitHubActions()
870+
=> Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true";
863871

864872
private bool IsMainOrDevelop()
865873
{
866-
var env = Environment.GetEnvironmentVariable("CIRCLE_BRANCH").ToLower();
867-
868-
return env == "main" || env == "develop";
874+
var br = GetBranchName().ToLower();
875+
return br == "main" || br == "develop";
876+
}
877+
private string GetBranchName()
878+
{
879+
if (IsRunningOnCircleCI())
880+
{
881+
return Environment.GetEnvironmentVariable("CIRCLE_BRANCH");
882+
}
883+
else if (IsRunningInGitHubActions())
884+
{
885+
return GetGitHubBranchName();
886+
}
887+
return versioning.BranchName;
888+
}
889+
private string GetGitHubBranchName()
890+
{
891+
string githubRef = Environment.GetEnvironmentVariable("GITHUB_REF");
892+
return (!string.IsNullOrEmpty(githubRef) && githubRef.StartsWith("refs/heads/"))
893+
? githubRef.Substring("refs/heads/".Length)
894+
: "Unknown Branch";
869895
}

0 commit comments

Comments
 (0)