Files
Febe/tests/Febe.Tests/Packaging/PipelineTests.Comandi.cs
T
Alby96andClaude Opus 5.5 a4ad8a8bc4 CI senza azioni e senza Node, solo comandi scritti in casa (C6, 3/4)
Per la decisione di Alberto del 18 novembre 2026 (niente componenti esterni) i flussi
di verifica, rilascio e pulizia non usano più azioni JavaScript, che vogliono Node:

- sorgenti con git init/fetch e il gettone del lavoro, passato a git solo
  nell'ambiente del passo, mai scritto nella configurazione;
- SDK .NET con .gitea/scripts/dotnet.sh, dai metadati di Microsoft e verificato
  con lo SHA-512 prima di installarlo nella cache degli strumenti del runner;
- builder buildx creato da costruisci-immagine.sh builder;
- artefatti nel pacchetto generico febe-ci del registro di Gitea (artefatti.sh,
  con REGISTRY_TOKEN), tolti dalla pulizia del lunedì dopo 14 giorni; la release
  ricostruisce installatore e zip invece di riceverli da un altro lavoro;
- JSON letto con un lettore in awk POSIX (json.awk) per i controlli e per la
  scelta delle versioni del registro, al posto di versioni-registro.js;
- contenitore delle prove debian:trixie al posto di node:24-trixie;
- la prova della pagina di accesso gira in Chromium invece che in Node.

controlli.sh rifiuta ora un flusso con uses:, tabulazioni o rientri dispari, e le
prove nuove controllano l'assenza di Node, il passo dei sorgenti uguale in ogni
lavoro, l'SDK prima di ogni dotnet, la scelta dell'SDK, il caricamento degli
artefatti con un curl finto e la scadenza dei vecchi. Nessuna esecuzione vera di
Gitea Actions: ciò che resta da vedere è in docs/processo.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:41:49 +01:00

333 lines
19 KiB
C#

