tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Add Progmasoft.Tazel.Packaging and parse SPDX expressions with it
- Commit
7b0fcd12cad2d7e9ae2a426f2a0f58478ce5cfb3- Author
- Leitwolf11 ·
- Parents
416b60c24a75
Changes
.github/workflows/release.yml | 2 +- CHANGELOG.md | 11 +- Directory.Packages.props | 1 - THIRD-PARTY-NOTICES.md | 3 +- Tazel.slnx | 1 + docs/README.md | 1 + docs/packaging.md | 41 +++ docs/project-files.md | 3 +- docs/reference/docfx.json | 2 +- spdx/update.cs | 3 +- .../Progmasoft.Tazel.Packaging.csproj | 20 ++ src/Progmasoft.Tazel.Packaging/Sha256Sums.cs | 64 +++++ .../Spdx/SpdxExpression.cs | 112 ++++++++ .../Spdx/SpdxExpressionParser.cs | 301 +++++++++++++++++++++ .../Spdx/SpdxLicenseList.cs | 218 +++++++++++++++ .../TazelPackageArchive.cs | 222 +++++++++++++++ .../TazelPackageIdentity.cs | 100 +++++++ .../TazelPluginManifest.cs | 106 ++++++++ src/Progmasoft.Tazel.PluginSdk/PackTazelPlugin.cs | 30 +- .../Progmasoft.Tazel.PluginSdk.csproj | 3 +- src/Progmasoft.Tazel/Archive/ModuleArchive.cs | 153 +---------- src/Progmasoft.Tazel/Progmasoft.Tazel.csproj | 9 +- src/Progmasoft.Tazel/Project/Plugins.cs | 61 +---- src/Progmasoft.Tazel/Project/SpdxLicenses.cs | 264 ++---------------- src/Shared/ReproducibleArchive.cs | 106 -------- tests/Progmasoft.Tazel.Tests/PackagingTests.cs | 170 ++++++++++++ tests/Progmasoft.Tazel.Tests/PluginTests.cs | 2 +- tests/Progmasoft.Tazel.Tests/SpdxLicensesTests.cs | 2 +- 28 files changed, 1444 insertions(+), 567 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a1fcd44..299712e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT # Runs when a GitHub release of Tazel is published: builds Tazel for each platform, attaches the archives and their -# SHA-256 sums to the release, and publishes the NuGet packages of the plugin API, the plugin SDK and its templates. +# SHA-256 sums to the release, and publishes the NuGet packages of the plugin API, the plugin SDK and its templates, and the packaging library. # Started by hand with the tag of a published release, it builds and attaches that release's archives again from the # tag's sources; the NuGet packages are pushed only by a published release. name: Release diff --git a/CHANGELOG.md b/CHANGELOG.md index af42c51..1989c21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,10 +5,13 @@ ## Unreleased -- `License` in `MODULE.csx` is checked as an SPDX license expression against the SPDX License List 3.29.0, which - ships with Tazel (`spdx/`, updated by `dotnet run spdx/update.cs -- <version>`); expressions are parsed with - Tethys.SPDX.ExpressionParser after Tazel checks their form. A misspelt identifier is refused with the closest - ones, a deprecated one with what replaces it: `error[E0509]`. The check is a fuzz target. +- Progmasoft.Tazel.Packaging, a new NuGet package, reads and writes Tazel packages as NuGet.Packaging does for NuGet: + package identities, reproducible `.tazel.tar.xz` archives and safe unpacking, `.sha256sums` files, the plugin + manifest, and SPDX license expressions with the SPDX License List 3.29.0. Tazel and the plugin SDK use it. + +- `License` in `MODULE.csx` is checked as an SPDX license expression against that list (`spdx/`, updated by + `dotnet run spdx/update.cs -- <version>`). A misspelt identifier is refused with the closest ones, a deprecated one + with what replaces it, a malformed expression with what is wrong: `error[E0509]`. The check is a fuzz target. - `tazel tool launch <name>` runs `TAZEL_TOOL_EXECUTABLE`, or the first `tazel-<name>` of `PATH` this user may run, with its arguments as written, and passes its exit status on; `tazel tool create-wrapper <name> [-o dir]` writes a diff --git a/Directory.Packages.props b/Directory.Packages.props index c04a3dc..b6a5579 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -10,7 +10,6 @@ <PackageVersion Include="BouncyCastle.Cryptography" Version="2.7.0" /> <PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="5.12.0" /> <PackageVersion Include="NuGet.Versioning" Version="8.0.0" /> - <PackageVersion Include="Tethys.SPDX.ExpressionParser" Version="2.2.0" /> <PackageVersion Include="Microsoft.Z3" Version="4.12.2" /> <PackageVersion Include="Lzma.Net" Version="5.8.4.3" /> <PackageVersion Include="xunit.v3" Version="4.0.3" /> diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 00bdb41..734b0c6 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -11,7 +11,6 @@ Tazel ships with the libraries below. Their licenses are in [LICENSES/](LICENSES | [Spectre.Console](https://github.com/spectreconsole/spectre.console) | MIT | Copyright (c) Patrik Svensson, Phil Scott, Nils Andresen, Cédric Luthi | | [Roslyn](https://github.com/dotnet/roslyn): Microsoft.CodeAnalysis.CSharp.Scripting and its assemblies | MIT | Copyright (c) .NET Foundation and Contributors | | [NuGet.Versioning](https://github.com/NuGet/NuGet.Client) | Apache-2.0 | Copyright (c) .NET Foundation and Contributors | -| [Tethys.SPDX.ExpressionParser](https://github.com/tngraf/Tethys.SPDX) | Apache-2.0 | Copyright (c) 2019-2026 T. Graf | | [Lzma.Net](https://github.com/zcsizmadia/Lzma.Net) | 0BSD | Copyright (c) 2026 Zoltan Csizmadia | | [BouncyCastle.Cryptography](https://github.com/bcgit/bc-csharp) | MIT | Copyright (c) 2000-2026 The Legion of the Bouncy Castle Inc. | @@ -21,7 +20,7 @@ DocFX) are not part of what is shipped. ## The SPDX License List Tazel carries `licenses.json` and `exceptions.json` of the SPDX License List 3.29.0, unmodified, from -<https://github.com/spdx/license-list-data> (tag `v3.29.0`), in `spdx/` of the repository and inside `tazel.dll`. The +<https://github.com/spdx/license-list-data> (tag `v3.29.0`), in `spdx/` of the repository and inside `Progmasoft.Tazel.Packaging.dll`. The list is the work of the SPDX Workgroup, a project of the Linux Foundation; see <https://spdx.org/licenses/>. ## The image of the MicroVM diff --git a/Tazel.slnx b/Tazel.slnx index 842b089..29b2006 100644 --- a/Tazel.slnx +++ b/Tazel.slnx @@ -3,6 +3,7 @@ <Project Path="src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj" /> <Project Path="src/Progmasoft.Tazel/Progmasoft.Tazel.csproj" /> <Project Path="src/Progmasoft.Tazel.Guest/Progmasoft.Tazel.Guest.csproj" /> + <Project Path="src/Progmasoft.Tazel.Packaging/Progmasoft.Tazel.Packaging.csproj" /> <Project Path="src/Progmasoft.Tazel.PluginApi/Progmasoft.Tazel.PluginApi.csproj" /> <Project Path="src/Progmasoft.Tazel.PluginSdk/Progmasoft.Tazel.PluginSdk.csproj" /> <Project Path="src/Progmasoft.Tazel.PluginTemplates/Progmasoft.Tazel.PluginTemplates.csproj" /> diff --git a/docs/README.md b/docs/README.md index be8a1e4..018448e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,6 +7,7 @@ | --- | --- | | [Project files](project-files.md) | `MODULE.csx`, `BUILD.csx` and toolchains, with every setting | | [Plugins](plugins.md) | making, packing and loading plugins, and their build steps | +| [Packaging](packaging.md) | Progmasoft.Tazel.Packaging: reading and writing packages, SPDX license expressions | | [Remote cache](remote-cache.md) | sharing the results of actions between machines through a cache that speaks Bazel's HTTP protocol | | [MicroVM](microvm.md) | the sandbox: what tazel custom runs in, what it needs, and building its image | | [Commands](commands.md) | the commands of `tazel`, their options, and `tazel_options.txt`, `tazel_custom.txt` and `tazel_envs.txt` | diff --git a/docs/packaging.md b/docs/packaging.md new file mode 100644 index 0000000..c0387f2 --- /dev/null +++ b/docs/packaging.md @@ -0,0 +1,41 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> + +# Progmasoft.Tazel.Packaging + +The NuGet package Progmasoft.Tazel.Packaging reads and writes Tazel packages, as NuGet.Packaging does for NuGet. Tazel +itself and the plugin SDK use it; a tool that makes, checks or serves Tazel modules and plugins can use it too. Its +only dependency is Lzma.Net. + +| Type | What it does | +| --- | --- | +| `TazelPackageIdentity` | a group, a name and a SemVer 2.0.0 version, checked; `BaseName` is `$group.$name-$version`, `FileName` adds `.tazel.tar.xz` | +| `TazelPackageArchive` | `Write` makes a `.tazel.tar.xz` that is the same bytes for the same files; `Unpack` refuses links, devices, absolute paths, `..`, entries outside the one top directory, more than 100 000 entries or 1 GiB | +| `Sha256Sums` | the SHA-256 of a file, its line of a `.sha256sums` file, and the sum a `.sha256sums` file gives for a name | +| `TazelPluginManifest` | `tazel-plugin.json`: read and checked, or written with its keys sorted | +| `Spdx.SpdxExpressionParser` | SPDX license expressions to a tree of `SpdxLicense`, `SpdxLicenseReference`, `SpdxWith`, `SpdxAnd` and `SpdxOr` | +| `Spdx.SpdxLicenseList` | the SPDX License List 3.29.0 and the check of an expression against it | + +A problem of a package is a `TazelPackageException`, and a malformed expression an `SpdxExpressionException` whose +`Reason` says what is wrong and `Position` where. + +## SPDX expressions + +```csharp +using Progmasoft.Tazel.Packaging.Spdx; + +var expression = SpdxExpressionParser.Parse("MIT OR GPL-2.0-only WITH Classpath-exception-2.0"); +foreach (var problem in SpdxLicenseList.Current.Check(expression)) +{ + Console.WriteLine($"{problem.Kind} {problem.Id}: {string.Join(", ", problem.Suggestions)}"); +} +``` + +AND binds tighter than OR, and WITH tighter than both; `ToString` writes the parentheses the tree needs and no others, +so a written expression reads back to the same tree. Identifiers and operators are read in any case. The parser never +overflows the stack: parentheses nest at most 64 deep and an expression names at most 1000 licenses. `Check` reports +licenses and exceptions that are not on the list, with up to three close ones, and deprecated ones, with what replaces +them (`GPL-2.0-only` and `GPL-2.0-or-later` for `GPL-2.0`, only `GPL-2.0-or-later` for `GPL-2.0+`). + +The list is `spdx/licenses.json` and `spdx/exceptions.json` of the repository, unmodified; `dotnet run spdx/update.cs -- +<version>` replaces them with those of another release of spdx/license-list-data. diff --git a/docs/project-files.md b/docs/project-files.md index 81c7045..0862c3e 100644 --- a/docs/project-files.md +++ b/docs/project-files.md @@ -49,7 +49,8 @@ execution = Execution.Define(new() { Jobs = 8, KeepGoing = false }); toolchains = Toolchains.Define("//toolchains:clang"); ``` -- `License` is an SPDX license expression, checked against the SPDX License List 3.29.0 that ships with Tazel: +- `License` is an SPDX license expression, checked against the SPDX License List 3.29.0 that ships with Tazel + ([Packaging](packaging.md)): identifiers of the list in any case, joined by `AND` and `OR`, an exception after `WITH`, parentheses around a group and `+` for a version or later, such as `MIT OR Apache-2.0` or `GPL-2.0-or-later WITH Classpath-exception-2.0`. A license of your own is `LicenseRef-<name>`. A misspelt identifier diff --git a/docs/reference/docfx.json b/docs/reference/docfx.json index d3e8516..2d52ba1 100644 --- a/docs/reference/docfx.json +++ b/docs/reference/docfx.json @@ -1,7 +1,7 @@ { "metadata": [ { - "src": [{ "src": "../..", "files": ["src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj", "src/Progmasoft.Tazel.PluginApi/Progmasoft.Tazel.PluginApi.csproj"] }], + "src": [{ "src": "../..", "files": ["src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj", "src/Progmasoft.Tazel.PluginApi/Progmasoft.Tazel.PluginApi.csproj", "src/Progmasoft.Tazel.Packaging/Progmasoft.Tazel.Packaging.csproj"] }], "dest": "api", "properties": { "TargetFramework": "net10.0" } } diff --git a/spdx/update.cs b/spdx/update.cs index c0be546..0e42942 100644 --- a/spdx/update.cs +++ b/spdx/update.cs @@ -7,7 +7,8 @@ // // dotnet run spdx/update.cs -- 3.29.0 // -// Afterwards update the version that SpdxLicensesTests expects and the line of THIRD-PARTY-NOTICES.md. +// Afterwards update the version that the tests expect (SpdxLicensesTests, PackagingTests), THIRD-PARTY-NOTICES.md and +// docs/packaging.md. using System; using System.IO; diff --git a/src/Progmasoft.Tazel.Packaging/Progmasoft.Tazel.Packaging.csproj b/src/Progmasoft.Tazel.Packaging/Progmasoft.Tazel.Packaging.csproj new file mode 100644 index 0000000..389dcb1 --- /dev/null +++ b/src/Progmasoft.Tazel.Packaging/Progmasoft.Tazel.Packaging.csproj @@ -0,0 +1,20 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<!-- Reading and writing Tazel packages, as NuGet.Packaging does for NuGet; the NuGet package Progmasoft.Tazel.Packaging. --> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <RootNamespace>Progmasoft.Tazel.Packaging</RootNamespace> + <IsPackable>true</IsPackable> + <PackageId>Progmasoft.Tazel.Packaging</PackageId> + <Description>Tazel packages: their identity, reproducible .tazel.tar.xz archives and safe unpacking, .sha256sums files, the plugin manifest, and SPDX license expressions with the SPDX License List.</Description> + <PackageTags>tazel;package;archive;spdx;license</PackageTags> + </PropertyGroup> + <ItemGroup> + <PackageReference Include="Lzma.Net" /> + </ItemGroup> + <ItemGroup> + <!-- The SPDX License List 3.29.0, unmodified; spdx/update.cs replaces it. --> + <EmbeddedResource Include="../../spdx/licenses.json" LogicalName="spdx.licenses.json" /> + <EmbeddedResource Include="../../spdx/exceptions.json" LogicalName="spdx.exceptions.json" /> + </ItemGroup> +</Project> diff --git a/src/Progmasoft.Tazel.Packaging/Sha256Sums.cs b/src/Progmasoft.Tazel.Packaging/Sha256Sums.cs new file mode 100644 index 0000000..a3ce2fe --- /dev/null +++ b/src/Progmasoft.Tazel.Packaging/Sha256Sums.cs @@ -0,0 +1,64 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Linq; +using System.Security.Cryptography; + +namespace Progmasoft.Tazel.Packaging; + +/// <summary>The SHA-256 of a file and the <c>.sha256sums</c> file beside it, as <c>sha256sum</c> writes it.</summary> +public static class Sha256Sums +{ + /// <summary>The SHA-256 of <paramref name="file"/> in lower-case hexadecimal.</summary> + public static string Sha256(string file) + { + using var stream = File.OpenRead(file); + return Convert.ToHexStringLower(SHA256.HashData(stream)); + } + + /// <summary>The line of a <c>.sha256sums</c> file for <paramref name="file"/>: the SHA-256, two spaces and the name.</summary> + public static string Line(string file) => $"{Sha256(file)} {Path.GetFileName(file)}\n"; + + /// <summary> + /// The SHA-256 that the <c>.sha256sums</c> text <paramref name="sums"/> gives for <paramref name="name"/>, or null. + /// Lines are <c><sha256> <name></c> or <c><sha256> *<name></c>; blank lines are skipped. + /// </summary> + /// <param name="sums">The text of the file.</param> + /// <param name="name">The name to look up.</param> + /// <param name="shown">How the file is named in a message.</param> + /// <exception cref="TazelPackageException">A line is not a line of sha256sum, or the name is listed twice.</exception> + public static string? SumFor(string sums, string name, string shown) + { + ArgumentNullException.ThrowIfNull(sums); + string? found = null; + var number = 0; + foreach (var raw in sums.Split('\n')) + { + number++; + var line = raw.TrimEnd('\r'); + if (line.Trim().Length == 0) + { + continue; + } + + if (line.Length < 67 || !line[..64].All(Uri.IsHexDigit) || line[64] != ' ' || line[65] is not (' ' or '*')) + { + throw new TazelPackageException($"{shown}:{number}: not a line of sha256sum: '{line}'"); + } + + if (line[66..] == name) + { + if (found is not null) + { + throw new TazelPackageException($"{shown} lists {name} twice"); + } + + found = line[..64].ToLowerInvariant(); + } + } + + return found; + } +} diff --git a/src/Progmasoft.Tazel.Packaging/Spdx/SpdxExpression.cs b/src/Progmasoft.Tazel.Packaging/Spdx/SpdxExpression.cs new file mode 100644 index 0000000..c8864e8 --- /dev/null +++ b/src/Progmasoft.Tazel.Packaging/Spdx/SpdxExpression.cs @@ -0,0 +1,112 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; + +namespace Progmasoft.Tazel.Packaging.Spdx; + +/// <summary> +/// An SPDX license expression, as <see cref="SpdxExpressionParser"/> reads it: a license, a license with an exception, +/// or two expressions joined by <c>AND</c> or <c>OR</c>. <see cref="object.ToString"/> writes it back with the +/// parentheses its structure needs and no others. +/// </summary> +public abstract record SpdxExpression +{ + private protected SpdxExpression() + { + } + + /// <summary>Every license and license reference of the expression, left to right.</summary> + public IEnumerable<SpdxExpression> Leaves() + { + var pending = new Stack<SpdxExpression>(); + pending.Push(this); + while (pending.Count > 0) + { + switch (pending.Pop()) + { + case SpdxAnd and: + pending.Push(and.Right); + pending.Push(and.Left); + break; + case SpdxOr or: + pending.Push(or.Right); + pending.Push(or.Left); + break; + case SpdxWith with: + yield return with.License; + break; + case var leaf: + yield return leaf; + break; + } + } + } + + /// <summary>How tightly the expression binds: OR 1, AND 2, everything else 3.</summary> + private protected abstract int Precedence { get; } + + /// <summary>The expression, in parentheses when it binds more loosely than its place needs.</summary> + private protected static string Within(SpdxExpression part, int place) + { + ArgumentNullException.ThrowIfNull(part); + var text = part.ToString(); + return part.Precedence < place ? $"({text})" : text; + } +} + +/// <summary>A license of the SPDX License List, such as <c>Apache-2.0</c>, or that version or later with <c>+</c>.</summary> +/// <param name="Id">The identifier as written.</param> +/// <param name="OrLater">Whether <c>+</c> follows it.</param> +public sealed record SpdxLicense(string Id, bool OrLater) : SpdxExpression +{ + private protected override int Precedence => 3; + + /// <inheritdoc /> + public override string ToString() => OrLater ? Id + "+" : Id; +} + +/// <summary>A license of one's own: <c>LicenseRef-name</c>, or <c>DocumentRef-document:LicenseRef-name</c>.</summary> +/// <param name="Document">The <c>DocumentRef-</c> part, or null.</param> +/// <param name="License">The <c>LicenseRef-</c> part.</param> +public sealed record SpdxLicenseReference(string? Document, string License) : SpdxExpression +{ + private protected override int Precedence => 3; + + /// <inheritdoc /> + public override string ToString() => Document is null ? License : $"{Document}:{License}"; +} + +/// <summary>A license with an exception, such as <c>GPL-2.0-only WITH Classpath-exception-2.0</c>.</summary> +/// <param name="License">The license: an <see cref="SpdxLicense"/> or an <see cref="SpdxLicenseReference"/>.</param> +/// <param name="Exception">The identifier of the exception.</param> +public sealed record SpdxWith(SpdxExpression License, string Exception) : SpdxExpression +{ + private protected override int Precedence => 3; + + /// <inheritdoc /> + public override string ToString() => $"{License} WITH {Exception}"; +} + +/// <summary>Both expressions apply.</summary> +/// <param name="Left">The first.</param> +/// <param name="Right">The second.</param> +public sealed record SpdxAnd(SpdxExpression Left, SpdxExpression Right) : SpdxExpression +{ + private protected override int Precedence => 2; + + /// <inheritdoc /> + public override string ToString() => $"{Within(Left, 2)} AND {Within(Right, 3)}"; +} + +/// <summary>Either expression applies, as the user chooses.</summary> +/// <param name="Left">The first.</param> +/// <param name="Right">The second.</param> +public sealed record SpdxOr(SpdxExpression Left, SpdxExpression Right) : SpdxExpression +{ + private protected override int Precedence => 1; + + /// <inheritdoc /> + public override string ToString() => $"{Within(Left, 1)} OR {Within(Right, 2)}"; +} diff --git a/src/Progmasoft.Tazel.Packaging/Spdx/SpdxExpressionParser.cs b/src/Progmasoft.Tazel.Packaging/Spdx/SpdxExpressionParser.cs new file mode 100644 index 0000000..adac96d --- /dev/null +++ b/src/Progmasoft.Tazel.Packaging/Spdx/SpdxExpressionParser.cs @@ -0,0 +1,301 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Progmasoft.Tazel.Packaging.Spdx; + +/// <summary>An expression that is not an SPDX license expression.</summary> +public sealed class SpdxExpressionException : FormatException +{ + /// <summary>A malformed expression, and why.</summary> + /// <param name="reason">What is wrong, in a sentence that fits after a colon.</param> + /// <param name="position">The index of the character where the problem is.</param> + public SpdxExpressionException(string reason, int position) + : base($"{reason} (at character {position + 1})") + { + Reason = reason; + Position = position; + } + + /// <summary>Nothing to say.</summary> + public SpdxExpressionException() + { + Reason = ""; + } + + /// <summary>A malformed expression.</summary> + public SpdxExpressionException(string message) + : base(message) + { + Reason = message; + } + + /// <summary>A malformed expression, and what was found.</summary> + public SpdxExpressionException(string message, Exception inner) + : base(message, inner) + { + Reason = message; + } + + /// <summary>What is wrong, without the position.</summary> + public string Reason { get; } + + /// <summary>The index of the character where the problem is.</summary> + public int Position { get; } +} + +/// <summary> +/// Reads SPDX license expressions (SPDX 2.3, Annex D): +/// <c>or = and {OR and}</c>, <c>and = with {AND with}</c>, <c>with = simple [WITH exception] | "(" or ")"</c>, where +/// a simple expression is a license identifier, optionally followed by <c>+</c>, or a <c>LicenseRef-</c> reference. +/// AND binds tighter than OR, WITH tighter than both. The operators are read in any case. It reads the form only: whether +/// an identifier is on the SPDX License List is <see cref="SpdxLicenseList.Check"/>'s question. +/// </summary> +public static class SpdxExpressionParser +{ + /// <summary>The deepest nesting of parentheses it reads; deeper ones are refused, so no input can exhaust the stack.</summary> + public const int MaxDepth = 64; + + /// <summary> + /// The most licenses one expression may name. The tree of a longer one would be deep enough that walking it, to write + /// or compare it, could exhaust the stack. + /// </summary> + public const int MaxLicenses = 1000; + + /// <summary>The expression <paramref name="text"/> writes.</summary> + /// <exception cref="SpdxExpressionException">The text is not an SPDX license expression.</exception> + public static SpdxExpression Parse(string text) + { + ArgumentNullException.ThrowIfNull(text); + var reader = new Reader(Tokens(text), text.Length); + if (reader.AtEnd) + { + throw new SpdxExpressionException("the expression is empty", 0); + } + + var expression = reader.Or(0); + if (!reader.AtEnd) + { + var token = reader.Current; + throw token.Kind == Kind.Close + ? new SpdxExpressionException("a ')' closes no '('", token.Position) + : new SpdxExpressionException($"'{token.Text}' cannot follow; join licenses with AND or OR", token.Position); + } + + return expression; + } + + /// <summary>Reads <paramref name="text"/>, or says why it cannot.</summary> + public static bool TryParse(string text, [NotNullWhen(true)] out SpdxExpression? expression, + [NotNullWhen(false)] out SpdxExpressionException? error) + { + try + { + expression = Parse(text); + error = null; + return true; + } + catch (SpdxExpressionException problem) + { + expression = null; + error = problem; + return false; + } + } + + private enum Kind + { + Word, + Open, + Close, + } + + private readonly record struct Token(Kind Kind, string Text, int Position); + + private static List<Token> Tokens(string text) + { + var tokens = new List<Token>(); + var index = 0; + while (index < text.Length) + { + var character = text[index]; + if (char.IsWhiteSpace(character)) + { + index++; + } + else if (character is '(' or ')') + { + tokens.Add(new Token(character == '(' ? Kind.Open : Kind.Close, character.ToString(), index)); + index++; + } + else if (IsWordCharacter(character)) + { + var start = index; + while (index < text.Length && IsWordCharacter(text[index])) + { + index++; + } + + tokens.Add(new Token(Kind.Word, text[start..index], start)); + } + else + { + throw new SpdxExpressionException( + $"'{character}' cannot be part of an SPDX expression; identifiers are letters, digits, '.' and '-'", index); + } + } + + return tokens; + } + + private static bool IsWordCharacter(char character) => + char.IsAsciiLetterOrDigit(character) || character is '.' or '-' or '+' or ':'; + + private static bool IsIdString(string text) => + text.Length > 0 && text.AsSpan().IndexOfAnyExcept(IdCharacters) < 0; + + private static readonly System.Buffers.SearchValues<char> IdCharacters = + System.Buffers.SearchValues.Create("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-"); + + private static bool IsOperator(Token token, string name) => + token.Kind == Kind.Word && string.Equals(token.Text, name, StringComparison.OrdinalIgnoreCase); + + private sealed class Reader(List<Token> tokens, int length) + { + private int _at; + private int _licenses; + + public bool AtEnd => _at == tokens.Count; + + public Token Current => tokens[_at]; + + public SpdxExpression Or(int depth) + { + var expression = And(depth); + while (!AtEnd && IsOperator(Current, "OR")) + { + Operator("OR"); + expression = new SpdxOr(expression, And(depth)); + } + + return expression; + } + + private SpdxExpression And(int depth) + { + var expression = With(depth); + while (!AtEnd && IsOperator(Current, "AND")) + { + Operator("AND"); + expression = new SpdxAnd(expression, With(depth)); + } + + return expression; + } + + private void Operator(string name) + { + var position = Current.Position; + _at++; + if (AtEnd) + { + throw new SpdxExpressionException($"it ends with {name}; a license must follow it", position); + } + } + + private SpdxExpression With(int depth) + { + if (AtEnd) + { + throw new SpdxExpressionException("a license is missing", length); + } + + var token = tokens[_at++]; + if (token.Kind == Kind.Open) + { + if (depth + 1 > MaxDepth) + { + throw new SpdxExpressionException($"parentheses nest deeper than {MaxDepth}", token.Position); + } + + var inner = Or(depth + 1); + if (AtEnd || Current.Kind != Kind.Close) + { + throw new SpdxExpressionException("a '(' is not closed", token.Position); + } + + _at++; + return inner; + } + + if (token.Kind == Kind.Close || IsOperator(token, "AND") || IsOperator(token, "OR") || IsOperator(token, "WITH")) + { + throw new SpdxExpressionException($"'{token.Text}' stands where a license should", token.Position); + } + + if (++_licenses > MaxLicenses) + { + throw new SpdxExpressionException($"it names more than {MaxLicenses} licenses", token.Position); + } + + var simple = Simple(token); + if (AtEnd || !IsOperator(Current, "WITH")) + { + return simple; + } + + var with = Current.Position; + _at++; + if (AtEnd || Current.Kind != Kind.Word || IsOperator(Current, "AND") || IsOperator(Current, "OR") || + IsOperator(Current, "WITH")) + { + throw new SpdxExpressionException("an exception must follow WITH", with); + } + + var exception = tokens[_at++]; + if (!IsIdString(exception.Text)) + { + throw new SpdxExpressionException( + $"'{exception.Text}' is no exception identifier; it is letters, digits, '.' and '-'", exception.Position); + } + + return new SpdxWith(simple, exception.Text); + } + + private static SpdxExpression Simple(Token token) + { + var text = token.Text; + var colon = text.IndexOf(':', StringComparison.Ordinal); + if (colon >= 0 || text.StartsWith("LicenseRef-", StringComparison.OrdinalIgnoreCase)) + { + var document = colon >= 0 ? text[..colon] : null; + var license = colon >= 0 ? text[(colon + 1)..] : text; + if ((document is not null && !Reference(document, "DocumentRef-")) || !Reference(license, "LicenseRef-")) + { + throw new SpdxExpressionException( + $"'{text}' is no license reference; write LicenseRef-<name> or DocumentRef-<name>:LicenseRef-<name>", + token.Position); + } + + return new SpdxLicenseReference(document, license); + } + + var orLater = text.EndsWith('+'); + var id = orLater ? text[..^1] : text; + if (!IsIdString(id)) + { + throw new SpdxExpressionException( + $"'{text}' is no license identifier; it is letters, digits, '.' and '-', with '+' only at the end", + token.Position); + } + + return new SpdxLicense(id, orLater); + } + + private static bool Reference(string text, string prefix) => + text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && IsIdString(text[prefix.Length..]); + } +} diff --git a/src/Progmasoft.Tazel.Packaging/Spdx/SpdxLicenseList.cs b/src/Progmasoft.Tazel.Packaging/Spdx/SpdxLicenseList.cs new file mode 100644 index 0000000..eb1dec9 --- /dev/null +++ b/src/Progmasoft.Tazel.Packaging/Spdx/SpdxLicenseList.cs @@ -0,0 +1,218 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; + +namespace Progmasoft.Tazel.Packaging.Spdx; + +/// <summary>A license or an exception of the SPDX License List.</summary> +/// <param name="Id">The identifier as the list writes it, such as <c>Apache-2.0</c>.</param> +/// <param name="Name">The full name.</param> +/// <param name="Deprecated">Whether the list keeps it only for old documents.</param> +public sealed record SpdxListEntry(string Id, string Name, bool Deprecated); + +/// <summary>What <see cref="SpdxLicenseList.Check"/> found wrong with one identifier of an expression.</summary> +public enum SpdxProblemKind +{ + /// <summary>The license is not on the list.</summary> + UnknownLicense, + + /// <summary>The exception is not on the list.</summary> + UnknownException, + + /// <summary>The license is on the list but deprecated.</summary> + DeprecatedLicense, + + /// <summary>The exception is on the list but deprecated.</summary> + DeprecatedException, +} + +/// <summary>A problem with one identifier of an expression.</summary> +/// <param name="Kind">What is wrong.</param> +/// <param name="Id">The identifier as written.</param> +/// <param name="Suggestions"> +/// For an unknown identifier, up to three of the list that are close to it; for a deprecated one, what replaces it, such +/// as <c>GPL-2.0-only</c> and <c>GPL-2.0-or-later</c> for <c>GPL-2.0</c>, or only <c>-or-later</c> when it was written +/// with <c>+</c>. May be empty. +/// </param> +public sealed record SpdxProblem(SpdxProblemKind Kind, string Id, IReadOnlyList<string> Suggestions); + +/// <summary> +/// The SPDX License List that ships with this package (<c>licenses.json</c> and <c>exceptions.json</c> of +/// spdx/license-list-data, unmodified). Identifiers match in any case, as the SPDX specification says. +/// </summary> +public sealed class SpdxLicenseList +{ + private static readonly Lazy<SpdxLicenseList> Shipped = new(Load); + + private readonly Dictionary<string, SpdxListEntry> _licenses; + private readonly Dictionary<string, SpdxListEntry> _exceptions; + + private SpdxLicenseList(string version, Dictionary<string, SpdxListEntry> licenses, Dictionary<string, SpdxListEntry> exceptions) + { + Version = version; + _licenses = licenses; + _exceptions = exceptions; + } + + /// <summary>The list that ships with this package.</summary> + public static SpdxLicenseList Current => Shipped.Value; + + /// <summary>The version of the list, such as <c>3.29.0</c>.</summary> + public string Version { get; } + + /// <summary>Every license of the list.</summary> + public IReadOnlyCollection<SpdxListEntry> Licenses => _licenses.Values; + + /// <summary>Every exception of the list.</summary> + public IReadOnlyCollection<SpdxListEntry> Exceptions => _exceptions.Values; + + /// <summary>The license <paramref name="id"/>, in any case, or null.</summary> + public SpdxListEntry? License(string id) => _licenses.GetValueOrDefault(id); + + /// <summary>The exception <paramref name="id"/>, in any case, or null.</summary> + public SpdxListEntry? Exception(string id) => _exceptions.GetValueOrDefault(id); + + /// <summary> + /// The identifiers of <paramref name="expression"/> that are not on the list or are deprecated, left to right. A + /// <see cref="SpdxLicenseReference"/> names a license of its author's own and is never a problem. + /// </summary> + public IReadOnlyList<SpdxProblem> Check(SpdxExpression expression) + { + ArgumentNullException.ThrowIfNull(expression); + var problems = new List<SpdxProblem>(); + var pending = new Stack<SpdxExpression>(); + pending.Push(expression); + while (pending.Count > 0) + { + switch (pending.Pop()) + { + case SpdxOr or: + pending.Push(or.Right); + pending.Push(or.Left); + break; + case SpdxAnd and: + pending.Push(and.Right); + pending.Push(and.Left); + break; + case SpdxWith with: + pending.Push(new ExceptionMark(with.Exception)); + pending.Push(with.License); + break; + case SpdxLicense license: + CheckLicense(license, problems); + break; + case ExceptionMark mark: + CheckException(mark.Id, problems); + break; + } + } + + return problems; + } + + private void CheckLicense(SpdxLicense license, List<SpdxProblem> problems) + { + if (License(license.Id) is not { } entry) + { + problems.Add(new SpdxProblem(SpdxProblemKind.UnknownLicense, license.Id, Closest(license.Id, _licenses))); + } + else if (entry.Deprecated) + { + var forms = license.OrLater ? new[] { "-or-later" } : ["-only", "-or-later"]; + var replacements = forms.Select(form => License(entry.Id + form)).OfType<SpdxListEntry>() + .Where(replacement => !replacement.Deprecated).Select(replacement => replacement.Id).ToList(); + problems.Add(new SpdxProblem(SpdxProblemKind.DeprecatedLicense, license.ToString(), replacements)); + } + } + + private void CheckException(string id, List<SpdxProblem> problems) + { + if (Exception(id) is not { } entry) + { + problems.Add(new SpdxProblem(SpdxProblemKind.UnknownException, id, Closest(id, _exceptions))); + } + else if (entry.Deprecated) + { + problems.Add(new SpdxProblem(SpdxProblemKind.DeprecatedException, id, [])); + } + } + + /// <summary>A stand-in on the stack of <see cref="Check"/> for the exception of a WITH.</summary> + private sealed record ExceptionMark(string Id) : SpdxExpression + { + private protected override int Precedence => 3; + } + + /// <summary>Up to three identifiers of the table that are not deprecated and close to <paramref name="id"/>.</summary> + private static List<string> Closest(string id, Dictionary<string, SpdxListEntry> table) + { + var upper = id.ToUpperInvariant(); + var limit = Math.Max(2, id.Length / 4); + return table.Values.Where(entry => !entry.Deprecated) + .Select(entry => (entry.Id, Distance: Distance(upper, entry.Id.ToUpperInvariant(), limit))) + .Where(candidate => candidate.Distance <= limit) + .OrderBy(candidate => candidate.Distance).ThenBy(candidate => candidate.Id, StringComparer.Ordinal) + .Take(3).Select(candidate => candidate.Id).ToList(); + } + + /// <summary>The edit distance of two strings, or more than <paramref name="limit"/> as soon as it must be.</summary> + private static int Distance(string a, string b, int limit) + { + if (Math.Abs(a.Length - b.Length) > limit) + { + return limit + 1; + } + + var previous = new int[b.Length + 1]; + var current = new int[b.Length + 1]; + for (var j = 0; j <= b.Length; j++) + { + previous[j] = j; + } + + for (var i = 1; i <= a.Length; i++) + { + current[0] = i; + for (var j = 1; j <= b.Length; j++) + { + var cost = a[i - 1] == b[j - 1] ? 0 : 1; + current[j] = Math.Min(Math.Min(current[j - 1] + 1, previous[j] + 1), previous[j - 1] + cost); + } + + (previous, current) = (current, previous); + } + + return previous[b.Length]; + } + + private static SpdxLicenseList Load() + { + using var licenses = JsonDocument.Parse(Resource("spdx.licenses.json")); + using var exceptions = JsonDocument.Parse(Resource("spdx.exceptions.json")); + var version = licenses.RootElement.GetProperty("licenseListVersion").GetString() ?? ""; + return new SpdxLicenseList(version, Table(licenses, "licenses", "licenseId"), + Table(exceptions, "exceptions", "licenseExceptionId")); + } + + private static Dictionary<string, SpdxListEntry> Table(JsonDocument document, string list, string idProperty) + { + var table = new Dictionary<string, SpdxListEntry>(StringComparer.OrdinalIgnoreCase); + foreach (var item in document.RootElement.GetProperty(list).EnumerateArray()) + { + var id = item.GetProperty(idProperty).GetString() ?? ""; + table[id] = new SpdxListEntry(id, item.GetProperty("name").GetString() ?? id, + item.GetProperty("isDeprecatedLicenseId").GetBoolean()); + } + + return table; + } + + private static Stream Resource(string name) => + typeof(SpdxLicenseList).Assembly.GetManifestResourceStream(name) + ?? throw new InvalidOperationException($"the SPDX License List ({name}) is missing from Progmasoft.Tazel.Packaging"); +} diff --git a/src/Progmasoft.Tazel.Packaging/TazelPackageArchive.cs b/src/Progmasoft.Tazel.Packaging/TazelPackageArchive.cs new file mode 100644 index 0000000..d16e1ff --- /dev/null +++ b/src/Progmasoft.Tazel.Packaging/TazelPackageArchive.cs @@ -0,0 +1,222 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Formats.Tar; +using System.IO; +using System.Linq; +using LzmaNet; + +namespace Progmasoft.Tazel.Packaging; + +/// <summary> +/// The archive of a Tazel package, <c>$group.$name-$version.tazel.tar.xz</c>: the files of the package below one +/// directory of that name less the extension. Modules and plugins are both written this way. +/// </summary> +/// <remarks> +/// An archive is the same bytes for the same files: entries are sorted, owned by no one, dated at the epoch, and either +/// <c>0644</c> or, for an executable file, <c>0755</c>; xz compresses with one thread. Unpacking refuses links, devices, +/// absolute paths, <c>..</c>, entries outside the one top directory, and archives over <see cref="MaxUnpackedBytes"/> or +/// <see cref="MaxEntries"/>. +/// </remarks> +public static class TazelPackageArchive +{ + /// <summary>The extension of an archive.</summary> + public const string Extension = ".tazel.tar.xz"; + + /// <summary>The most an archive may unpack to; a larger one is refused before it fills the disk.</summary> + public const long MaxUnpackedBytes = 1L << 30; + + /// <summary>The most entries an archive may hold.</summary> + public const int MaxEntries = 100_000; + + private const UnixFileMode FileMode = + UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead; + + private const UnixFileMode ExecutableMode = FileMode | + UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute; + + private const UnixFileMode DirectoryMode = ExecutableMode | UnixFileMode.UserWrite; + + /// <summary> + /// Writes <paramref name="files"/>, paths with <c>/</c> below <paramref name="root"/>, into <paramref name="archive"/> + /// below the directory <paramref name="baseName"/>. The archive appears whole or not at all. + /// </summary> + public static void Write(string root, string baseName, string archive, IReadOnlyList<string> files) + { + ArgumentNullException.ThrowIfNull(files); + ArgumentNullException.ThrowIfNull(archive); + var directory = Path.GetDirectoryName(Path.GetFullPath(archive))!; + Directory.CreateDirectory(directory); + var temporary = Path.Combine(directory, $".{Path.GetFileName(archive)}.{Guid.NewGuid():N}.partial"); + try + { + using (var output = File.Create(temporary)) + using (var xz = new XzCompressStream(output, new XzCompressOptions { Threads = 1 }, leaveOpen: false)) + using (var tar = new TarWriter(xz, TarEntryFormat.Ustar, leaveOpen: false)) + { + foreach (var (path, isDirectory) in PathsAndDirectories(files)) + { + var name = path.Length == 0 ? $"{baseName}/" : isDirectory ? $"{baseName}/{path}/" : $"{baseName}/{path}"; + var entry = new UstarTarEntry(isDirectory ? TarEntryType.Directory : TarEntryType.RegularFile, name) + { + ModificationTime = DateTimeOffset.UnixEpoch, + Uid = 0, + Gid = 0, + UserName = "", + GroupName = "", + }; + var source = Path.Combine(root, path); + entry.Mode = isDirectory ? DirectoryMode : IsExecutable(source) ? ExecutableMode : FileMode; + if (isDirectory) + { + tar.WriteEntry(entry); + } + else + { + using var data = File.OpenRead(source); + entry.DataStream = data; + tar.WriteEntry(entry); + } + } + } + + File.Move(temporary, archive, overwrite: true); + } + finally + { + File.Delete(temporary); + } + } + + /// <summary> + /// Unpacks <paramref name="archive"/> into <paramref name="destination"/>, which must not exist, and returns the top + /// directory in it, which must hold <paramref name="requiredFile"/>. + /// </summary> + /// <exception cref="TazelPackageException">The archive cannot be unpacked or is not a package; the message says why.</exception> + public static string Unpack(string archive, string destination, string requiredFile) + { + ArgumentNullException.ThrowIfNull(archive); + ArgumentNullException.ThrowIfNull(destination); + ArgumentNullException.ThrowIfNull(requiredFile); + var shown = Path.GetFileName(archive); + var parent = Path.GetDirectoryName(Path.GetFullPath(destination))!; + Directory.CreateDirectory(parent); + var work = Path.Combine(parent, $".unpack-{Guid.NewGuid():N}"); + Directory.CreateDirectory(work); + try + { + string? top = null; + long total = 0; + var entries = 0; + using (var input = File.OpenRead(archive)) + using (var xz = new XzDecompressStream(input, new XzDecompressOptions(), leaveOpen: false)) + using (var tar = new TarReader(xz)) + { + while (tar.GetNextEntry() is { } entry) + { + if (++entries > MaxEntries) + { + throw new TazelPackageException($"{shown} holds more than {MaxEntries} entries"); + } + + var parts = PartsOf(entry, shown); + top ??= parts[0]; + if (parts[0] != top) + { + throw new TazelPackageException($"{shown}: '{entry.Name}' is not below {top}/"); + } + + total += Extract(entry, Path.Combine(work, Path.Combine(parts)), shown); + if (total > MaxUnpackedBytes) + { + throw new TazelPackageException($"{shown} unpacks to more than {MaxUnpackedBytes} bytes"); + } + } + } + + CheckUnpacked(work, top, requiredFile, shown); + Directory.Move(work, destination); + return Path.Combine(destination, top); + } + catch (Exception error) when (error is IOException or InvalidDataException or FormatException) + { + throw new TazelPackageException($"{shown} could not be unpacked: {error.Message}", error); + } + finally + { + if (Directory.Exists(work)) + { + Directory.Delete(work, recursive: true); + } + } + } + + private static void CheckUnpacked(string work, [NotNull] string? top, string requiredFile, string shown) + { + if (top is null) + { + throw new TazelPackageException($"{shown} is empty"); + } + + if (!File.Exists(Path.Combine(work, top, requiredFile))) + { + throw new TazelPackageException($"{shown} has no {top}/{requiredFile}"); + } + } + + private static string[] PartsOf(TarEntry entry, string shown) + { + var name = entry.Name.TrimEnd('/'); + var parts = name.Split('/'); + return name.Length == 0 || name.StartsWith('/') || name.Contains('\\', StringComparison.Ordinal) || + parts.Any(part => part is "" or "." or "..") + ? throw new TazelPackageException($"{shown}: '{entry.Name}' is not a path inside the archive") + : parts; + } + + private static long Extract(TarEntry entry, string target, string shown) + { + if (entry.EntryType == TarEntryType.Directory) + { + Directory.CreateDirectory(target); + return 0; + } + + if (entry.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile)) + { + throw new TazelPackageException($"{shown}: '{entry.Name}' is a {entry.EntryType}; an archive holds only files"); + } + + // The size is checked before the bytes are written, so a huge entry is refused unwritten. + if (entry.Length > MaxUnpackedBytes) + { + throw new TazelPackageException($"{shown} unpacks to more than {MaxUnpackedBytes} bytes"); + } + + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + entry.ExtractToFile(target, overwrite: false); + return entry.Length; + } + + private static bool IsExecutable(string file) => + !OperatingSystem.IsWindows() && (File.GetUnixFileMode(file) & UnixFileMode.UserExecute) != 0; + + private static IEnumerable<(string Path, bool IsDirectory)> PathsAndDirectories(IReadOnlyList<string> files) + { + var directories = new SortedSet<string>(StringComparer.Ordinal) { "" }; + foreach (var file in files) + { + var parts = file.Split('/'); + for (var depth = 1; depth < parts.Length; depth++) + { + directories.Add(string.Join('/', parts.Take(depth))); + } + } + + return directories.Select(d => (d, true)).Concat(files.Select(f => (f, false))) + .OrderBy(entry => entry.Item1, StringComparer.Ordinal); + } +} diff --git a/src/Progmasoft.Tazel.Packaging/TazelPackageIdentity.cs b/src/Progmasoft.Tazel.Packaging/TazelPackageIdentity.cs new file mode 100644 index 0000000..e4ccf35 --- /dev/null +++ b/src/Progmasoft.Tazel.Packaging/TazelPackageIdentity.cs @@ -0,0 +1,100 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Linq; +using System.Text.RegularExpressions; + +namespace Progmasoft.Tazel.Packaging; + +/// <summary>A package that cannot be read, written or trusted; the message says why.</summary> +public sealed class TazelPackageException : Exception +{ + /// <summary>A problem of a package.</summary> + public TazelPackageException(string message) + : base(message) + { + } + + /// <summary>Nothing to say.</summary> + public TazelPackageException() + { + } + + /// <summary>A problem of a package, and what was found.</summary> + public TazelPackageException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// <summary> +/// Who a package is: a group such as <c>com.example</c>, a name and a SemVer 2.0.0 version. Its archive is +/// <see cref="FileName"/>, <c>$group.$name-$version.tazel.tar.xz</c>. +/// </summary> +public sealed partial record TazelPackageIdentity +{ + /// <summary>A package, once its parts are checked.</summary> + /// <exception cref="TazelPackageException">A part is not what it must be; the message says which.</exception> + public TazelPackageIdentity(string group, string name, string version) + { + ArgumentNullException.ThrowIfNull(group); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(version); + if (!IsGroup(group)) + { + throw new TazelPackageException($"the group '{group}' must be names joined by dots, such as com.example"); + } + + if (!IsName(name)) + { + throw new TazelPackageException($"the name '{name}' must be letters, digits and _ + . -"); + } + + if (!IsSemVer(version)) + { + throw new TazelPackageException($"'{version}' is not a SemVer version such as 1.2.0"); + } + + Group = group; + Name = name; + Version = version; + } + + /// <summary>The group, such as <c>com.example</c>.</summary> + public string Group { get; } + + /// <summary>The name.</summary> + public string Name { get; } + + /// <summary>The SemVer 2.0.0 version, such as <c>1.2.0</c> or <c>2.0.0-rc.1</c>.</summary> + public string Version { get; } + + /// <summary><c>$group.$name-$version</c>: the name of the archive without its extension, and its top directory.</summary> + public string BaseName => $"{Group}.{Name}-{Version}"; + + /// <summary>The file name of the archive.</summary> + public string FileName => BaseName + TazelPackageArchive.Extension; + + /// <summary>Whether <paramref name="name"/> is a name: letters, digits and <c>_ + . -</c>.</summary> + public static bool IsName(string name) => name is not null && NamePattern().IsMatch(name); + + /// <summary>Whether <paramref name="group"/> is names of letters, digits, <c>_</c> and <c>-</c> joined by dots.</summary> + public static bool IsGroup(string group) => + !string.IsNullOrEmpty(group) && group.Split('.').All(part => + part.Length > 0 && part.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-')); + + /// <summary>Whether <paramref name="version"/> is a SemVer 2.0.0 version, as the expression of semver.org says.</summary> + public static bool IsSemVer(string version) => version is not null && SemVerPattern().IsMatch(version); + + /// <inheritdoc /> + public override string ToString() => BaseName; + + [GeneratedRegex("^[A-Za-z0-9_+.-]+$")] + private static partial Regex NamePattern(); + + // The expression semver.org gives for SemVer 2.0.0. + [GeneratedRegex(@"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$", + RegexOptions.CultureInvariant)] + private static partial Regex SemVerPattern(); +} diff --git a/src/Progmasoft.Tazel.Packaging/TazelPluginManifest.cs b/src/Progmasoft.Tazel.Packaging/TazelPluginManifest.cs new file mode 100644 index 0000000..799a20e --- /dev/null +++ b/src/Progmasoft.Tazel.Packaging/TazelPluginManifest.cs @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Text.Json; + +namespace Progmasoft.Tazel.Packaging; + +/// <summary> +/// The manifest of a plugin, <c>tazel-plugin.json</c> at the top of its archive: who the plugin is, the plugin API it +/// was built against and the assembly Tazel loads first. +/// </summary> +/// <param name="Group">The group, such as <c>com.example</c>.</param> +/// <param name="Name">The name.</param> +/// <param name="Version">The SemVer version.</param> +/// <param name="PluginApi">The version of Progmasoft.Tazel.PluginApi it was built against.</param> +/// <param name="EntryAssembly">The file name of the assembly that holds the plugin, at the top of the archive.</param> +public sealed record TazelPluginManifest(string Group, string Name, string Version, string PluginApi, string EntryAssembly) +{ + /// <summary>The name of the manifest file.</summary> + public const string FileName = "tazel-plugin.json"; + + private static readonly JsonSerializerOptions ReadOptions = + new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, AllowTrailingCommas = false }; + + private static readonly JsonSerializerOptions WriteOptions = new() { WriteIndented = true }; + + /// <summary>The identity of the plugin's package.</summary> + /// <exception cref="TazelPackageException">The group, name or version is not what it must be.</exception> + public TazelPackageIdentity Identity => new(Group, Name, Version); + + /// <summary>Reads a manifest and checks it with <see cref="Check"/>.</summary> + /// <param name="json">The text of <c>tazel-plugin.json</c>.</param> + /// <param name="shown">How the manifest is named in a message.</param> + /// <exception cref="TazelPackageException">The text is not a manifest, or the manifest is not valid.</exception> + public static TazelPluginManifest Read(string json, string shown) + { + ArgumentNullException.ThrowIfNull(json); + TazelPluginManifest? manifest; + try + { + manifest = JsonSerializer.Deserialize<TazelPluginManifest>(json, ReadOptions); + } + catch (JsonException error) + { + throw new TazelPackageException($"{shown}: {FileName} cannot be read: {error.Message}", error); + } + + if (manifest is null) + { + throw new TazelPackageException($"{shown}: {FileName} is empty"); + } + + manifest.Check(shown); + return manifest; + } + + /// <summary> + /// Checks the manifest: a group of names joined by dots, a name, a SemVer version, a plugin API version and an entry + /// assembly that is a <c>.dll</c> at the top of the archive. Whether the plugin API matches a Tazel is Tazel's question. + /// </summary> + /// <exception cref="TazelPackageException">A field is not what it must be; the message says which.</exception> + public void Check(string shown) + { + if (string.IsNullOrEmpty(Group) || !TazelPackageIdentity.IsGroup(Group)) + { + throw new TazelPackageException($"{shown}: the group '{Group}' of its manifest is not names joined by dots"); + } + + if (string.IsNullOrEmpty(Name) || !TazelPackageIdentity.IsName(Name)) + { + throw new TazelPackageException($"{shown}: the name '{Name}' of its manifest is not a name"); + } + + if (!TazelPackageIdentity.IsSemVer(Version ?? "")) + { + throw new TazelPackageException($"{shown}: '{Version}' is not a SemVer version"); + } + + if (!System.Version.TryParse(PluginApi ?? "", out _)) + { + throw new TazelPackageException($"{shown}: '{PluginApi}' is not the version of a plugin API"); + } + + if (string.IsNullOrEmpty(EntryAssembly) || EntryAssembly.Contains('/', StringComparison.Ordinal) || + EntryAssembly.Contains('\\', StringComparison.Ordinal) || !EntryAssembly.EndsWith(".dll", StringComparison.Ordinal)) + { + throw new TazelPackageException($"{shown}: the entry assembly '{EntryAssembly}' is not a .dll at the top"); + } + } + + /// <summary>The manifest as <c>tazel-plugin.json</c> holds it: its keys sorted, indented, with a final newline.</summary> + public string ToJson() + { + var fields = new SortedDictionary<string, string>(StringComparer.Ordinal) + { + ["entryAssembly"] = EntryAssembly, + ["group"] = Group, + ["name"] = Name, + ["pluginApi"] = PluginApi, + ["version"] = Version, + }; + return JsonSerializer.Serialize(fields, WriteOptions) + "\n"; + } +} diff --git a/src/Progmasoft.Tazel.PluginSdk/PackTazelPlugin.cs b/src/Progmasoft.Tazel.PluginSdk/PackTazelPlugin.cs index fef53df..7539a16 100644 --- a/src/Progmasoft.Tazel.PluginSdk/PackTazelPlugin.cs +++ b/src/Progmasoft.Tazel.PluginSdk/PackTazelPlugin.cs @@ -5,10 +5,9 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text.Json; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; -using Progmasoft.Tazel.Archive; +using Progmasoft.Tazel.Packaging; namespace Progmasoft.Tazel.PluginSdk; @@ -76,23 +75,15 @@ public sealed class PackTazelPlugin : Task File.Copy(Path.Combine(OutputDirectory, file), Path.Combine(staging, file)); } - var manifest = new SortedDictionary<string, string>(StringComparer.Ordinal) - { - ["entryAssembly"] = EntryAssembly, - ["group"] = Group, - ["name"] = Name, - ["pluginApi"] = PluginApiVersion, - ["version"] = Version, - }; - File.WriteAllText(Path.Combine(staging, "tazel-plugin.json"), - JsonSerializer.Serialize(manifest, new JsonSerializerOptions { WriteIndented = true }) + "\n"); - files.Add("tazel-plugin.json"); + var manifest = new TazelPluginManifest(Group, Name, Version, PluginApiVersion, EntryAssembly); + File.WriteAllText(Path.Combine(staging, TazelPluginManifest.FileName), manifest.ToJson()); + files.Add(TazelPluginManifest.FileName); files.Sort(StringComparer.Ordinal); - var baseName = $"{Group}.{Name}-{Version}"; - Archive = Path.Combine(PackageOutputPath, baseName + ".tazel.tar.xz"); - ReproducibleArchive.Write(staging, baseName, Archive, files); - File.WriteAllText(Archive + ".sha256sums", ReproducibleArchive.SumsLine(Archive)); + var identity = manifest.Identity; + Archive = Path.Combine(PackageOutputPath, identity.FileName); + TazelPackageArchive.Write(staging, identity.BaseName, Archive, files); + File.WriteAllText(Archive + ".sha256sums", Sha256Sums.Line(Archive)); Log.LogMessage(MessageImportance.High, $"Tazel plugin: {Archive}"); return true; } @@ -101,6 +92,11 @@ public sealed class PackTazelPlugin : Task Log.LogError($"The plugin archive could not be written: {error.Message}"); return false; } + catch (TazelPackageException error) + { + Log.LogError($"The plugin cannot be packed: {error.Message}"); + return false; + } finally { Directory.Delete(staging, recursive: true); diff --git a/src/Progmasoft.Tazel.PluginSdk/Progmasoft.Tazel.PluginSdk.csproj b/src/Progmasoft.Tazel.PluginSdk/Progmasoft.Tazel.PluginSdk.csproj index e72f031..ecc6505 100644 --- a/src/Progmasoft.Tazel.PluginSdk/Progmasoft.Tazel.PluginSdk.csproj +++ b/src/Progmasoft.Tazel.PluginSdk/Progmasoft.Tazel.PluginSdk.csproj @@ -18,7 +18,7 @@ <NoWarn>$(NoWarn);NU5100;NU5128</NoWarn> </PropertyGroup> <ItemGroup> - <Compile Include="../Shared/*.cs" LinkBase="Shared" /> + <ProjectReference Include="../Progmasoft.Tazel.Packaging/Progmasoft.Tazel.Packaging.csproj" PrivateAssets="all" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.Build.Utilities.Core" ExcludeAssets="runtime" PrivateAssets="all" /> @@ -38,6 +38,7 @@ <ItemGroup> <None Include="$(_TazelSdkProps)" Pack="true" PackagePath="Sdk/Sdk.props" /> <None Include="$(OutputPath)Progmasoft.Tazel.PluginSdk.dll" Pack="true" PackagePath="tasks/net10.0/" /> + <None Include="$(OutputPath)Progmasoft.Tazel.Packaging.dll" Pack="true" PackagePath="tasks/net10.0/" /> <None Include="$(OutputPath)LzmaNet.dll" Pack="true" PackagePath="tasks/net10.0/" /> </ItemGroup> </Target> diff --git a/src/Progmasoft.Tazel/Archive/ModuleArchive.cs b/src/Progmasoft.Tazel/Archive/ModuleArchive.cs index a68c21d..6f69237 100644 --- a/src/Progmasoft.Tazel/Archive/ModuleArchive.cs +++ b/src/Progmasoft.Tazel/Archive/ModuleArchive.cs @@ -3,11 +3,9 @@ using System; using System.Collections.Generic; -using System.Formats.Tar; using System.IO; using System.Linq; -using System.Security.Cryptography; -using LzmaNet; +using Progmasoft.Tazel.Packaging; using Progmasoft.Tazel.Project; namespace Progmasoft.Tazel.Archive; @@ -20,13 +18,7 @@ namespace Progmasoft.Tazel.Archive; internal static class ModuleArchive { /// <summary>The extension of an archive.</summary> - public const string Extension = ".tazel.tar.xz"; - - /// <summary>The most an archive may unpack to; a larger one is refused before it fills the disk.</summary> - public const long MaxUnpackedBytes = 1L << 30; - - /// <summary>The most entries an archive may hold.</summary> - public const int MaxEntries = 100_000; + public const string Extension = TazelPackageArchive.Extension; /// <summary><c>$group.$module-$version</c>, the name of an archive without its extension.</summary> public static string BaseName(string group, string module, string version) => $"{group}.{module}-{version}"; @@ -76,7 +68,7 @@ internal static class ModuleArchive /// <summary>Writes <paramref name="files"/> of the module at <paramref name="root"/> below <paramref name="baseName"/>.</summary> public static void Write(string root, string baseName, string archive, IReadOnlyList<string> files) => - ReproducibleArchive.Write(root, baseName, archive, files); + TazelPackageArchive.Write(root, baseName, archive, files); /// <summary> /// The directory a <c>.unpacked</c> marker below <paramref name="destination"/> names, or null when there is no @@ -103,129 +95,35 @@ internal static class ModuleArchive public static void WriteMarker(string destination, string directory) => System.IO.File.WriteAllText(Path.Combine(destination, ".unpacked"), Path.GetFileName(directory)); - /// <summary>An unpacked archive has one top directory, and the file it must hold in it.</summary> - private static void CheckUnpacked(string work, [System.Diagnostics.CodeAnalysis.NotNull] string? top, string requiredFile, string shown) - { - if (top is null) - { - throw new ProjectException($"{shown} is empty"); - } - - if (!System.IO.File.Exists(Path.Combine(work, top, requiredFile))) - { - throw new ProjectException($"{shown} has no {top}/{requiredFile}"); - } - } - - /// <summary>The parts of the path of an entry, which must stay inside the archive.</summary> - private static string[] PartsOf(TarEntry entry, string shown) - { - var name = entry.Name.TrimEnd('/'); - var parts = name.Split('/'); - return name.Length == 0 || name.StartsWith('/') || name.Contains('\\', StringComparison.Ordinal) || - parts.Any(part => part is "" or "." or "..") - ? throw new ProjectException($"{shown}: '{entry.Name}' is not a path inside the archive") - : parts; - } - - /// <summary>Writes a directory or a file of the archive; anything else is refused. Returns the bytes written.</summary> - private static long Extract(TarEntry entry, string target, string shown) - { - if (entry.EntryType == TarEntryType.Directory) - { - Directory.CreateDirectory(target); - return 0; - } - - if (entry.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile)) - { - throw new ProjectException($"{shown}: '{entry.Name}' is a {entry.EntryType}; an archive holds only files"); - } - - // The size is checked before the bytes are written, so a huge entry is refused unwritten. - if (entry.Length > MaxUnpackedBytes) - { - throw new ProjectException($"{shown} unpacks to more than {MaxUnpackedBytes} bytes"); - } - - Directory.CreateDirectory(Path.GetDirectoryName(target)!); - entry.ExtractToFile(target, overwrite: false); - return entry.Length; - } - /// <summary> /// Unpacks <paramref name="archive"/> into <paramref name="destination"/>, which must not exist, and returns the /// directory of the module in it. Every entry must be below one top directory; links, devices, absolute paths and - /// <c>..</c> are refused, as are archives over <see cref="MaxUnpackedBytes"/> or <see cref="MaxEntries"/>. + /// <c>..</c> are refused, as are archives over <see cref="TazelPackageArchive.MaxUnpackedBytes"/> or <see cref="TazelPackageArchive.MaxEntries"/>. /// </summary> public static string Unpack(string archive, string destination) => Unpack(archive, destination, ModuleFiles.ModuleFile); /// <inheritdoc cref="Unpack(string, string)"/> public static string Unpack(string archive, string destination, string requiredFile) { - var shown = Path.GetFileName(archive); - var parent = Path.GetDirectoryName(Path.GetFullPath(destination))!; - Directory.CreateDirectory(parent); - var work = Path.Combine(parent, $".unpack-{Guid.NewGuid():N}"); - Directory.CreateDirectory(work); try { - string? top = null; - long total = 0; - var entries = 0; - using (var input = System.IO.File.OpenRead(archive)) - using (var xz = new XzDecompressStream(input, new XzDecompressOptions(), leaveOpen: false)) - using (var tar = new TarReader(xz)) - { - while (tar.GetNextEntry() is { } entry) - { - if (++entries > MaxEntries) - { - throw new ProjectException($"{shown} holds more than {MaxEntries} entries"); - } - - var parts = PartsOf(entry, shown); - top ??= parts[0]; - if (parts[0] != top) - { - throw new ProjectException($"{shown}: '{entry.Name}' is not below {top}/"); - } - - total += Extract(entry, Path.Combine(work, Path.Combine(parts)), shown); - if (total > MaxUnpackedBytes) - { - throw new ProjectException($"{shown} unpacks to more than {MaxUnpackedBytes} bytes"); - } - } - } - - CheckUnpacked(work, top, requiredFile, shown); - Directory.Move(work, destination); - return Path.Combine(destination, top); + return TazelPackageArchive.Unpack(archive, destination, requiredFile); } - catch (Exception error) when (error is IOException or InvalidDataException or FormatException) + catch (TazelPackageException error) { - throw new ProjectException($"{shown} could not be unpacked: {error.Message}", error); - } - finally - { - if (Directory.Exists(work)) - { - Directory.Delete(work, recursive: true); - } + throw new ProjectException(error.Message, error); } } - } /// <summary>The SHA-256 of an archive and the <c>.sha256sums</c> file beside it, as <c>sha256sum</c> writes it.</summary> internal static class Sha256Sums { /// <summary>The SHA-256 of <paramref name="file"/> in lower-case hexadecimal.</summary> - public static string Sha256(string file) => ReproducibleArchive.Sha256(file); + public static string Sha256(string file) => Packaging.Sha256Sums.Sha256(file); /// <summary>The line of a <c>.sha256sums</c> file for <paramref name="file"/>.</summary> - public static string SumsLine(string file) => ReproducibleArchive.SumsLine(file); + public static string SumsLine(string file) => Packaging.Sha256Sums.Line(file); /// <summary> /// The SHA-256 that the <c>.sha256sums</c> text <paramref name="sums"/> gives for <paramref name="name"/>. Lines are @@ -234,34 +132,13 @@ internal static class Sha256Sums /// </summary> public static string? SumFor(string sums, string name, string shown) { - ArgumentNullException.ThrowIfNull(sums); - string? found = null; - var number = 0; - foreach (var raw in sums.Split('\n')) + try { - number++; - var line = raw.TrimEnd('\r'); - if (line.Trim().Length == 0) - { - continue; - } - - if (line.Length < 67 || !line[..64].All(Uri.IsHexDigit) || line[64] != ' ' || line[65] is not (' ' or '*')) - { - throw new ProjectException($"{shown}:{number}: not a line of sha256sum: '{line}'"); - } - - if (line[66..] == name) - { - if (found is not null) - { - throw new ProjectException($"{shown} lists {name} twice"); - } - - found = line[..64].ToLowerInvariant(); - } + return Packaging.Sha256Sums.SumFor(sums, name, shown); + } + catch (TazelPackageException error) + { + throw new ProjectException(error.Message, error); } - - return found; } } diff --git a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj index aeb026e..8a9fa27 100644 --- a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj +++ b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj @@ -20,18 +20,15 @@ <PackageReference Include="Spectre.Console" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" /> <PackageReference Include="NuGet.Versioning" /> - <PackageReference Include="Tethys.SPDX.ExpressionParser" /> <PackageReference Include="Lzma.Net" /> <PackageReference Include="BouncyCastle.Cryptography" /> </ItemGroup> + <ItemGroup> + <ProjectReference Include="../Progmasoft.Tazel.Packaging/Progmasoft.Tazel.Packaging.csproj" /> + </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Progmasoft.Tazel.Tests" /> <InternalsVisibleTo Include="Progmasoft.Tazel.Benchmarks" /> <InternalsVisibleTo Include="Progmasoft.Tazel.Fuzz" /> </ItemGroup> - <ItemGroup> - <!-- The SPDX License List the License of a module is checked against; spdx/update.cs replaces it. --> - <EmbeddedResource Include="../../spdx/licenses.json" LogicalName="spdx.licenses.json" /> - <EmbeddedResource Include="../../spdx/exceptions.json" LogicalName="spdx.exceptions.json" /> - </ItemGroup> </Project> diff --git a/src/Progmasoft.Tazel/Project/Plugins.cs b/src/Progmasoft.Tazel/Project/Plugins.cs index b5eae87..52e4d2c 100644 --- a/src/Progmasoft.Tazel/Project/Plugins.cs +++ b/src/Progmasoft.Tazel/Project/Plugins.cs @@ -7,29 +7,20 @@ using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; -using System.Text.Json; -using NuGet.Versioning; using Progmasoft.Tazel.Archive; using Progmasoft.Tazel.Dsl.Build.Prelude; using Progmasoft.Tazel.Dsl.Common; using Progmasoft.Tazel.Dsl.Module.Prelude; using Progmasoft.Tazel.Label; +using Progmasoft.Tazel.Packaging; using Progmasoft.Tazel.PluginApi; namespace Progmasoft.Tazel.Project; -/// <summary>What <c>tazel-plugin.json</c>, the manifest at the top of a plugin archive, says.</summary> -/// <param name="Group">The group of the plugin.</param> -/// <param name="Name">The name of the plugin.</param> -/// <param name="Version">Its SemVer version.</param> -/// <param name="PluginApi">The version of Progmasoft.Tazel.PluginApi it was built against.</param> -/// <param name="EntryAssembly">The file of the assembly that holds its <see cref="ITazelPlugin"/>.</param> -internal sealed record PluginManifest(string Group, string Name, string Version, string PluginApi, string EntryAssembly); - /// <summary>A plugin, loaded into a load context of its own and applied.</summary> -internal sealed class LoadedPlugin(PluginManifest manifest, string directory, AssemblyLoadContext context, List<Assembly> assemblies) +internal sealed class LoadedPlugin(TazelPluginManifest manifest, string directory, AssemblyLoadContext context, List<Assembly> assemblies) { - public PluginManifest Manifest { get; } = manifest; + public TazelPluginManifest Manifest { get; } = manifest; public string Directory { get; } = directory; @@ -52,7 +43,7 @@ internal sealed class LoadedPlugin(PluginManifest manifest, string directory, As /// </summary> internal static class Plugins { - public const string ManifestFile = "tazel-plugin.json"; + public const string ManifestFile = TazelPluginManifest.FileName; private static readonly string[] Shared = ["Progmasoft.Tazel.PluginApi", "Progmasoft.Tazel.Dsl"]; @@ -135,7 +126,7 @@ internal static class Plugins /// <summary>The directory of the plugin's archive, unpacked once below the state directory by its SHA-256.</summary> private static string Unpacked(string mainRoot, string archive) { - var sha = Sha256Sums.Sha256(archive); + var sha = Archive.Sha256Sums.Sha256(archive); var destination = Path.Combine(mainRoot, ModuleFiles.StateDirectory, "plugins", sha[..32]); if (ModuleArchive.FromMarker(destination) is { } unpacked) { @@ -164,55 +155,25 @@ internal static class Plugins } } - private static PluginManifest ReadManifest(string file, string shown) + private static TazelPluginManifest ReadManifest(string file, string shown) { try { - return JsonSerializer.Deserialize<PluginManifest>(File.ReadAllText(file), - new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, AllowTrailingCommas = false }) - ?? throw new ProjectException($"{shown}: {ManifestFile} is empty"); - } - catch (JsonException error) - { - throw new ProjectException($"{shown}: {ManifestFile} cannot be read: {error.Message}", error); + return TazelPluginManifest.Read(File.ReadAllText(file), shown); } - } - - private static void CheckManifest(PluginManifest manifest, string shown) - { - CheckNames(manifest, shown); - CheckApi(manifest, shown); - var entry = manifest.EntryAssembly; - if (string.IsNullOrEmpty(entry) || entry.Contains('/', StringComparison.Ordinal) || entry.Contains('\\', StringComparison.Ordinal) || - !entry.EndsWith(".dll", StringComparison.Ordinal)) + catch (TazelPackageException error) { - throw new ProjectException($"{shown}: the entry assembly '{entry}' is not a .dll at the top"); + throw new ProjectException(error.Message, error); } } - private static void CheckNames(PluginManifest manifest, string shown) - { - if (string.IsNullOrEmpty(manifest.Group) || manifest.Group.Split('.').Any(part => part.Length == 0 || !Labels.IsName(part))) - { - throw new ProjectException($"{shown}: the group '{manifest.Group}' of its manifest is not names joined by dots"); - } - - if (string.IsNullOrEmpty(manifest.Name) || !Labels.IsName(manifest.Name)) - { - throw new ProjectException($"{shown}: the name '{manifest.Name}' of its manifest is not a name"); - } - - if (!NuGetVersion.TryParseStrict(manifest.Version ?? "", out _)) - { - throw new ProjectException($"{shown}: '{manifest.Version}' is not a SemVer version"); - } - } + private static void CheckManifest(TazelPluginManifest manifest, string shown) => CheckApi(manifest, shown); /// <summary> /// The plugin API a plugin was built against must be this Tazel's: before 1.0.0 a new MINOR may change the API, so /// the MAJOR and MINOR must be the same; from 1.0.0 the MAJOR, and a MINOR no newer. /// </summary> - private static void CheckApi(PluginManifest manifest, string shown) + private static void CheckApi(TazelPluginManifest manifest, string shown) { if (!Version.TryParse(manifest.PluginApi ?? "", out var api)) { diff --git a/src/Progmasoft.Tazel/Project/SpdxLicenses.cs b/src/Progmasoft.Tazel/Project/SpdxLicenses.cs index df5410d..059c143 100644 --- a/src/Progmasoft.Tazel/Project/SpdxLicenses.cs +++ b/src/Progmasoft.Tazel/Project/SpdxLicenses.cs @@ -2,11 +2,7 @@ // SPDX-License-Identifier: MIT using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.Json; -using Tethys.SPDX.ExpressionParser; +using Progmasoft.Tazel.Packaging.Spdx; namespace Progmasoft.Tazel.Project; @@ -32,29 +28,17 @@ public sealed class LicenseException : Exception } /// <summary> -/// The SPDX License List that ships with Tazel (<c>spdx/licenses.json</c> and <c>spdx/exceptions.json</c> of the -/// repository, embedded) and the check of a module's <c>License</c> against it. Identifiers match without regard to -/// case, as the SPDX specification says; <c>LicenseRef-</c> and <c>DocumentRef-</c> name licenses of one's own. +/// The check of a module's <c>License</c>: Progmasoft.Tazel.Packaging reads the expression and holds the SPDX License +/// List; this turns what it finds into the messages of <c>error[E0509]</c>. /// </summary> internal static class SpdxLicenses { - private sealed record Entry(string Id, bool Deprecated); - - private static readonly Lazy<(string Version, Dictionary<string, Entry> Licenses, Dictionary<string, Entry> Exceptions)> - List = new(Load); - /// <summary>The version of the SPDX License List, such as 3.29.0.</summary> - public static string Version => List.Value.Version; - - /// <summary>Whether <paramref name="id"/> is a license of the list, in any case.</summary> - public static bool IsLicense(string id) => List.Value.Licenses.ContainsKey(id); - - /// <summary>Whether <paramref name="id"/> is an exception of the list, in any case.</summary> - public static bool IsException(string id) => List.Value.Exceptions.ContainsKey(id); + public static string Version => SpdxLicenseList.Current.Version; /// <summary> - /// Checks a license expression: its grammar (<c>AND</c>, <c>OR</c>, <c>WITH</c>, parentheses, <c>+</c>), that - /// every license and exception is on the list and that none is deprecated. + /// Checks a license expression: its form (<c>AND</c>, <c>OR</c>, <c>WITH</c>, parentheses, <c>+</c>), that every + /// license and exception is on the list and that none is deprecated. /// </summary> /// <exception cref="LicenseException">The expression cannot stand; the message says why and what to write.</exception> public static void Check(string expression, string shown) @@ -65,229 +49,37 @@ internal static class SpdxLicenses throw new LicenseException($"{shown}: License is empty; write an SPDX expression such as MIT, or leave it out"); } - var (version, licenses, exceptions) = List.Value; - var afterWith = false; - foreach (var word in Words(expression)) - { - if (word is "(" or ")" || IsOperator(word, "AND") || IsOperator(word, "OR")) - { - afterWith = false; - continue; - } - - if (IsOperator(word, "WITH")) - { - afterWith = true; - continue; - } - - if (!afterWith && IsReference(word)) - { - continue; - } - - var id = afterWith ? word : word.TrimEnd('+'); - var table = afterWith ? exceptions : licenses; - var kind = afterWith ? "exception" : "license"; - if (!table.TryGetValue(id, out var entry)) - { - throw new LicenseException( - $"{shown}: '{id}' is no {kind} of the SPDX License List {version}{Suggestions(id, table, afterWith)}"); - } - - if (entry.Deprecated) - { - throw new LicenseException( - $"{shown}: '{entry.Id}' is deprecated in the SPDX License List {version}{Replacements(entry.Id, licenses, orLater: !afterWith && word.EndsWith('+'))}"); - } - - afterWith = false; - } - - // Tethys.SPDX 2.2.0 recurses without end, and the process dies of a stack overflow that cannot be caught, on an - // expression that ends in AND or OR; only an expression whose form is checked here reaches it. - Grammar.Check(Words(expression).ToList(), expression, shown); - try - { - _ = SpdxExpressionParser.Parse(expression, id => IsLicense(id) || IsException(id) || IsReference(id), IsException); - } - catch (SpdxExpressionException error) + if (!SpdxExpressionParser.TryParse(expression, out var parsed, out var error)) { throw new LicenseException( - $"{shown}: '{expression}' is not an SPDX expression: licenses joined by AND and OR, an exception after " + - "WITH, parentheses around a group", error); - } - catch (ArgumentException error) - { - throw new LicenseException($"{shown}: '{expression}' is not an SPDX expression", error); - } - } - - /// <summary> - /// The form of an expression, as SPDX writes it: <c>expression = term {(AND | OR) term}</c> and - /// <c>term = "(" expression ")" | license [WITH exception]</c>. - /// </summary> - private sealed class Grammar - { - private readonly List<string> _words; - private readonly string _expression; - private readonly string _shown; - private int _at; - - private Grammar(List<string> words, string expression, string shown) - { - _words = words; - _expression = expression; - _shown = shown; + $"{shown}: '{expression}' is not an SPDX expression: {error.Reason}; licenses are joined by AND and OR, " + + "an exception follows WITH, and parentheses group them", error); } - public static void Check(List<string> words, string expression, string shown) + var list = SpdxLicenseList.Current; + foreach (var problem in list.Check(parsed)) { - var grammar = new Grammar(words, expression, shown); - grammar.Expression(); - if (grammar._at < words.Count) - { - grammar.Fail(words[grammar._at] == ")" ? "a ')' closes no '('" : $"'{words[grammar._at]}' cannot follow"); - } + throw new LicenseException($"{shown}: {Describe(problem, list.Version)}"); } - - private void Expression() - { - Term(); - while (_at < _words.Count && (IsOperator(_words[_at], "AND") || IsOperator(_words[_at], "OR"))) - { - var joiner = _words[_at++]; - if (_at == _words.Count) - { - Fail($"it ends with {joiner.ToUpperInvariant()}; a license must follow it"); - } - - Term(); - } - } - - private void Term() - { - if (_at == _words.Count) - { - Fail("a license is missing"); - } - - var word = _words[_at++]; - if (word == "(") - { - Expression(); - if (_at == _words.Count || _words[_at] != ")") - { - Fail("a '(' is not closed"); - } - - _at++; - return; - } - - if (word == ")" || IsOperator(word, "AND") || IsOperator(word, "OR") || IsOperator(word, "WITH")) - { - Fail($"'{word}' stands where a license should"); - } - - if (_at < _words.Count && IsOperator(_words[_at], "WITH")) - { - _at++; - if (_at == _words.Count || _words[_at] is "(" or ")") - { - Fail("an exception must follow WITH"); - } - - _at++; - } - } - - private void Fail(string why) => - throw new LicenseException( - $"{_shown}: '{_expression}' is not an SPDX expression: {why}; licenses are joined by AND and OR, an " + - "exception follows WITH, and parentheses group them"); } - /// <summary>The words of an expression: parentheses apart, the rest split at white space.</summary> - private static IEnumerable<string> Words(string expression) => - expression.Replace("(", " ( ", StringComparison.Ordinal).Replace(")", " ) ", StringComparison.Ordinal) - .Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); - - private static bool IsOperator(string word, string name) => string.Equals(word, name, StringComparison.OrdinalIgnoreCase); - - private static bool IsReference(string word) => - word.StartsWith("LicenseRef-", StringComparison.OrdinalIgnoreCase) || - word.StartsWith("DocumentRef-", StringComparison.OrdinalIgnoreCase); - - /// <summary>Up to three identifiers of the list close to a misspelt one.</summary> - private static string Suggestions(string id, Dictionary<string, Entry> table, bool exception) + private static string Describe(SpdxProblem problem, string version) { - var close = table.Values.Where(entry => !entry.Deprecated) - .Select(entry => (entry.Id, Distance: Distance(id.ToUpperInvariant(), entry.Id.ToUpperInvariant()))) - .Where(candidate => candidate.Distance <= Math.Max(2, id.Length / 4)) - .OrderBy(candidate => candidate.Distance).ThenBy(candidate => candidate.Id, StringComparer.Ordinal) - .Take(3).Select(candidate => candidate.Id).ToList(); - if (close.Count > 0) + var suggested = string.Join(", ", problem.Suggestions); + return problem.Kind switch { - return $"; did you mean {string.Join(", ", close)}?"; - } - - return exception - ? "; the exceptions are listed at https://spdx.org/licenses/exceptions-index.html" - : "; a license of your own is written LicenseRef-<name>"; - } - - /// <summary>What to write instead of a deprecated license: its -only and -or-later forms when the list has them.</summary> - private static string Replacements(string id, Dictionary<string, Entry> licenses, bool orLater) - { - var stem = id.EndsWith('+') ? id[..^1] : id; - var forms = (orLater ? new[] { stem + "-or-later" } : new[] { stem + "-only", stem + "-or-later" }).Where(licenses.ContainsKey).ToList(); - return forms.Count > 0 - ? $"; write {string.Join(" or ", forms.Select(form => licenses[form].Id))}" - : "; https://spdx.org/licenses/ names the identifier that replaces it"; + SpdxProblemKind.UnknownLicense => $"'{problem.Id}' is no license of the SPDX License List {version}" + + (problem.Suggestions.Count > 0 ? $"; did you mean {suggested}?" : "; a license of your own is written LicenseRef-<name>"), + SpdxProblemKind.UnknownException => $"'{problem.Id}' is no exception of the SPDX License List {version}" + + (problem.Suggestions.Count > 0 + ? $"; did you mean {suggested}?" + : "; the exceptions are listed at https://spdx.org/licenses/exceptions-index.html"), + SpdxProblemKind.DeprecatedLicense => $"'{problem.Id}' is deprecated in the SPDX License List {version}" + + (problem.Suggestions.Count > 0 + ? $"; write {string.Join(" or ", problem.Suggestions)}" + : "; https://spdx.org/licenses/ names the identifier that replaces it"), + _ => $"'{problem.Id}' is a deprecated exception in the SPDX License List {version}; " + + "https://spdx.org/licenses/exceptions-index.html names the one that replaces it", + }; } - - private static int Distance(string a, string b) - { - var previous = Enumerable.Range(0, b.Length + 1).ToArray(); - for (var i = 1; i <= a.Length; i++) - { - var current = new int[b.Length + 1]; - current[0] = i; - for (var j = 1; j <= b.Length; j++) - { - var cost = a[i - 1] == b[j - 1] ? 0 : 1; - current[j] = Math.Min(Math.Min(current[j - 1] + 1, previous[j] + 1), previous[j - 1] + cost); - } - - previous = current; - } - - return previous[b.Length]; - } - - private static (string, Dictionary<string, Entry>, Dictionary<string, Entry>) Load() - { - using var licensesJson = JsonDocument.Parse(Resource("spdx.licenses.json")); - using var exceptionsJson = JsonDocument.Parse(Resource("spdx.exceptions.json")); - var version = licensesJson.RootElement.GetProperty("licenseListVersion").GetString() ?? ""; - return (version, Table(licensesJson, "licenses", "licenseId"), Table(exceptionsJson, "exceptions", "licenseExceptionId")); - } - - private static Dictionary<string, Entry> Table(JsonDocument document, string list, string idProperty) - { - var table = new Dictionary<string, Entry>(StringComparer.OrdinalIgnoreCase); - foreach (var item in document.RootElement.GetProperty(list).EnumerateArray()) - { - var id = item.GetProperty(idProperty).GetString() ?? ""; - table[id] = new Entry(id, item.GetProperty("isDeprecatedLicenseId").GetBoolean()); - } - - return table; - } - - private static Stream Resource(string name) => - typeof(SpdxLicenses).Assembly.GetManifestResourceStream(name) - ?? throw new InvalidOperationException($"the SPDX License List ({name}) is missing from Tazel"); } diff --git a/src/Shared/ReproducibleArchive.cs b/src/Shared/ReproducibleArchive.cs deleted file mode 100644 index ff4c5de..0000000 --- a/src/Shared/ReproducibleArchive.cs +++ /dev/null @@ -1,106 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> -// SPDX-License-Identifier: MIT - -using System; -using System.Collections.Generic; -using System.Formats.Tar; -using System.IO; -using System.Linq; -using LzmaNet; - -namespace Progmasoft.Tazel.Archive; - -/// <summary> -/// Writes a <c>.tar.xz</c> that is the same bytes for the same files: its entries are sorted, below one top directory, -/// owned by no one, dated at the epoch, and either <c>0644</c> or, for an executable file, <c>0755</c>; xz compresses -/// with one thread. The modules of Tazel and the plugins of the SDK are written by it. -/// </summary> -internal static class ReproducibleArchive -{ - private const UnixFileMode FileMode = - UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead; - - private const UnixFileMode ExecutableMode = FileMode | - UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute; - - private const UnixFileMode DirectoryMode = ExecutableMode | UnixFileMode.UserWrite; - - /// <summary> - /// Writes <paramref name="files"/>, paths with <c>/</c> below <paramref name="root"/>, into <paramref name="archive"/> - /// below the directory <paramref name="baseName"/>. The archive appears whole or not at all. - /// </summary> - public static void Write(string root, string baseName, string archive, IReadOnlyList<string> files) - { - ArgumentNullException.ThrowIfNull(files); - var directory = Path.GetDirectoryName(Path.GetFullPath(archive))!; - Directory.CreateDirectory(directory); - var temporary = Path.Combine(directory, $".{Path.GetFileName(archive)}.{Guid.NewGuid():N}.partial"); - try - { - using (var output = File.Create(temporary)) - using (var xz = new XzCompressStream(output, new XzCompressOptions { Threads = 1 }, leaveOpen: false)) - using (var tar = new TarWriter(xz, TarEntryFormat.Ustar, leaveOpen: false)) - { - foreach (var (path, isDirectory) in PathsAndDirectories(files)) - { - var name = path.Length == 0 ? $"{baseName}/" : isDirectory ? $"{baseName}/{path}/" : $"{baseName}/{path}"; - var entry = new UstarTarEntry(isDirectory ? TarEntryType.Directory : TarEntryType.RegularFile, name) - { - ModificationTime = DateTimeOffset.UnixEpoch, - Uid = 0, - Gid = 0, - UserName = "", - GroupName = "", - }; - var source = Path.Combine(root, path); - entry.Mode = isDirectory ? DirectoryMode : IsExecutable(source) ? ExecutableMode : FileMode; - if (isDirectory) - { - tar.WriteEntry(entry); - } - else - { - using var data = File.OpenRead(source); - entry.DataStream = data; - tar.WriteEntry(entry); - } - } - } - - File.Move(temporary, archive, overwrite: true); - } - finally - { - File.Delete(temporary); - } - } - - /// <summary>The SHA-256 of <paramref name="file"/> in lower-case hexadecimal.</summary> - public static string Sha256(string file) - { - using var stream = File.OpenRead(file); - return Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(stream)); - } - - /// <summary>The line of a <c>.sha256sums</c> file for <paramref name="file"/>, as <c>sha256sum</c> writes it.</summary> - public static string SumsLine(string file) => $"{Sha256(file)} {Path.GetFileName(file)}\n"; - - private static bool IsExecutable(string file) => - !OperatingSystem.IsWindows() && (File.GetUnixFileMode(file) & UnixFileMode.UserExecute) != 0; - - private static IEnumerable<(string Path, bool IsDirectory)> PathsAndDirectories(IReadOnlyList<string> files) - { - var directories = new SortedSet<string>(StringComparer.Ordinal) { "" }; - foreach (var file in files) - { - var parts = file.Split('/'); - for (var depth = 1; depth < parts.Length; depth++) - { - directories.Add(string.Join('/', parts.Take(depth))); - } - } - - return directories.Select(d => (d, true)).Concat(files.Select(f => (f, false))) - .OrderBy(entry => entry.Item1, StringComparer.Ordinal); - } -} diff --git a/tests/Progmasoft.Tazel.Tests/PackagingTests.cs b/tests/Progmasoft.Tazel.Tests/PackagingTests.cs new file mode 100644 index 0000000..068ac40 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/PackagingTests.cs @@ -0,0 +1,170 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Linq; +using CsCheck; +using Progmasoft.Tazel.Packaging; +using Progmasoft.Tazel.Packaging.Spdx; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +/// <summary>Progmasoft.Tazel.Packaging: identities, archives, sums, the plugin manifest and SPDX expressions.</summary> +public sealed class PackagingTests +{ + [Fact] + public void AnIdentityNamesItsArchive() + { + var identity = new TazelPackageIdentity("com.example", "greeter", "1.2.0-rc.1"); + Assert.Equal("com.example.greeter-1.2.0-rc.1", identity.BaseName); + Assert.Equal("com.example.greeter-1.2.0-rc.1.tazel.tar.xz", identity.FileName); + } + + [Theory] + [InlineData("com..example", "greeter", "1.0.0", "group")] + [InlineData("com.example", "greet er", "1.0.0", "name")] + [InlineData("com.example", "greeter", "1.0", "SemVer")] + [InlineData("com.example", "greeter", "01.0.0", "SemVer")] + public void AnIdentityRefusesWhatItCannotBe(string group, string name, string version, string part) + { + var error = Assert.Throws<TazelPackageException>(() => new TazelPackageIdentity(group, name, version)); + Assert.Contains(part, error.Message, StringComparison.Ordinal); + } + + [Fact] + public void AnArchiveIsTheSameBytesAndUnpacksToItsFiles() + { + using var module = new TemporaryModule().Write("MODULE.csx", "m").Write("src/a.c", "int a;"); + var files = new[] { "MODULE.csx", "src/a.c" }; + var first = Path.Combine(module.Root, "out", "first" + TazelPackageArchive.Extension); + var second = Path.Combine(module.Root, "out", "second" + TazelPackageArchive.Extension); + TazelPackageArchive.Write(module.Root, "com.example.m-1.0.0", first, files); + TazelPackageArchive.Write(module.Root, "com.example.m-1.0.0", second, files); + Assert.Equal(File.ReadAllBytes(first), File.ReadAllBytes(second)); + + var top = TazelPackageArchive.Unpack(first, Path.Combine(module.Root, "unpacked"), "MODULE.csx"); + Assert.Equal("com.example.m-1.0.0", Path.GetFileName(top)); + Assert.Equal("int a;", File.ReadAllText(Path.Combine(top, "src", "a.c"))); + + var missing = Assert.Throws<TazelPackageException>(() => + TazelPackageArchive.Unpack(first, Path.Combine(module.Root, "again"), "tazel-plugin.json")); + Assert.Contains("has no com.example.m-1.0.0/tazel-plugin.json", missing.Message, StringComparison.Ordinal); + } + + [Fact] + public void SumsAreReadAsSha256sumWritesThem() + { + using var module = new TemporaryModule().Write("x.bin", "x"); + var file = Path.Combine(module.Root, "x.bin"); + var line = Sha256Sums.Line(file); + Assert.Equal(Sha256Sums.Sha256(file), Sha256Sums.SumFor(line, "x.bin", "x.bin.sha256sums")); + Assert.Null(Sha256Sums.SumFor(line, "y.bin", "x.bin.sha256sums")); + Assert.Throws<TazelPackageException>(() => Sha256Sums.SumFor("not a sum\n", "x.bin", "x.bin.sha256sums")); + Assert.Throws<TazelPackageException>(() => Sha256Sums.SumFor(line + line, "x.bin", "x.bin.sha256sums")); + } + + [Fact] + public void AManifestIsWrittenAndReadBack() + { + var manifest = new TazelPluginManifest("com.example", "greeter", "0.1.0", "0.2.0", "Greeter.dll"); + var json = manifest.ToJson(); + Assert.StartsWith("{\n \"entryAssembly\": \"Greeter.dll\",", json.ReplaceLineEndings("\n"), StringComparison.Ordinal); + Assert.Equal(manifest, TazelPluginManifest.Read(json, "tazel-plugin.json")); + Assert.Equal("com.example.greeter-0.1.0", manifest.Identity.BaseName); + } + + [Theory] + [InlineData("""{"group":"com.example","name":"g","version":"0.1.0","pluginApi":"0.2.0","entryAssembly":"lib/G.dll"}""", "not a .dll at the top")] + [InlineData("""{"group":"com.example","name":"g","version":"x","pluginApi":"0.2.0","entryAssembly":"G.dll"}""", "not a SemVer version")] + [InlineData("""{"group":"","name":"g","version":"0.1.0","pluginApi":"0.2.0","entryAssembly":"G.dll"}""", "not names joined by dots")] + [InlineData("""{"group":"com.example",""", "cannot be read")] + public void AManifestThatCannotStandIsRefused(string json, string why) + { + var error = Assert.Throws<TazelPackageException>(() => TazelPluginManifest.Read(json, "p.tazel.tar.xz")); + Assert.Contains(why, error.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData("MIT OR Apache-2.0 AND BSD-2-Clause", "MIT OR Apache-2.0 AND BSD-2-Clause")] + [InlineData("(MIT OR Apache-2.0) AND BSD-2-Clause", "(MIT OR Apache-2.0) AND BSD-2-Clause")] + [InlineData("((MIT))", "MIT")] + [InlineData("mit or apache-2.0", "mit OR apache-2.0")] + [InlineData("GPL-2.0-only WITH Classpath-exception-2.0 OR MIT", "GPL-2.0-only WITH Classpath-exception-2.0 OR MIT")] + [InlineData("MIT AND (Apache-2.0 AND BSD-3-Clause)", "MIT AND (Apache-2.0 AND BSD-3-Clause)")] + [InlineData("DocumentRef-spdx-tool-1.2:LicenseRef-MIT-Style-2", "DocumentRef-spdx-tool-1.2:LicenseRef-MIT-Style-2")] + public void ExpressionsAreReadWithTheirPrecedence(string text, string written) => + Assert.Equal(written, SpdxExpressionParser.Parse(text).ToString()); + + [Fact] + public void AndBindsTighterThanOrAndWithTighterThanBoth() + { + var parsed = SpdxExpressionParser.Parse("MIT OR GPL-2.0-only WITH Classpath-exception-2.0 AND Apache-2.0+"); + Assert.Equal( + new SpdxOr(new SpdxLicense("MIT", false), + new SpdxAnd(new SpdxWith(new SpdxLicense("GPL-2.0-only", false), "Classpath-exception-2.0"), + new SpdxLicense("Apache-2.0", true))), + parsed); + Assert.Equal(["MIT", "GPL-2.0-only", "Apache-2.0+"], parsed.Leaves().Select(leaf => leaf.ToString())); + } + + [Theory] + [InlineData("MIT,Apache-2.0", "','")] + [InlineData("MIT Apache-2.0", "'Apache-2.0' cannot follow")] + [InlineData("MIT+Foo", "'+' only at the end")] + [InlineData("LicenseRef-", "no license reference")] + [InlineData("MIT)", "a ')' closes no '('")] + [InlineData("", "the expression is empty")] + public void MalformedExpressionsSayWhy(string text, string why) + { + var error = Assert.Throws<SpdxExpressionException>(() => SpdxExpressionParser.Parse(text)); + Assert.Contains(why, error.Reason, StringComparison.Ordinal); + } + + [Fact] + public void NoInputCanExhaustTheStack() + { + var nested = new string('(', SpdxExpressionParser.MaxDepth) + "MIT" + new string(')', SpdxExpressionParser.MaxDepth); + Assert.Equal("MIT", SpdxExpressionParser.Parse(nested).ToString()); + Assert.Contains("deeper", Assert.Throws<SpdxExpressionException>(() => + SpdxExpressionParser.Parse(new string('(', 1_000_000) + "MIT")).Reason, StringComparison.Ordinal); + var chain = string.Join(" AND ", Enumerable.Repeat("MIT", SpdxExpressionParser.MaxLicenses)); + Assert.Equal(chain, SpdxExpressionParser.Parse(chain).ToString()); + Assert.Contains("more than", Assert.Throws<SpdxExpressionException>(() => + SpdxExpressionParser.Parse(chain + " OR MIT")).Reason, StringComparison.Ordinal); + } + + [Fact] + public void WrittenExpressionsReadBackToTheSameTree() + { + var ids = Gen.OneOf("MIT", "Apache-2.0", "BSD-3-Clause", "GPL-2.0-only", "LicenseRef-Own"); + var leaf = Gen.Select(ids, Gen.Bool, (id, orLater) => + (SpdxExpression)(id.StartsWith("LicenseRef-", StringComparison.Ordinal) + ? new SpdxLicenseReference(null, id) + : new SpdxLicense(id, orLater))); + var tree = Gen.Recursive<SpdxExpression>((depth, inner) => depth > 4 + ? leaf + : Gen.Frequency( + (3, leaf), + (1, Gen.Select(inner, inner, (left, right) => (SpdxExpression)new SpdxAnd(left, right))), + (1, Gen.Select(inner, inner, (left, right) => (SpdxExpression)new SpdxOr(left, right))), + (1, Gen.Select(leaf, Gen.OneOf("LLVM-exception", "Classpath-exception-2.0"), + (license, exception) => (SpdxExpression)new SpdxWith(license, exception))))); + tree.Sample(expression => Assert.Equal(expression, SpdxExpressionParser.Parse(expression.ToString()))); + } + + [Fact] + public void TheListFindsUnknownAndDeprecatedIdentifiers() + { + var list = SpdxLicenseList.Current; + Assert.Equal("3.29.0", list.Version); + Assert.Equal("Apache-2.0", list.License("apache-2.0")?.Id); + var problems = list.Check(SpdxExpressionParser.Parse("MTI OR GPL-2.0+ OR Apache-2.0 WITH Nope-exception OR LicenseRef-x")); + Assert.Equal([SpdxProblemKind.UnknownLicense, SpdxProblemKind.DeprecatedLicense, SpdxProblemKind.UnknownException], + problems.Select(problem => problem.Kind)); + Assert.Contains("MIT", problems[0].Suggestions); + Assert.Equal(["GPL-2.0-or-later"], problems[1].Suggestions); + Assert.Empty(list.Check(SpdxExpressionParser.Parse("MIT OR Apache-2.0 WITH LLVM-exception"))); + } +} diff --git a/tests/Progmasoft.Tazel.Tests/PluginTests.cs b/tests/Progmasoft.Tazel.Tests/PluginTests.cs index 0134f64..40f1fc7 100644 --- a/tests/Progmasoft.Tazel.Tests/PluginTests.cs +++ b/tests/Progmasoft.Tazel.Tests/PluginTests.cs @@ -161,7 +161,7 @@ public sealed class PluginSdkTests await Run(Path.Combine(work.Root, "Greeter"), isolated, "pack", "-c", "Release", "-o", "out"); var archive = Path.Combine(work.Root, "Greeter", "out", "com.example.tools.greeter-0.1.0.tazel.tar.xz"); - Assert.Equal(ReproducibleArchive.SumsLine(archive), + Assert.Equal(Packaging.Sha256Sums.Line(archive), await File.ReadAllTextAsync(archive + ".sha256sums", TestContext.Current.CancellationToken)); Directory.CreateDirectory(Path.Combine(work.Root, "module", "plugins")); File.Copy(archive, Path.Combine(work.Root, "module", "plugins", "greeter.tazel.tar.xz")); diff --git a/tests/Progmasoft.Tazel.Tests/SpdxLicensesTests.cs b/tests/Progmasoft.Tazel.Tests/SpdxLicensesTests.cs index 33e349c..dc04448 100644 --- a/tests/Progmasoft.Tazel.Tests/SpdxLicensesTests.cs +++ b/tests/Progmasoft.Tazel.Tests/SpdxLicensesTests.cs @@ -36,7 +36,7 @@ public sealed class SpdxLicensesTests [InlineData("MIT AND", "not an SPDX expression", "AND and OR")] [InlineData("(MIT OR Apache-2.0", "not an SPDX expression", "parentheses")] [InlineData(" ", "License is empty", "leave it out")] - // These made Tethys.SPDX 2.2.0 recurse until the stack overflowed. + // These overflowed the stack of the SPDX parser Tazel first tried (Tethys.SPDX 2.2.0, tngraf/Tethys.SPDX#10). [InlineData("MIT OR", "ends with OR", "AND and OR")] [InlineData("AND MIT", "stands where a license should", "AND and OR")] [InlineData("MIT WITH", "an exception must follow WITH", "WITH")]