Files
Febe/tests/Febe.Tests/Packaging/PipelineTests.cs
T
Alby96andClaude Opus 5.5 2144f755dc CI: l'immagine di main si pubblica solo dopo l'installatore
Il lavoro immagine dipendeva solo da prove: :main e :sha- uscivano anche con l'installatore rosso o non ancora finito,
mentre docs/docker.md dice che :main è l'ultimo commit di main che ha passato la verifica. Ora needs: [prove,
installatore]; sull'unico runner i lavori vanno comunque uno alla volta, quindi la durata non cambia. Rilievo
main-senza-installatore della revisione.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:04:55 +02:00

488 lines
27 KiB
C#

using System.Diagnostics;
using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Packaging;
/// <summary>
/// The CI of the repository (.gitea/workflows/verifica.yml, pulizia.yml and the scripts of .gitea/scripts), read as
/// text: the rules that must survive later edits. Every push of every branch is verified and nothing else triggers
/// it twice; the tests run only through tests/Febe.Tests, with the browser, and again with the seed of the run; the
/// image is published only from main and never as :latest; credentials are never printed; the external tools are
/// pinned and checked; the cleanup touches only what the CI of Febe made, never a real Febe on the same daemon; the
/// tried container never has a network.
/// </summary>
[TestClass]
public sealed partial class PipelineTests
{
private static readonly string[] Jobs = ["controlli", "prove", "installatore", "immagine"];
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void EveryPushOfEveryBranchIsVerifiedOnceAndTagsAreLeftToTheRelease()
{
var workflow = Workflow("verifica.yml");
StringAssert.Contains(workflow, "on:\n push:\n branches: [\"**\"]\n workflow_dispatch:");
var code = Code(workflow);
Assert.DoesNotContain("pull_request", code, "a PR shows the status of its head commit, already verified by the push");
Assert.DoesNotContain("tags:", code, "tags belong to rilascio.yml");
StringAssert.Contains(code, "cancel-in-progress: ${{ gitea.ref != 'refs/heads/main' }}", "every merge into main runs to the end");
// A run started by hand never cancels the run of a push: only that one writes the statuses a merge needs.
StringAssert.Contains(code, "group: verifica-${{ gitea.event_name }}-${{ gitea.ref }}");
}
[TestMethod]
public void TheJobsFollowOneAnotherAndEachHasATimeout()
{
var workflow = Workflow("verifica.yml");
foreach (var job in Jobs)
{
StringAssert.Contains(Job(workflow, job), "timeout-minutes:", job);
}
StringAssert.Contains(Job(workflow, "prove"), "needs: controlli");
StringAssert.Contains(Job(workflow, "installatore"), "needs: prove");
StringAssert.Contains(Job(workflow, "immagine"), "needs: [prove, installatore]", ":main comes only from a commit whose whole verification is green");
foreach (var other in new[] { "rilascio.yml", "pulizia.yml" })
{
var text = Workflow(other);
foreach (Match job in JobHeader().Matches(text))
{
StringAssert.Contains(Job(text, job.Groups["name"].Value), "timeout-minutes:", $"{other}: {job.Groups["name"].Value}");
}
}
}
[TestMethod]
public void TheWholeSolutionIsBuiltAndTheTestsRunOnlyThroughTheTestProjectWithTheBrowser()
{
var prove = Job(Workflow("verifica.yml"), "prove");
StringAssert.Contains(prove, "container:\n image: node:24-trixie", "Debian: Chromium is a real package there, a snap on Ubuntu");
StringAssert.Contains(prove, "bash .gitea/scripts/ambiente-prove.sh");
StringAssert.Contains(prove, "dotnet build Febe.slnx -c Release -nologo -warnaserror");
StringAssert.Contains(prove, "bash .gitea/scripts/riepilogo-prove.sh out/prove 0", "no test may skip itself in the CI");
// The second pass: the tests of the synthetic world again, with the seed of the run in the variable the helper reads.
StringAssert.Contains(prove, $"{SyntheticSite.Variable}: ${{{{ steps.semi.outputs.seme }}}}");
StringAssert.Contains(prove, $"--filter \"TestCategory={SyntheticSite.Category}\"");
var environment = Script("ambiente-prove.sh");
foreach (var package in new[] { "chromium", "xvfb", "ffmpeg", "nsis", "locales" })
{
StringAssert.Contains(environment, package);
}
// tests/Febe.Tests.Windows runs only on Windows: never «dotnet test» on the solution or without a project.
foreach (var name in new[] { "verifica.yml", "rilascio.yml" })
{
foreach (Match test in DotnetTest().Matches(Code(Workflow(name))))
{
Assert.AreEqual("tests/Febe.Tests", test.Groups["target"].Value, $"{name}: {test.Value}");
}
}
}
[TestMethod]
public void TheImageIsPublishedOnlyAfterAPushToMainAsMainAndShaNeverAsLatest()
{
var image = Job(Workflow("verifica.yml"), "immagine");
var decision = Step(image, "Pubblicare?");
StringAssert.Contains(decision, "[ \"$EVENTO\" != push ] || [ \"$RIFERIMENTO\" != refs/heads/main ]");
StringAssert.Contains(decision, "::warning::Manca il segreto REGISTRY_TOKEN");
Assert.DoesNotContain("exit 1", decision, "without the secret the job stays green");
var publish = Step(image, "Pubblicazione come :main e :sha-<commit>");
StringAssert.Contains(publish, "if: steps.segreto.outputs.presente == 'si'");
StringAssert.Contains(publish, "\"$IMAGE:sha-${GITHUB_SHA::7}\"");
StringAssert.Contains(publish, "\"$IMAGE:main\"");
StringAssert.Contains(publish, "bash .gitea/scripts/costruisci-immagine.sh pubblica");
StringAssert.Contains(publish, "| cut -f1) || CIMA=\"\"", "under bash -e an unreadable main must reach the warning and still publish :sha-");
Assert.DoesNotContain(":latest", Code(Workflow("verifica.yml")), ":latest belongs to the release");
// Built with buildx, tried without a network and scanned before anything is published; always cleaned up.
StringAssert.Contains(image, "uses: docker/setup-buildx-action@v3");
StringAssert.Contains(image, "http = true");
StringAssert.Contains(image, "insecure = true");
var decide = image.IndexOf("- name: Pubblicare?", StringComparison.Ordinal);
foreach (var gate in new[] { "bash .gitea/scripts/costruisci-immagine.sh archivio", "bash .gitea/scripts/prova-immagine.sh", "bash .gitea/scripts/scansione-immagine.sh" })
{
var at = image.IndexOf(gate, StringComparison.Ordinal);
Assert.IsTrue(at >= 0 && at < decide, $"«{gate}» comes before the publication");
}
var cleanup = Step(image, "Pulizia (sempre)");
StringAssert.Contains(cleanup, "if: always()");
StringAssert.Contains(cleanup, "bash .gitea/scripts/pulizia-docker.sh esecuzione \"$ESECUZIONE\"");
StringAssert.Contains(cleanup, ".auths |= del(.[$r])", "the credentials leave the client configuration");
}
[TestMethod]
public void SecretsAreNeverPrintedNorTheDaemonUsedForTheRegistry()
{
foreach (var (name, text) in AllCiFiles())
{
var code = Code(text);
Assert.DoesNotContain("docker login", code, name);
Assert.DoesNotContain("docker push", code, name);
Assert.IsFalse(Trace().IsMatch(code), $"{name}: no shell tracing (it would print secrets)");
// A secret goes into echo or printf only to be piped or redirected, never to the log.
foreach (var line in code.Split('\n').Where(l => Printing().IsMatch(l)))
{
var secret = SecretReference().Match(line);
if (secret.Success)
{
var after = line[secret.Index..];
Assert.IsTrue(after.Contains('|', StringComparison.Ordinal) || after.Contains('>', StringComparison.Ordinal), $"{name}: «{line.Trim()}» would print a secret");
}
}
}
}
[TestMethod]
public void TheExternalToolsArePinnedAndCheckedAndNoThirdPartyActionRunsThem()
{
var tool = Script("strumento.sh");
StringAssert.Contains(tool, "versione=\"8.30.1\"");
StringAssert.Contains(tool, "versione=\"0.75.0\"");
Assert.HasCount(2, Sha256().Matches(tool), "one SHA-256 per tool");
StringAssert.Contains(tool, "sha256sum -c");
Assert.DoesNotContain("latest", Code(tool));
foreach (var (name, text) in AllCiFiles())
{
Assert.DoesNotContain("trivy-action", Code(text), name);
Assert.DoesNotContain("gitleaks-action", Code(text), name);
}
var secrets = Script("segreti.sh");
StringAssert.Contains(secrets, "--redact");
StringAssert.Contains(Job(Workflow("verifica.yml"), "controlli"), "fetch-depth: 0");
var scan = Script("scansione-immagine.sh");
StringAssert.Contains(scan, "--severity CRITICAL --ignore-unfixed");
StringAssert.Contains(scan, "--exit-code 1");
}
[TestMethod]
public void TheCleanupTouchesOnlyWhatTheCiOfFebeMade()
{
var cleanup = Code(Script("pulizia-docker.sh"));
foreach (var forbidden in new[] { "system prune", "builder prune", "volume prune", "container prune", "image prune -a", "prune --all", "image prune -f -a" })
{
Assert.DoesNotContain(forbidden, cleanup, "the daemon is shared with Alberto's other projects");
}
Assert.HasCount(1, ImagePrune().Matches(cleanup), "only dangling images, older than three days");
StringAssert.Contains(cleanup, "docker image prune -f --filter \"until=72h\"");
StringAssert.Contains(cleanup, "^buildx_buildkit_(febe-ci-[0-9]+)0$");
// The febe.ci.* labels of the image are in every container made from a published image, a real Febe too: they
// never choose what goes. Containers are chosen by febe.ci.prova (and their exact name), the builders by name,
// and an image only by its local name febe-ci:<run>, never by id and never forced.
Assert.IsFalse(ProvenanceLabelFilter().IsMatch(cleanup), "the cleanup filters on febe.ci.prova only");
foreach (var line in cleanup.Split('\n').Where(l => l.Contains("docker ps", StringComparison.Ordinal)))
{
Assert.IsTrue(
line.Contains("--filter \"label=febe.ci.prova", StringComparison.Ordinal) || line.Contains("--filter \"name=buildx_buildkit_febe-ci-\"", StringComparison.Ordinal) || line.Contains("--filter \"ancestor=", StringComparison.Ordinal),
$"«{line.Trim()}» lists containers without the mark of the tried container");
}
StringAssert.Contains(cleanup, "\"febe-prova-$valore\"", "the name must match the mark");
StringAssert.Contains(cleanup, "contenitori_di_prova \"\" exited created dead", "the sweeps take only stopped tried containers");
Assert.IsFalse(ForcedImageRemoval().IsMatch(cleanup), "an image is never removed by force");
StringAssert.Contains(cleanup, "[[ \"$riferimento\" =~ ^febe-ci:[0-9]+$ ]]");
var weekly = Workflow("pulizia.yml");
StringAssert.Contains(weekly, "schedule:");
StringAssert.Contains(weekly, "workflow_dispatch:");
StringAssert.Contains(weekly, "bash .gitea/scripts/pulizia-docker.sh settimanale");
}
[TestMethod]
public void TheTriedContainerNeverHasANetworkAndAlwaysCarriesTheMarkNoImageHas()
{
var smoke = Code(Script("prova-immagine.sh"));
var runs = DockerRun().Matches(smoke);
Assert.IsGreaterThanOrEqualTo(4, runs.Count);
foreach (Match run in runs)
{
StringAssert.Contains(run.Value, "--network none", "rule 1: the image under test cannot reach any site");
StringAssert.Contains(run.Value, "\"${etichette[@]}\"", "every tried container carries the mark the cleanup looks for");
}
StringAssert.Contains(smoke, "etichette=(--label \"febe.ci.prova=$esecuzione\")");
StringAssert.Contains(smoke, "nome=\"febe-prova-$esecuzione\"");
// Docker copies the labels of an image into every container made from it: the mark must never be in an image.
Assert.DoesNotContain("febe.ci.prova", Code(Script("costruisci-immagine.sh")));
Assert.DoesNotContain("febe.ci.prova", Code(Read(Repository.PathOf("docker", "Dockerfile"))));
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task OnADaemonSharedWithARealFebeTheCleanupTakesOnlyWhatTheCiMade()
{
var script = CiPath("scripts", "pulizia-docker.sh");
var bash = BashForScripts();
if (bash is null)
{
Assert.Inconclusive("Manca bash (su Windows serve Git Bash): la prova della pulizia su un demone finto si salta.");
}
Assert.IsTrue(File.Exists(script));
// At the start or the end of a run (a release run again keeps its id, so the published image has the same
// febe.ci.run as the run): only the tried container, the local name and the builder of that run.
var run = await RunCleanupAsync(bash, FakeDaemon.Full, "esecuzione", "777");
Assert.AreEqual(0, run.Code, run.Report);
Assert.DoesNotContain("::warning::", run.Output, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-777", "b-777"]).ToList(), run.Containers, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777(), run.Images, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-7770_state"]).ToList(), run.Volumes, run.Report);
// Leftovers of interrupted runs: stopped tried containers, febe-ci images and builders older than 90 minutes.
var leftovers = await RunCleanupAsync(bash, FakeDaemon.Full, "residui", "90");
Assert.AreEqual(0, leftovers.Code, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-555", "b-vecchio"]).ToList(), leftovers.Containers, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555"), leftovers.Images, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-4560_state"]).ToList(), leftovers.Volumes, leftovers.Report);
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore di prova febe-prova-556 è acceso", "a running tried container is reported, not removed");
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore buildx_buildkit_febe-ci-4570 non è un builder buildx", leftovers.Report);
// Every week, on a daemon without anything odd: the same, the old febe:ci and the dangling images older than
// 72 hours that no container uses. Green.
var weekly = await RunCleanupAsync(bash, FakeDaemon.Clean, "settimanale");
Assert.AreEqual(0, weekly.Code, weekly.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Clean).Except(["c-prova-555", "b-vecchio"]).ToList(), weekly.Containers, weekly.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555", "img-ci556", "img-legacy", "img-penzolante-vecchia"), weekly.Images, weekly.Report);
// With something left for a person to look at, the weekly cleanup goes red.
var noticed = await RunCleanupAsync(bash, FakeDaemon.Full, "settimanale");
Assert.AreEqual(1, noticed.Code, noticed.Report);
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
CollectionAssert.Contains(noticed.Containers, "c-febe-vero");
}
/// <summary>
/// The daemon the cleanup runs against in <see cref="OnADaemonSharedWithARealFebeTheCleanupTakesOnlyWhatTheCiMade"/>
/// (format in fake-docker.sh). A real Febe started from :latest and one from :main carry the febe.ci.* labels of
/// their images, as Docker gives them; the image of the release also has the local name of run 777.
/// </summary>
private static class FakeDaemon
{
public static readonly string[] Full =
[
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0",
"c-febe-fermo|febe-main|exited|43200|192.168.30.23:3000/alby96/febe:main|img-main|febe.ci.workflow=verifica,febe.ci.run=888",
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
"c-prova-777|febe-prova-777|running|5|febe-ci:777|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.prova=777",
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
"c-prova-556|febe-prova-556|running|300|febe-ci:556|img-ci556|febe.ci.run=556,febe.ci.prova=556",
"c-prova-557|febe-prova-557|exited|10|febe-ci:557|img-ci557|febe.ci.run=557,febe.ci.prova=557",
"c-nome-strano|febe-prova-558-bis|exited|300|encelado:latest|img-encelado|febe.ci.prova=558",
"c-segno-diverso|febe-prova-559|exited|300|encelado:latest|img-encelado|febe.ci.prova=560",
"c-senza-segno|febe-prova-561|exited|300|encelado:latest|img-encelado|",
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|",
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-finto|buildx_buildkit_febe-ci-4570|running|300|encelado:latest|img-encelado|",
"b-giovane|buildx_buildkit_febe-ci-7890|running|10|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-altro|altro_buildx_buildkit_febe-ci-10|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-777|buildx_buildkit_febe-ci-7770|running|20|moby/buildkit:buildx-stable-1|img-buildkit|",
];
/// <summary>The same daemon without the running tried container and the builder that is not one.</summary>
public static readonly string[] Clean = [.. Full.Where(c => !c.StartsWith("c-prova-556|", StringComparison.Ordinal) && !c.StartsWith("b-finto|", StringComparison.Ordinal))];
public static readonly string[] Images =
[
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0,febe-ci:777|43200|febe.ci.run=777",
"img-main|192.168.30.23:3000/alby96/febe:main|43200|febe.ci.run=888",
"img-ci555|febe-ci:555|300|febe.ci.run=555",
"img-ci556|febe-ci:556|300|febe.ci.run=556",
"img-ci557|febe-ci:557|10|febe.ci.run=557",
"img-penzolante-febe||300|febe.ci.run=999",
"img-penzolante-vecchia||6000|",
"img-penzolante-in-uso||20000|febe.ci.run=111",
"img-encelado|encelado:latest|5000|",
"img-buildkit|moby/buildkit:buildx-stable-1|50000|",
"img-legacy|febe:ci|6000|",
];
public static readonly string[] Volumes =
[
"buildx_buildkit_febe-ci-4560_state",
"buildx_buildkit_febe-ci-4570_state",
"buildx_buildkit_febe-ci-7890_state",
"buildx_buildkit_febe-ci-7770_state",
"encelado-dati",
];
public static List<string> ContainersOf(string[] world) => [.. world.Select(c => c[..c.IndexOf('|', StringComparison.Ordinal)])];
/// <summary>
/// «id|names» of each image once febe-ci:777 is gone (the image of the release keeps its registry names), without
/// the images given.
/// </summary>
public static List<string> ImagesWithout777(params string[] gone) =>
[
.. Images
.Select(i => string.Join('|', i.Split('|')[..2]).Replace(",febe-ci:777", string.Empty, StringComparison.Ordinal))
.Where(i => !gone.Contains(i[..i.IndexOf('|', StringComparison.Ordinal)])),
];
}
private sealed record CleanupRun(int Code, string Output, string Errors, List<string> Containers, List<string> Images, List<string> Volumes)
{
public string Report => $"codice {Code}\n{Output}\n{Errors}";
}
/// <summary>
/// pulizia-docker.sh against the fake daemon. DOCKER_HOST points nowhere: even if a real docker client came first on
/// the PATH it could not reach a daemon, and the test fails because the fake recorded no call.
/// </summary>
private async Task<CleanupRun> RunCleanupAsync(string bash, string[] containers, params string[] arguments)
{
using var world = new TempFolder("febe-pulizia");
var bin = world.Combine("bin");
Directory.CreateDirectory(bin);
var docker = Path.Combine(bin, "docker");
File.Copy(Repository.PathOf("tests", "Febe.Tests", "Packaging", "fake-docker.sh"), docker);
if (!OperatingSystem.IsWindows())
{
File.SetUnixFileMode(docker, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
await WriteLinesAsync(world.Combine("containers"), containers);
await WriteLinesAsync(world.Combine("images"), FakeDaemon.Images);
await WriteLinesAsync(world.Combine("volumes"), FakeDaemon.Volumes);
var start = new ProcessStartInfo(bash)
{
WorkingDirectory = Repository.Root()!,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardOutputEncoding = System.Text.Encoding.UTF8,
StandardErrorEncoding = System.Text.Encoding.UTF8,
};
start.ArgumentList.Add(".gitea/scripts/pulizia-docker.sh");
foreach (var argument in arguments)
{
start.ArgumentList.Add(argument);
}
start.Environment["PATH"] = bin + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH");
start.Environment["FAKE_DOCKER_WORLD"] = world.Path.Replace('\\', '/');
start.Environment["DOCKER_HOST"] = OperatingSystem.IsWindows() ? "npipe:////./pipe/febe-nessun-demone" : "unix:///nonexistent/febe-nessun-demone.sock";
start.Environment.Remove("DOCKER_CONTEXT");
using var process = Process.Start(start)!;
var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
await process.WaitForExitAsync(TestContext.CancellationToken);
var result = new CleanupRun(
process.ExitCode,
(await output).Replace("\r\n", "\n", StringComparison.Ordinal),
await errors,
FakeDaemon.ContainersOf([.. await ReadLinesAsync(world.Combine("containers"))]),
[.. (await ReadLinesAsync(world.Combine("images"))).Select(i => string.Join('|', i.Split('|')[..2]))],
await ReadLinesAsync(world.Combine("volumes")));
var calls = world.Combine("calls");
Assert.IsTrue(File.Exists(calls) && (await File.ReadAllTextAsync(calls, TestContext.CancellationToken)).Contains("docker ps", StringComparison.Ordinal), $"the fake docker client was not the one called\n{result.Report}");
Assert.DoesNotContain("unexpected call", result.Errors, result.Report);
return result;
}
private async Task WriteLinesAsync(string path, IEnumerable<string> lines) =>
await File.WriteAllTextAsync(path, string.Concat(lines.Select(line => line + "\n")), TestContext.CancellationToken);
private async Task<List<string>> ReadLinesAsync(string path) =>
[.. (await File.ReadAllTextAsync(path, TestContext.CancellationToken)).Split('\n', StringSplitOptions.RemoveEmptyEntries)];
/// <summary>bash for the scripts of the CI: the system one on Linux, Git Bash on Windows (not the one of WSL).</summary>
private static string? BashForScripts()
{
if (OperatingSystem.IsWindows())
{
var git = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Git", "bin", "bash.exe");
return File.Exists(git) ? git : null;
}
return new[] { "/bin/bash", "/usr/bin/bash" }.FirstOrDefault(File.Exists);
}
/// <summary>The workflows and the scripts of the CI, by name.</summary>
private static List<(string Name, string Text)> AllCiFiles() =>
[.. Directory.EnumerateFiles(CiPath("workflows")).Concat(Directory.EnumerateFiles(CiPath("scripts")))
.Select(file => (Path.GetFileName(file), Read(file)))];
private static string Workflow(string name) => Read(CiPath("workflows", name));
private static string Script(string name) => Read(CiPath("scripts", name));
private static string Read(string path) => File.ReadAllText(path).Replace("\r\n", "\n", StringComparison.Ordinal);
/// <summary>A path under .gitea; inconclusive in the build of the image, whose context leaves .gitea out.</summary>
private static string CiPath(params string[] parts)
{
var path = Repository.PathOf([".gitea", .. parts]);
var root = Repository.Root()!;
if (!File.Exists(path) && !Directory.Exists(path) && !Directory.Exists(Path.Combine(root, ".git")) && !File.Exists(Path.Combine(root, ".git")))
{
Assert.Inconclusive("Questa copia del repository non ha .gitea/ (costruzione dell'immagine Docker).");
}
return path;
}
/// <summary>The text without comment lines (YAML and shell): what runs, not what the comments say.</summary>
private static string Code(string text) =>
string.Join('\n', text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n').Where(line => !line.TrimStart().StartsWith('#')));
/// <summary>The block of a job: from « name:» to the next job.</summary>
private static string Job(string workflow, string name)
{
var match = Regex.Match(workflow, $@"^ {Regex.Escape(name)}:\n(?<body>(?:(?: .*|\s*)\n)*)", RegexOptions.Multiline);
Assert.IsTrue(match.Success, $"manca il lavoro {name}");
return match.Groups["body"].Value;
}
/// <summary>The block of a step, from its «- name:» to the next step.</summary>
private static string Step(string job, string name)
{
var start = job.IndexOf("- name: " + name, StringComparison.Ordinal);
Assert.IsGreaterThanOrEqualTo(0, start, $"manca il passo «{name}»");
var next = job.IndexOf("\n - ", start + 1, StringComparison.Ordinal);
return next < 0 ? job[start..] : job[start..next];
}
[GeneratedRegex(@"(?<=^jobs:\n(?:.*\n)*?)^ (?<name>[a-z][\w-]*):$", RegexOptions.Multiline)]
private static partial Regex JobHeader();
[GeneratedRegex(@"dotnet test(?:\s+(?<target>[^\s-][^\s]*))?")]
private static partial Regex DotnetTest();
[GeneratedRegex(@"(?m)^\s*set\s+-[a-wyz]*x|\bbash\s+-x\b")]
private static partial Regex Trace();
[GeneratedRegex(@"\b(?:echo|printf)\b")]
private static partial Regex Printing();
[GeneratedRegex(@"\$\{?(?:TOKEN|FEBE_PASSWORD|AUTH|REGISTRY_TOKEN|PASSWORD)\b")]
private static partial Regex SecretReference();
[GeneratedRegex(@"\b[0-9a-f]{64}\b")]
private static partial Regex Sha256();
[GeneratedRegex(@"docker (?:image|container|volume|builder|system) prune")]
private static partial Regex ImagePrune();
[GeneratedRegex(@"docker run\b(?:[^\n]*\\\n)*[^\n]*")]
private static partial Regex DockerRun();
[GeneratedRegex(@"label=febe\.ci\.(?!prova\b)")]
private static partial Regex ProvenanceLabelFilter();
[GeneratedRegex(@"docker (?:image rm|rmi)\s+(?:-\w+\s+)*-\w*f")]
private static partial Regex ForcedImageRemoval();
}