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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 14:41:49 +01:00
1 parent 7a54f1a460
commit a4ad8a8bc4
27 files changed
+1763 -396

No files matched your search

+8 -3
View File
@@ -148,11 +148,16 @@ public sealed partial class PackagingTests
// The registry at home answers in HTTP: buildx with its own builder, told so, and no «docker login». The push is
// the same build as the tested one (.gitea/scripts/costruisci-immagine.sh, shared with the verification).
StringAssert.Contains(image, "uses: docker/setup-buildx-action@v3");
StringAssert.Contains(image, "http = true");
StringAssert.Contains(image, "insecure = true");
StringAssert.Contains(image, "bash .gitea/scripts/costruisci-immagine.sh builder \"$REGISTRY\"");
StringAssert.Contains(Step(image, "Pubblicazione sul registro di Gitea"), "bash .gitea/scripts/costruisci-immagine.sh pubblica");
var build = File.ReadAllText(Repository.PathOf(".gitea", "scripts", "costruisci-immagine.sh"));
StringAssert.Contains(build, "http = true");
StringAssert.Contains(build, "insecure = true");
// No artifact goes from one job to the next (that would take an action): the release builds Febe.exe, the
// installer and the zip again from the same commit, as the windows job did before it.
StringAssert.Contains(release, "bash installer/costruisci.sh \"${GITHUB_REF_NAME#v}\"");
StringAssert.Contains(release, "bash .gitea/scripts/dotnet.sh 10.0");
StringAssert.Contains(build, "docker buildx build \"${comuni[@]}\" \"${etichette[@]}\" --push .");
foreach (var text in new[] { image, build })
{
@@ -0,0 +1,332 @@
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();
}
@@ -7,8 +7,9 @@ using Febe.Tests.Support;
namespace Febe.Tests.Packaging;
/// <summary>
/// The cleanup of the CI: .gitea/scripts/pulizia-docker.sh, its choice of registry tags (versioni-registro.js) and the
/// steps that run it. The Docker daemon is shared with Alberto's other projects, very likely with his Unraid apps, and
/// The cleanup of the CI: .gitea/scripts/pulizia-docker.sh, its choice of registry versions (versioni-registro.sh, awk
/// with json.awk: no Node, no jq) and the steps that run it. The Docker daemon is shared with Alberto's other projects,
/// very likely with his Unraid apps, and
/// may run a real Febe. Since 21 October 2026 the cleanup removes what the CI of Febe made and what nothing uses any
/// more, of any project; never a container, a volume or a network that is not the CI's, never main, latest or a
/// release on the registry, never the token in the log; with --prova it removes nothing at all. The script runs against
@@ -34,6 +35,12 @@ public sealed partial class PipelineTests
"sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647",
];
/// <summary>
/// The versions of the generic package febe-ci in artefatti-registro.json created more than 14 days ago, oldest
/// first: those of 2020 with the shape of an artifact of the CI and a date with its zone.
/// </summary>
private static readonly string[] ExpiredArtifacts = ["0.1.2-rilascio.3", "0.1.2-ci.40", "0.2.0-rc.1-ci.7"];
[TestMethod]
public void TheCleanupNeverPrunesBlindlyAndChoosesOnlyByTheMarksOfTheCiOrByUse()
{
@@ -80,9 +87,13 @@ public sealed partial class PipelineTests
Assert.IsFalse(ForcedImageRemoval().IsMatch(cleanup), "an image is never removed by force");
StringAssert.Contains(cleanup, "[[ \"$riferimento\" =~ ^febe-ci:[0-9]+$ ]]");
// On the registry only the shape of a sha- tag of the verification, checked again before every DELETE.
// On the registry only the shape of a sha- tag of the verification, or of an artifact of the CI, checked again
// before every DELETE.
StringAssert.Contains(cleanup, "[[ ! \"$versione\" =~ ^sha-[0-9a-f]{7,40}$ ]]");
StringAssert.Contains(Script("versioni-registro.js"), "/^sha-[0-9a-f]{7,40}$/");
StringAssert.Contains(cleanup, "[[ ! \"$versione\" =~ ^[0-9]+\\.[0-9]+\\.[0-9]+(-[0-9A-Za-z.-]+)?-(ci|rilascio)\\.[0-9]+$ ]]");
var chooser = Script("versioni-registro.sh");
StringAssert.Contains(chooser, "$4 ~ /^sha-[0-9a-f]+$/ && length($4) >= 11 && length($4) <= 44");
Assert.DoesNotContain("node", Code(Script("pulizia-docker.sh")) + Code(chooser), "the registry is read with awk, not with Node");
}
[TestMethod]
@@ -321,7 +332,6 @@ public sealed partial class PipelineTests
public async Task TheDryRunListsWhatTheCleanupWouldTakeAndTouchesNothing()
{
var bash = RequireBash();
RequireNode();
var world = SharedDaemon.World with { Registry = new FakeRegistry(RegistryToken) };
var tried = await RunCleanupAsync(bash, world, "completa", "--prova");
Assert.AreEqual(0, tried.Code, tried.Report);
@@ -336,7 +346,14 @@ public sealed partial class PipelineTests
Assert.IsTrue(tried.RegistryCalls.Count > 0 && tried.RegistryCalls.All(c => c.StartsWith("GET ", StringComparison.Ordinal)), tried.Report);
Assert.IsEmpty(tried.Deleted, tried.Report);
Assert.IsEmpty(tried.DeletedArtifacts, tried.Report);
Assert.DoesNotContain(RegistryToken, tried.Output + tried.Errors, "the token never reaches the log");
foreach (var version in ExpiredArtifacts)
{
StringAssert.Contains(tried.Output, $" toglierei febe-ci {version} (caricata il ", tried.Report);
}
Assert.AreEqual(ExpiredArtifacts.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), SummaryCount(tried.Output, "artefatti della CI sul registro"), tried.Report);
// What it lists, with size and age: also what becomes unused once the leftovers it lists are gone.
Assert.DoesNotContain("solo indicativo", tried.Output, "with the classic store the ages are those «until» uses");
@@ -428,21 +445,22 @@ public sealed partial class PipelineTests
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheRegistryKeepsMainLatestTheReleasesAndTheTenNewestShaTags()
{
var node = RequireNode();
var script = CiPath("scripts", "versioni-registro.js");
var bash = RequireBash();
CiPath("scripts", "versioni-registro.sh");
const string script = ".gitea/scripts/versioni-registro.sh";
using var folder = new TempFolder("febe-registro");
var pages = await WriteRegistryPagesAsync(folder.Path);
// Of fourteen sha- tags the four oldest go. sha-3d4e5f6 (23:30 UTC) is newer than sha-4e5f6a7 (01:00 in Italy,
// 23:00 UTC): dates, not text. main, latest, the releases, digests, malformed sha- tags, one without a date and
// other packages stay, though they are older; a tag in two pages counts once.
var chosen = await RunProcessAsync(node, [script, "10", .. pages]);
var chosen = await RunProcessAsync(bash, [script, "10", .. pages]);
Assert.AreEqual(0, chosen.Code, chosen.Errors);
CollectionAssert.AreEqual(OldShaTags, Lines(chosen.Output).Select(l => l.Split('\t')[0]).ToList(), chosen.Output);
StringAssert.Contains(chosen.Output, "sha-2c3d4e5\t2026-10-03T07:00:00Z\n");
// Keeping none: every well formed sha- tag of the container febe, and nothing else.
var all = await RunProcessAsync(node, [script, "0", .. pages]);
var all = await RunProcessAsync(bash, [script, "0", .. pages]);
Assert.HasCount(14, Lines(all.Output), all.Output);
foreach (var line in Lines(all.Output))
{
@@ -451,20 +469,63 @@ public sealed partial class PipelineTests
// The untagged versions, the manifests of an index with their layers: listed only to be counted, oldest first,
// those of the container febe and no other package.
var untagged = await RunProcessAsync(node, [script, "senza-etichetta", .. pages]);
var untagged = await RunProcessAsync(bash, [script, "senza-etichetta", .. pages]);
Assert.AreEqual(0, untagged.Code, untagged.Errors);
CollectionAssert.AreEqual(UntaggedDigests, Lines(untagged.Output).Select(l => l.Split('\t')[0]).ToList(), untagged.Output);
// Keeping more than there are: nothing. An empty page of Gitea is fine; a page that is not a list stops
// everything, so in doubt nothing goes.
// Keeping more than there are: nothing. An empty page of Gitea is fine; a page that is not a list, or not JSON,
// stops everything, so in doubt nothing goes. So does a mode written another way.
var empty = Path.Combine(folder.Path, "vuota.json");
await File.WriteAllTextAsync(empty, "null", TestContext.CancellationToken);
Assert.IsEmpty((await RunProcessAsync(node, [script, "20", .. pages, empty])).Output);
Assert.IsEmpty((await RunProcessAsync(bash, [script, "20", .. pages, empty])).Output);
var broken = Path.Combine(folder.Path, "rotta.json");
await File.WriteAllTextAsync(broken, "{\"message\":\"internal error\"}", TestContext.CancellationToken);
var refused = await RunProcessAsync(node, [script, "10", .. pages, broken]);
Assert.AreEqual(2, refused.Code, refused.Errors);
Assert.IsEmpty(refused.Output);
var cut = Path.Combine(folder.Path, "tagliata.json");
await File.WriteAllTextAsync(cut, "[{\"type\":\"container\",\"name\":\"febe\",\"version\":\"sha-0a1b2c3\"", TestContext.CancellationToken);
foreach (var bad in new[] { broken, cut })
{
var refused = await RunProcessAsync(bash, [script, "10", .. pages, bad]);
Assert.AreEqual(2, refused.Code, refused.Errors);
Assert.IsEmpty(refused.Output);
StringAssert.Contains(refused.Errors, Path.GetFileName(bad));
}
foreach (var mode in new[] { "dieci", "-1", "senza_etichetta" })
{
var wrong = await RunProcessAsync(bash, [script, mode, .. pages]);
Assert.AreEqual(2, wrong.Code, mode);
Assert.IsEmpty(wrong.Output, mode);
}
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task OnlyTheArtifactsOfTheCiOlderThanTheirDaysExpire()
{
var bash = RequireBash();
CiPath("scripts", "versioni-registro.sh");
const string script = ".gitea/scripts/versioni-registro.sh";
using var folder = new TempFolder("febe-artefatti");
var pages = await WriteArtifactPagesAsync(folder.Path, "pagina-");
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture);
// Those of 2020 with the shape <x.y.z>-ci.<n> or <x.y.z>-rilascio.<n>, oldest first. The one of 2099, a release
// version, a date that does not read or has no zone, another package, a container and a strange name stay.
var expired = await RunProcessAsync(bash, [script, "scadute", "14", now, .. pages]);
Assert.AreEqual(0, expired.Code, expired.Errors);
CollectionAssert.AreEqual(ExpiredArtifacts, Lines(expired.Output).Select(l => l.Split('\t')[0]).ToList(), expired.Output);
StringAssert.Contains(expired.Output, "0.2.0-rc.1-ci.7\t2020-04-01T00:00:00.250Z\n");
// On the first of April 2020 at noon only those created more than a day before have expired.
var early = await RunProcessAsync(bash, [script, "scadute", "1", "1585742400", .. pages]);
CollectionAssert.AreEqual(new[] { "0.1.2-rilascio.3", "0.1.2-ci.40" }, Lines(early.Output).Select(l => l.Split('\t')[0]).ToList(), early.Output);
foreach (var arguments in new[] { new[] { "scadute", "14" }, ["scadute", "quattordici", now], ["scadute", "14", "ieri"] })
{
var wrong = await RunProcessAsync(bash, [script, .. arguments, .. pages]);
Assert.AreEqual(2, wrong.Code, string.Join(' ', arguments));
Assert.IsEmpty(wrong.Output);
}
}
[TestMethod]
@@ -472,41 +533,54 @@ public sealed partial class PipelineTests
public async Task TheRegistryCleanupDeletesOnlyTheChosenTagsNeverPrintsTheTokenAndARefusalIsOnlyAWarning()
{
var bash = RequireBash();
RequireNode();
// A daemon with almost nothing on it: here only the registry counts.
var quiet = new World(["c-encelado|encelado|exited|5000|encelado:latest|img-encelado|"], ["img-encelado|encelado:latest|5000||250MB"], [], []);
var run = await RunCleanupAsync(bash, quiet with { Registry = new FakeRegistry(RegistryToken) }, "completa");
Assert.AreEqual(0, run.Code, run.Report);
CollectionAssert.AreEqual(OldShaTags, run.Deleted, run.Report);
CollectionAssert.AreEqual(ExpiredArtifacts, run.DeletedArtifacts, run.Report);
var package = $"{RegistryApi}/packages/Alby96/container/febe";
var artifacts = $"{RegistryApi}/packages/Alby96/generic/febe-ci";
CollectionAssert.AreEqual(
new[] { $"GET {package}?page=1&limit=50", $"GET {package}?page=2&limit=50", $"GET {package}?page=3&limit=50" }
.Concat(OldShaTags.Select(tag => $"DELETE {package}/{tag}")).ToList(),
.Concat(OldShaTags.Select(tag => $"DELETE {package}/{tag}"))
.Concat([$"GET {artifacts}?page=1&limit=50", $"GET {artifacts}?page=2&limit=50", $"GET {artifacts}?page=3&limit=50"])
.Concat(ExpiredArtifacts.Select(version => $"DELETE {artifacts}/{version}")).ToList(),
run.RegistryCalls,
run.Report);
Assert.DoesNotContain(RegistryToken, run.Output + run.Errors, "the token never reaches the log");
Assert.AreEqual("4", SummaryCount(run.Output, "etichette sha- sul registro"), run.Report);
Assert.AreEqual("3", SummaryCount(run.Output, "artefatti della CI sul registro"), run.Report);
// The untagged versions stay, and the log says how many there are: their layers are freed only by a cleanup
// rule of Gitea, which knows whether a tag still uses them.
Assert.IsFalse(run.RegistryCalls.Any(c => c.Contains("sha256:", StringComparison.Ordinal)), run.Report);
StringAssert.Contains(run.Output, $" {UntaggedDigests.Length} versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano", run.Report);
// No package febe-ci yet (404): nothing to remove there, and no warning.
var without = await RunCleanupAsync(bash, quiet with { Registry = new FakeRegistry(RegistryToken, Artifacts: false) }, "completa");
Assert.AreEqual(0, without.Code, without.Report);
StringAssert.Contains(without.Output, "Il pacchetto febe-ci non è ancora sul registro: niente da togliere.", without.Report);
Assert.IsEmpty(without.DeletedArtifacts, without.Report);
Assert.IsFalse(WarningLine().IsMatch(without.Output), without.Report);
// The API refuses (a token without the permission) or does not know the token: a warning, nothing deleted,
// and the weekly job stays green.
// the registry is not asked again with the same token, and the weekly job stays green.
foreach (var registry in new[] { new FakeRegistry(RegistryToken, Refuse: true), new FakeRegistry(RegistryToken, Sent: "un-altro-gettone-finto") })
{
var refused = await RunCleanupAsync(bash, quiet with { Registry = registry }, "completa");
Assert.AreEqual(0, refused.Code, refused.Report);
StringAssert.Contains(refused.Output, "::warning::L'API dei pacchetti di Gitea risponde 40", refused.Report);
Assert.IsEmpty(refused.Deleted, refused.Report);
Assert.IsEmpty(refused.DeletedArtifacts, refused.Report);
Assert.HasCount(1, refused.RegistryCalls, refused.Report);
Assert.DoesNotContain(RegistryToken, refused.Output + refused.Errors);
Assert.DoesNotContain("un-altro-gettone-finto", refused.Output + refused.Errors);
}
}
/// <summary>
/// The daemon of <see cref="OnADaemonSharedWithARealFebeTheCleanupOfTheCiTakesOnlyWhatTheCiMade"/> (format in
/// fake-docker.sh). A real Febe started from :latest and one from :main carry the febe.ci.* labels of their images,
@@ -714,10 +788,11 @@ public sealed partial class PipelineTests
}
/// <summary>
/// The packages API of Gitea with the pages of versioni-registro.json, for the token given. Sent is the token the
/// cleanup gets (the same, if null); Refuse answers 403 to everything.
/// The packages API of Gitea with the pages of versioni-registro.json and, with Artifacts, the generic package
/// febe-ci of artefatti-registro.json, for the token given. Sent is the token the cleanup gets (the same, if null);
/// Refuse answers 403 to everything.
/// </summary>
private sealed record FakeRegistry(string Token, bool Refuse = false, string? Sent = null);
private sealed record FakeRegistry(string Token, bool Refuse = false, string? Sent = null, bool Artifacts = true);
private sealed record CleanupRun(int Code, string Output, string Errors)
{
@@ -740,6 +815,9 @@ public sealed partial class PipelineTests
/// <summary>The versions deleted from the registry.</summary>
public List<string> Deleted { get; init; } = [];
/// <summary>The versions of the generic package febe-ci deleted from the registry.</summary>
public List<string> DeletedArtifacts { get; init; } = [];
public List<string> ImageIds => [.. Images.Select(i => i.Split('|')[0])];
public string Report => $"codice {Code}\n{Output}\n{Errors}";
@@ -794,6 +872,11 @@ public sealed partial class PipelineTests
}
await WriteRegistryPagesAsync(registry);
if (fake.Artifacts)
{
await File.WriteAllTextAsync(Path.Combine(registry, "base-ci"), $"{RegistryApi}/packages/Alby96/generic/febe-ci", TestContext.CancellationToken);
await WriteArtifactPagesAsync(registry, "ci-page-");
}
}
// The fakes go first on the PATH from inside bash: Git Bash puts its own folders (with a real curl) before the
@@ -826,6 +909,7 @@ public sealed partial class PipelineTests
Calls = await ReadLinesAsync(folder.Combine("calls")),
RegistryCalls = await ReadLinesAsync(Path.Combine(registry, "calls")),
Deleted = await ReadLinesAsync(Path.Combine(registry, "deleted")),
DeletedArtifacts = await ReadLinesAsync(Path.Combine(registry, "deleted-ci")),
};
if (touchesDocker)
{
@@ -879,6 +963,23 @@ public sealed partial class PipelineTests
return files;
}
/// <summary>The pages of artefatti-registro.json (the generic package febe-ci) as Gitea would answer them, one
/// file each, named prefix plus the page number.</summary>
private async Task<List<string>> WriteArtifactPagesAsync(string folder, string prefix)
{
var fixture = await File.ReadAllTextAsync(Repository.PathOf("tests", "Febe.Tests", "Packaging", "artefatti-registro.json"), TestContext.CancellationToken);
using var pages = JsonDocument.Parse(fixture);
var files = new List<string>();
foreach (var page in pages.RootElement.EnumerateArray())
{
var file = Path.Combine(folder, $"{prefix}{files.Count + 1}.json");
await File.WriteAllTextAsync(file, page.GetRawText(), TestContext.CancellationToken);
files.Add(file);
}
return files;
}
private static void InstallFake(string name, string path)
{
File.Copy(Repository.PathOf("tests", "Febe.Tests", "Packaging", name), path);
@@ -935,22 +1036,6 @@ public sealed partial class PipelineTests
return bash;
}
/// <summary>node from the PATH: the registry part of the cleanup reads JSON with it, in the CI as here.</summary>
private static string RequireNode()
{
var names = OperatingSystem.IsWindows() ? new[] { "node.exe" } : ["node"];
var node = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty)
.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)
.SelectMany(folder => names.Select(name => Path.Combine(folder.Trim('"'), name)))
.FirstOrDefault(File.Exists);
if (node is null)
{
Assert.Inconclusive("Manca node: la prova della scelta delle versioni del registro si salta.");
}
return node;
}
[GeneratedRegex(@"docker (?<what>[a-z]+) prune(?<args>[^\n]*)")]
private static partial Regex Prune();
+9 -6
View File
@@ -59,7 +59,7 @@ public sealed partial class PipelineTests
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, "container:\n image: debian:trixie", "Debian: Chromium is a real package there, a snap on Ubuntu; and no Node in it");
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");
@@ -114,9 +114,12 @@ public sealed partial class PipelineTests
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");
StringAssert.Contains(image, "BUILDER: febe-ci-${{ gitea.run_id }}");
StringAssert.Contains(image, "bash .gitea/scripts/costruisci-immagine.sh builder \"$REGISTRY\"");
var builder = Code(Script("costruisci-immagine.sh"));
StringAssert.Contains(builder, "http = true");
StringAssert.Contains(builder, "insecure = true");
StringAssert.Contains(builder, "--driver docker-container");
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" })
{
@@ -169,7 +172,7 @@ public sealed partial class PipelineTests
var secrets = Script("segreti.sh");
StringAssert.Contains(secrets, "--redact");
StringAssert.Contains(Job(Workflow("verifica.yml"), "controlli"), "fetch-depth: 0");
StringAssert.Contains(Step(Job(Workflow("verifica.yml"), "controlli"), "Sorgenti"), "PROFONDITA: \"0\"", "gitleaks reads the whole history");
var scan = Script("scansione-immagine.sh");
StringAssert.Contains(scan, "--severity CRITICAL --ignore-unfixed");
StringAssert.Contains(scan, "--exit-code 1");
@@ -264,7 +267,7 @@ public sealed partial class PipelineTests
[GeneratedRegex(@"\b(?:echo|printf)\b")]
private static partial Regex Printing();
[GeneratedRegex(@"\$\{?(?:TOKEN|FEBE_PASSWORD|AUTH|REGISTRY_TOKEN|PASSWORD)\b")]
[GeneratedRegex(@"\$\{?(?:TOKEN|FEBE_PASSWORD|AUTH|REGISTRY_TOKEN|GITEA_TOKEN|INTESTAZIONE|GIT_CONFIG_VALUE_0|PASSWORD)\b")]
private static partial Regex SecretReference();
[GeneratedRegex(@"\b[0-9a-f]{64}\b")]
@@ -0,0 +1,17 @@
[
[
{"id": 301, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-ci.40", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2-ci.40", "created_at": "2020-03-01T10:00:00+01:00"},
{"id": 302, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-ci.41", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2-ci.41", "created_at": "2099-03-01T10:00:00+01:00"},
{"id": 303, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-rilascio.3", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2-rilascio.3", "created_at": "2020-02-01T10:00:00Z"},
{"id": 304, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2", "created_at": "2020-01-01T00:00:00Z"},
{"id": 305, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-ci.39", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2-ci.39", "created_at": "non è una data"},
{"id": 309, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-ci.38", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2-ci.38", "created_at": "2020-01-15T10:00:00"}
],
[
{"id": 306, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "altro", "version": "0.1.2-ci.1", "html_url": "https://gitea.example/Alby96/-/packages/generic/altro/0.1.2-ci.1", "created_at": "2020-01-01T00:00:00Z"},
{"id": 307, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe-ci", "version": "0.1.2-ci.2", "html_url": "https://gitea.example/Alby96/-/packages/container/febe-ci/0.1.2-ci.2", "created_at": "2020-01-01T00:00:00Z"},
{"id": 301, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-ci.40", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2-ci.40", "created_at": "2020-03-01T10:00:00+01:00"},
{"id": 308, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.2.0-rc.1-ci.7", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.2.0-rc.1-ci.7", "created_at": "2020-04-01T00:00:00.250Z"},
{"id": 310, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-ci.37;rm", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/x", "created_at": "2020-01-01T00:00:00Z"}
]
]
+50 -15
View File
@@ -1,9 +1,17 @@
#!/usr/bin/env bash
# A fake curl for PipelineTests: the registry part of .gitea/scripts/pulizia-docker.sh talks to the packages API of
# Gitea 28 through it. No network. It knows only the options the cleanup uses and answers like Gitea:
# GET <base>?page=<n>&limit=50 the page $FAKE_CURL_WORLD/page-<n>.json, or [] after the last one (200)
# DELETE <base>/<version> 204, and the version is written to $FAKE_CURL_WORLD/deleted
# where <base> is the content of $FAKE_CURL_WORLD/base (…/api/v1/packages/<owner>/container/febe). Without the header
# A fake curl for PipelineTests: the registry part of .gitea/scripts/pulizia-docker.sh and .gitea/scripts/artefatti.sh
# talk to the packages API of Gitea 28 through it. No network. It knows only the options those scripts use and answers
# like Gitea:
# GET <base>?page=<n>&limit=50 the page $FAKE_CURL_WORLD/page-<n>.json, or [] after the last one (200)
# DELETE <base>/<version> 204, and the version is written to $FAKE_CURL_WORLD/deleted
# GET <ci>?page=<n>&limit=50 the page $FAKE_CURL_WORLD/ci-page-<n>.json, or [] after the last one (200)
# DELETE <ci>/<version> 204, and the version is written to $FAKE_CURL_WORLD/deleted-ci
# PUT <upload>/<version>/<file> with --upload-file: 201, the file copied to $FAKE_CURL_WORLD/uploaded/<version>/;
# 409 if that file is already there (as Gitea answers a second upload)
# DELETE <upload>/<version>/<file> 204, and the uploaded file goes
# where <base> is the content of $FAKE_CURL_WORLD/base (…/api/v1/packages/<owner>/container/febe), <ci> of
# $FAKE_CURL_WORLD/base-ci (…/api/v1/packages/<owner>/generic/febe-ci) and <upload> of $FAKE_CURL_WORLD/upload
# (…/api/packages/<owner>/generic/febe-ci); a base whose file is missing is unknown. Without the header
# «Authorization: token <content of $FAKE_CURL_WORLD/token>» it answers 401; with $FAKE_CURL_WORLD/refuse it answers
# 403 to every call; any other address is 404. Every call goes to $FAKE_CURL_WORLD/calls as «METHOD URL», never with
# its headers. Any other option is an error (exit 3).
@@ -11,7 +19,7 @@ set -uo pipefail
world="${FAKE_CURL_WORLD:?}"
token="$(cat "$world/token" 2> /dev/null)"
method=GET output="" write="" url="" authorized=0
method=GET output="" write="" url="" authorized=0 upload=""
while (($#)); do
case "$1" in
-s | -S | -sS) ;;
@@ -20,6 +28,7 @@ while (($#)); do
-H) [[ -n "$token" && "$2" == "Authorization: token $token" ]] && authorized=1; shift ;;
-o) output="$2"; shift ;;
-w) write="$2"; shift ;;
--upload-file) upload="$2"; shift ;;
-*) echo "fake curl: unexpected option $1" >&2; exit 3 ;;
*)
[[ -z "$url" ]] || { echo "fake curl: a second address $1" >&2; exit 3; }
@@ -30,6 +39,7 @@ while (($#)); do
done
printf '%s %s\n' "$method" "$url" >> "$world/calls"
[[ -z "$write" || "$write" == '%{http_code}' ]] || { echo "fake curl: unexpected -w $write" >&2; exit 3; }
[[ -z "$upload" || "$method" == PUT ]] || { echo "fake curl: --upload-file without -X PUT" >&2; exit 3; }
answer() {
local code="$1" body="${2:-}"
@@ -45,19 +55,44 @@ answer() {
[[ -f "$world/refuse" ]] && answer 403 '{"message":"token does not have at least one of required scope(s): [write:package]"}'
((authorized)) || answer 401 '{"message":"token is required"}'
base="$(cat "$world/base")"
known() { [[ -f "$world/$1" ]] && cat "$world/$1"; }
base="$(known base)" || base="//nessuna-base"
ci="$(known base-ci)" || ci="//nessuna-base"
send="$(known upload)" || send="//nessuna-base"
page() {
local prefix="$1" number="${url#*\?page=}"
number="${number%%&*}"
if [[ -f "$world/${prefix}page-$number.json" ]]; then
answer 200 "$(cat "$world/${prefix}page-$number.json")"
fi
answer 200 "[]"
}
case "$method $url" in
"GET $base?page="*"&limit=50")
page="${url#"$base?page="}"
page="${page%%&*}"
if [[ -f "$world/page-$page.json" ]]; then
answer 200 "$(cat "$world/page-$page.json")"
fi
answer 200 "[]"
;;
"GET $base?page="*"&limit=50") page "" ;;
"DELETE $base/"*)
echo "${url#"$base/"}" >> "$world/deleted"
answer 204
;;
"GET $ci?page="*"&limit=50") page "ci-" ;;
"DELETE $ci/"*)
echo "${url#"$ci/"}" >> "$world/deleted-ci"
answer 204
;;
"PUT $send/"*/*)
[[ -f "$upload" ]] || { echo "fake curl: no file to upload: $upload" >&2; exit 3; }
target="$world/uploaded/${url#"$send/"}"
[[ -f "$target" ]] && answer 409 '{"message":"package file already exists"}'
mkdir -p "$(dirname "$target")"
cp "$upload" "$target"
answer 201
;;
"DELETE $send/"*/*)
target="$world/uploaded/${url#"$send/"}"
[[ -f "$target" ]] || answer 404 '{"message":"The target couldn'"'"'t be found."}'
rm -f "$target"
answer 204
;;
*) answer 404 '{"message":"The target couldn'"'"'t be found."}' ;;
esac