using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Packaging;
/// <summary>
/// The CI is made only of commands (decision of 18 November 2026): no action (the JavaScript ones want Node) and no
/// Node anywhere. Every job fetches its sources with git and the token of the job, installs the .NET SDK with
/// .gitea/scripts/dotnet.sh (checked against Microsoft's SHA-512) before any dotnet, and keeps its artifacts in the
/// generic package febe-ci; the quick checks read the workflows and the JSON files with awk. The scripts run here against
/// files of the test and a fake curl, never against the network.
/// </summary>
public sealed partial class PipelineTests
{
private static readonly string[] Workflows = ["verifica.yml", "rilascio.yml", "pulizia.yml"];
[TestMethod]
public void NoActionAndNoNodeRunInTheCi()
{
foreach (var name in Workflows)
{
var code = Code(Workflow(name));
Assert.IsFalse(UsesLine().IsMatch(code), $"{name}: «uses:» calls an action; the CI is made of commands");
Assert.IsFalse(Regex.IsMatch(code, @"image:\s*node\b"), $"{name}: no container with Node");
}
foreach (var (name, text) in AllCiFiles())
{
foreach (var line in Code(text).Split('\n'))
{
Assert.IsFalse(NodeCommand().IsMatch(line) && !line.Contains("command -v node", StringComparison.Ordinal), $"{name}: «{line.Trim()}» runs Node");
}
}
foreach (var file in Directory.EnumerateFiles(CiPath(), "*", SearchOption.AllDirectories))
{
Assert.IsFalse(Regex.IsMatch(file, @"\.(?:js|mjs|cjs|ts)$"), $"{file}: no JavaScript in the CI");
}
// The container of the tests has no Node, and says so if an image ever brings it.
StringAssert.Contains(Script("ambiente-prove.sh"), "if command -v node > /dev/null; then");
}
[TestMethod]
public void EveryJobFetchesItsSourcesWithGitAndTheTokenOfTheJob()
{
var model = Normalized(Step(Job(Workflow("verifica.yml"), "controlli"), "Sorgenti"));
StringAssert.Contains(model, "TOKEN: ${{ gitea.token }}");
StringAssert.Contains(model, "export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0");
StringAssert.Contains(model, "git checkout -q --force --detach \"$GITHUB_SHA\"");
// The token lives only in the environment of git for that step: never in a configuration file of the repository.
Assert.DoesNotContain("credential", model);
Assert.IsFalse(Regex.IsMatch(model, @"git config[^\n]*(?:extraheader|http\.)", RegexOptions.IgnoreCase), "the header is never written to .git/config");
foreach (var name in Workflows)
{
var text = Workflow(name);
foreach (Match header in JobHeader().Matches(text))
{
var job = Job(text, header.Groups["name"].Value);
var steps = StepName().Matches(job).Select(m => m.Groups["name"].Value).ToList();
var where = $"{name}: {header.Groups["name"].Value}";
// First, or right after the step that brings git into the bare Debian container of the tests.
var first = steps.FirstOrDefault() == "Git e curl per i sorgenti" ? 1 : 0;
Assert.IsGreaterThan(first, steps.Count, where);
Assert.AreEqual("Sorgenti", steps[first], $"{where}: the sources come first");
Assert.AreEqual(model, Normalized(Step(job, "Sorgenti")), $"{where}: the same step as everywhere else");
}
}
static string Normalized(string step) => Regex.Replace(Code(step).TrimEnd(), "PROFONDITA: \"[0-9]+\"", "PROFONDITA: …");
}
[TestMethod]
public void TheSdkIsInstalledAndCheckedBeforeAnyDotnet()
{
foreach (var name in Workflows)
{
var text = Workflow(name);
foreach (Match header in JobHeader().Matches(text))
{
var job = Code(Job(text, header.Groups["name"].Value));
var use = DotnetUse().Match(job);
if (!use.Success)
{
continue;
}
var install = job.IndexOf("bash .gitea/scripts/dotnet.sh 10.0", StringComparison.Ordinal);
Assert.IsTrue(install >= 0 && install < use.Index, $"{name}: {header.Groups["name"].Value} uses «{use.Value}» before dotnet.sh");
}
}
var installer = Code(Script("dotnet.sh"));
StringAssert.Contains(installer, "https://builds.dotnet.microsoft.com/dotnet/release-metadata/$canale/releases.json");
StringAssert.Contains(installer, "sha512sum -c");
StringAssert.Contains(installer, "-f \"$qui/json.awk\" -f \"$qui/dotnet-sdk.awk\"");
Assert.DoesNotContain("dotnet-install", installer, "no installation script fetched on the fly");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheSdkComesOnlyFromMicrosoftWithTheHashOfItsMetadata()
{
var bash = RequireBash();
CiPath("scripts", "dotnet-sdk.awk");
using var folder = new TempFolder("febe-sdk");
var hash = string.Concat(Enumerable.Repeat("AB", 64));
var other = new string('c', 128);
const string sdk = "https://builds.dotnet.microsoft.com/dotnet/Sdk";
// The metadata of a channel as Microsoft writes them: latest-sdk at the root, the files of each SDK with url and
// hash. Another rid, a zip, an older SDK and a copy on another host are there too.
string Metadata(string latest, string host, string digest) => $$$"""
{"channel-version": "10.0", "latest-release": "10.0.5", "latest-sdk": "{{{latest}}}", "releases": [
{"release-version": "10.0.5", "sdk": {"version": "10.0.201", "files": [
{"name": "dotnet-sdk-linux-arm64.tar.gz", "rid": "linux-arm64", "url": "{{{sdk}}}/10.0.201/dotnet-sdk-10.0.201-linux-arm64.tar.gz", "hash": "{{{other}}}"},
{"name": "dotnet-sdk-linux-x64.tar.gz", "rid": "linux-x64", "url": "{{{host}}}/10.0.201/dotnet-sdk-10.0.201-linux-x64.tar.gz", "hash": "{{{digest}}}"},
{"name": "dotnet-sdk-linux-x64.zip", "rid": "linux-x64", "url": "{{{sdk}}}/10.0.201/dotnet-sdk-10.0.201-linux-x64.zip", "hash": "{{{other}}}"}]}},
{"release-version": "10.0.4", "sdk": {"version": "10.0.105", "files": [
{"name": "dotnet-sdk-linux-x64.tar.gz", "rid": "linux-x64", "url": "{{{sdk}}}/10.0.105/dotnet-sdk-10.0.105-linux-x64.tar.gz", "hash": "{{{other}}}"}]}}]}
""";
async Task<(int Code, string Output, string Errors)> ChooseAsync(string json)
{
var file = Path.Combine(folder.Path, $"releases-{Guid.NewGuid():N}.json");
await File.WriteAllTextAsync(file, json, TestContext.CancellationToken);
return await RunProcessAsync(bash, ["-c", "LC_ALL=C awk -v rid=linux-x64 -f .gitea/scripts/json.awk -f .gitea/scripts/dotnet-sdk.awk \"$1\"", "bash", file.Replace('\\', '/')]);
}
var chosen = await ChooseAsync(Metadata("10.0.201", sdk, hash));
Assert.AreEqual(0, chosen.Code, chosen.Errors);
Assert.AreEqual($"10.0.201\t{sdk}/10.0.201/dotnet-sdk-10.0.201-linux-x64.tar.gz\t{hash.ToLowerInvariant()}\n", chosen.Output);
// No archive of the newest SDK for this rid, an archive on another host, a short hash, no latest-sdk, broken
// JSON: nothing is chosen, and the step stops.
foreach (var (json, why) in new[]
{
(Metadata("10.0.300", sdk, hash), "archivio"),
(Metadata("10.0.201", "https://esempio.invalid/dotnet/Sdk", hash), "archivio"),
(Metadata("10.0.201", "http://builds.dotnet.microsoft.com/dotnet/Sdk", hash), "archivio"),
(Metadata("10.0.201", sdk, hash[..64]), "archivio"),
(Metadata("", sdk, hash), "latest-sdk"),
(Metadata("10.0.201", sdk, hash)[..200], "non validi"),
})
{
var refused = await ChooseAsync(json);
Assert.AreEqual(1, refused.Code, $"{why}\n{refused.Output}");
Assert.IsEmpty(refused.Output, why);
StringAssert.Contains(refused.Errors, why);
}
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheChecksStopActionsBadIndentationAndBrokenJson()
{
var bash = RequireBash();
CiPath("scripts", "controlli.sh");
const string good = """
name: prova
on:
push:
branches: ["**"]
jobs:
uno:
runs-on: ubuntu-latest
steps:
- name: Passo
run: |
echo ciao
un rientro libero dentro il blocco di testo
- name: Altro
run: >-
echo uno
due
""";
var passed = await RunChecksAsync(bash, good, "{\"a\": [1, 2.5e3, \"x\\u00e8\"], \"b\": null}");
Assert.AreEqual(0, passed.Code, passed.Output + passed.Errors);
StringAssert.Contains(passed.Output, "Controlli superati.");
foreach (var (workflow, json, expected) in new[]
{
(good.Replace(" - name: Altro", " - uses: actions/checkout@v4\n - name: Altro", StringComparison.Ordinal), "{}", "«uses:» (nessuna azione: solo comandi)"),
(good.Replace(" runs-on:", " runs-on:", StringComparison.Ordinal), "{}", "rientro dispari"),
(good.Replace(" runs-on:", "\truns-on:", StringComparison.Ordinal), "{}", "tabulazioni"),
(good.Replace("jobs:", "lavori:", StringComparison.Ordinal), "{}", "manca «jobs:»"),
(good, "{\"a\": 1,}", "JSON non valido"),
(good, "{\"a\": 01}", "JSON non valido"),
})
{
var failed = await RunChecksAsync(bash, workflow, json);
Assert.AreEqual(1, failed.Code, $"{expected}\n{failed.Output}");
StringAssert.Contains(failed.Errors, expected, failed.Output);
}
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheArtifactsGoToThePackageOfTheRunAndTheTokenNeverToTheLog()
{
var bash = RequireBash();
CiPath("scripts", "artefatti.sh");
using var folder = new TempFolder("febe-artefatti-su");
var bin = folder.Combine("bin");
var world = folder.Combine("registro");
Directory.CreateDirectory(bin);
Directory.CreateDirectory(world);
InstallFake("fake-curl.sh", Path.Combine(bin, "curl"));
await File.WriteAllTextAsync(Path.Combine(world, "token"), RegistryToken, TestContext.CancellationToken);
const string server = "http://gitea.invalid";
var upload = $"{server}/api/packages/Alby96/generic/febe-ci";
await File.WriteAllTextAsync(Path.Combine(world, "upload"), upload, TestContext.CancellationToken);
var results = new[] { folder.Combine("prove-seme-13.trx"), folder.Combine("prove-seme-1042.trx") };
foreach (var file in results)
{
await File.WriteAllTextAsync(file, "<TestRun />\n", TestContext.CancellationToken);
}
var version = Regex.Match(Read(Repository.PathOf("Directory.Build.props")), "<Version>(?<v>[^<]+)</Version>").Groups["v"].Value + "-ci.77";
var files = results.Select(f => f.Replace('\\', '/')).ToArray();
async Task<(int Code, string Output, string Errors, List<string> Calls)> SendAsync(string? token, string flow = "verifica", string? number = "77", params string[] paths)
{
File.Delete(Path.Combine(world, "calls"));
string[] script = ["-c", "bin=\"$FAKE_BIN\"; if command -v cygpath > /dev/null; then bin=\"$(cygpath -u \"$bin\")\"; fi; PATH=\"$bin:$PATH\"; exec bash \"$@\"", "bash", ".gitea/scripts/artefatti.sh", flow];
var run = await RunProcessAsync(bash, [.. script, .. paths.Length > 0 ? paths : files], start =>
{
start.Environment["FAKE_BIN"] = bin;
start.Environment["FAKE_CURL_WORLD"] = world.Replace('\\', '/');
start.Environment["GITEA_URL"] = server + "/";
start.Environment["PROPRIETARIO"] = "Alby96";
start.Environment.Remove("REGISTRY_TOKEN");
start.Environment.Remove("NUMERO");
if (token is not null)
{
start.Environment["REGISTRY_TOKEN"] = token;
}
if (number is not null)
{
start.Environment["NUMERO"] = number;
}
});
Assert.DoesNotContain(RegistryToken, run.Output + run.Errors, "the token never reaches the log");
Assert.DoesNotContain("fake curl:", run.Errors);
Assert.DoesNotContain("curl: (", run.Errors, "a real curl was called");
return (run.Code, run.Output, run.Errors, await ReadLinesAsync(Path.Combine(world, "calls")));
}
// Without the secret: a warning, nothing sent, the job green.
var without = await SendAsync(token: null);
Assert.AreEqual(0, without.Code, without.Errors);
StringAssert.Contains(without.Output, "::warning::Manca il segreto REGISTRY_TOKEN");
Assert.IsEmpty(without.Calls);
// With it: one PUT per file, into the version of the run.
var sent = await SendAsync(RegistryToken);
Assert.AreEqual(0, sent.Code, sent.Errors);
CollectionAssert.AreEqual(new[] { $"PUT {upload}/{version}/prove-seme-13.trx", $"PUT {upload}/{version}/prove-seme-1042.trx" }, sent.Calls);
Assert.AreEqual("<TestRun />\n", (await File.ReadAllTextAsync(Path.Combine(world, "uploaded", version, "prove-seme-13.trx"), TestContext.CancellationToken)).Replace("\r\n", "\n", StringComparison.Ordinal));
StringAssert.Contains(sent.Output, $"Artefatti: {server}/Alby96/-/packages/generic/febe-ci/{version}");
// A new attempt of the same run: Gitea answers 409, the old copy goes and the new one takes its place.
var again = await SendAsync(RegistryToken, paths: [files[0]]);
Assert.AreEqual(0, again.Code, again.Errors);
CollectionAssert.AreEqual(new[] { $"PUT {upload}/{version}/prove-seme-13.trx", $"DELETE {upload}/{version}/prove-seme-13.trx", $"PUT {upload}/{version}/prove-seme-13.trx" }, again.Calls);
// The release keeps its own versions.
var release = await SendAsync(RegistryToken, "rilascio", paths: [files[1]]);
Assert.AreEqual(0, release.Code, release.Errors);
CollectionAssert.AreEqual(new[] { $"PUT {upload}/{version.Replace("-ci.", "-rilascio.", StringComparison.Ordinal)}/prove-seme-1042.trx" }, release.Calls);
// A missing file, a refusal, a token Gitea does not know: the step fails. Without the number of the run, or with
// a flow of another name, nothing is sent.
var missing = await SendAsync(RegistryToken, paths: [folder.Combine("non-c-e.trx").Replace('\\', '/')]);
Assert.AreEqual(1, missing.Code, missing.Output);
Assert.IsEmpty(missing.Calls);
var unknown = await SendAsync("un-altro-gettone-finto");
Assert.AreEqual(1, unknown.Code, unknown.Output);
StringAssert.Contains(unknown.Errors, "risponde 401");
Assert.DoesNotContain("un-altro-gettone-finto", unknown.Output + unknown.Errors);
foreach (var (flow, number) in new[] { ("verifica", (string?)null), ("verifica", "7a"), ("prova", "77") })
{
var refused = await SendAsync(RegistryToken, flow, number);
Assert.AreEqual(2, refused.Code, $"{flow} {number}");
Assert.IsEmpty(refused.Calls, $"{flow} {number}");
}
}
/// <summary>controlli.sh in a repository of its own: the scripts it needs, one workflow, one JSON file.</summary>
private async Task<(int Code, string Output, string Errors)> RunChecksAsync(string bash, string workflow, string json)
{
using var folder = new TempFolder("febe-controlli");
var root = folder.Path;
foreach (var script in new[] { "controlli.sh", "json.awk", "json-valido.awk" })
{
var target = Path.Combine(root, ".gitea", "scripts", script);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
await File.WriteAllTextAsync(target, Read(CiPath("scripts", script)), TestContext.CancellationToken);
}
Directory.CreateDirectory(Path.Combine(root, ".gitea", "workflows"));
Directory.CreateDirectory(Path.Combine(root, "src"));
await File.WriteAllTextAsync(Path.Combine(root, ".gitea", "workflows", "prova.yml"), workflow.Replace("\r\n", "\n", StringComparison.Ordinal) + "\n", TestContext.CancellationToken);
await File.WriteAllTextAsync(Path.Combine(root, "dati.json"), json, TestContext.CancellationToken);
await File.WriteAllTextAsync(Path.Combine(root, "Directory.Build.props"), "<Project>\n <PropertyGroup>\n <Version>0.1.2</Version>\n </PropertyGroup>\n</Project>\n", TestContext.CancellationToken);
await File.WriteAllTextAsync(Path.Combine(root, "Febe.slnx"), "<Solution>\n <Project Path=\"src/Uno.csproj\" />\n</Solution>\n", TestContext.CancellationToken);
await File.WriteAllTextAsync(Path.Combine(root, "src", "Uno.csproj"), "<Project />\n", TestContext.CancellationToken);
var prepared = await RunProcessAsync(bash, ["-c", "git -c init.defaultBranch=main init -q . && git -c core.autocrlf=false add -A"], start => start.WorkingDirectory = root);
Assert.AreEqual(0, prepared.Code, prepared.Errors);
return await RunProcessAsync(bash, [".gitea/scripts/controlli.sh"], start => start.WorkingDirectory = root);
}
[GeneratedRegex(@"(?m)^\s*(?:-\s+)?uses\s*:")]
private static partial Regex UsesLine();
// A command named node, npm, npx, corepack or nodejs: at the start of a command, not a word in a message.
[GeneratedRegex(@"(?:^|[;&|({]|\$\(|\b(?:then|do|else|run:|exec|command)\s)\s*(?:node|nodejs|npm|npx|corepack)(?=\s|$|[;&|)])")]
private static partial Regex NodeCommand();
[GeneratedRegex(@"(?m)^ - name: (?<name>.+)$")]
private static partial Regex StepName();
// Where a job uses the SDK: dotnet itself, or the installer build, which runs dotnet publish.
[GeneratedRegex(@"(?m)^\s*(?:run:\s*(?:>-?|\|)?\s*)?(?:dotnet\s+(?:build|test|publish|run|restore|pack)\b|bash installer/costruisci\.sh)")]
private static partial Regex DotnetUse();
}