tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Load local plugins and run the build steps they declare
- Commit
c3cb084c54a8e3bbafab2d1e532ee26927b36549- Author
- Leitwolf11 ·
- Parents
64f52cb21c76
Changes
CHANGELOG.md | 3 + Directory.Packages.props | 1 + Tazel.slnx | 3 + docs/README.md | 1 + docs/architecture.md | 4 + docs/plugins.md | 100 ++++++ docs/project-files.md | 5 +- docs/reference/docfx.json | 2 +- src/Progmasoft.Tazel.Dsl/Declarations.cs | 6 + .../Progmasoft.Tazel.Dsl.csproj | 5 + src/Progmasoft.Tazel.PluginApi/Plugin.cs | 86 ++++++ .../Progmasoft.Tazel.PluginApi.csproj | 19 ++ src/Progmasoft.Tazel.PluginApi/Steps/Step.cs | 97 ++++++ src/Progmasoft.Tazel.PluginSdk/PackTazelPlugin.cs | 109 +++++++ .../Progmasoft.Tazel.PluginSdk.csproj | 44 +++ src/Progmasoft.Tazel.PluginSdk/Sdk/Sdk.props.in | 18 ++ src/Progmasoft.Tazel.PluginSdk/Sdk/Sdk.targets | 55 ++++ .../Progmasoft.Tazel.PluginTemplates.csproj | 34 +++ .../tazel-plugin/.template.config/template.json | 28 ++ .../content/tazel-plugin/Plugin.cs | 29 ++ .../content/tazel-plugin/PluginProject.csproj.in | 7 + src/Progmasoft.Tazel/Archive/ModuleArchive.cs | 88 +----- src/Progmasoft.Tazel/Cli/Commands.cs | 9 +- src/Progmasoft.Tazel/Driver/Actions.cs | 3 + src/Progmasoft.Tazel/Driver/Executor.cs | 6 +- src/Progmasoft.Tazel/Driver/Planner.cs | 7 +- src/Progmasoft.Tazel/Driver/StepPlanner.cs | 155 ++++++++++ src/Progmasoft.Tazel/Progmasoft.Tazel.csproj | 4 + src/Progmasoft.Tazel/Project/Plugins.cs | 335 +++++++++++++++++++++ src/Progmasoft.Tazel/Project/ScriptHost.cs | 41 ++- src/Progmasoft.Tazel/Project/TargetChecks.cs | 12 + src/Progmasoft.Tazel/Project/Workspace.cs | 20 +- src/Shared/ReproducibleArchive.cs | 106 +++++++ tests/Progmasoft.Tazel.Tests/PluginTests.cs | 219 ++++++++++++++ 34 files changed, 1553 insertions(+), 108 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffd5f57..4fa2871 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,3 +18,6 @@ The first version of Tazel, written in C# for .NET 10. - An action cache by content, depfiles for headers, parallel actions, runfiles, sharded and flaky tests. - Reproducible `.tazel.tar.xz` archives of modules, and dependencies on them checked by SHA-256. - `tazel_options.txt` (with `platform:`) and `tazel_custom.txt`. +- Plugins: `Progmasoft.Tazel.PluginApi`, the project SDK `Progmasoft.Tazel.PluginSdk` that packs a plugin with + `dotnet pack`, the template `dotnet new tazel-plugin`, local plugins loaded each into its own load context, and build + steps that plugins and `BUILD.csx` files declare. diff --git a/Directory.Packages.props b/Directory.Packages.props index aca2b46..284c1f6 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -16,6 +16,7 @@ <PackageVersion Include="Snapshooter.Xunit3" Version="1.3.1" /> <PackageVersion Include="coverlet.MTP" Version="10.1.0" /> <PackageVersion Include="BenchmarkDotNet" Version="0.15.8" /> + <PackageVersion Include="Microsoft.Build.Utilities.Core" Version="18.0.2" /> <PackageVersion Include="SharpFuzz" Version="2.3.0" /> </ItemGroup> </Project> diff --git a/Tazel.slnx b/Tazel.slnx index 03672ef..bd7fab6 100644 --- a/Tazel.slnx +++ b/Tazel.slnx @@ -2,6 +2,9 @@ <Folder Name="/src/"> <Project Path="src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj" /> <Project Path="src/Progmasoft.Tazel/Progmasoft.Tazel.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" /> </Folder> <Folder Name="/tests/"> <Project Path="tests/Progmasoft.Tazel.Tests/Progmasoft.Tazel.Tests.csproj" /> diff --git a/docs/README.md b/docs/README.md index fc4a6f9..5a18f01 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,6 +6,7 @@ | Document | What it covers | | --- | --- | | [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 | | [Commands](commands.md) | the commands of `tazel`, their options, and `tazel_options.txt` and `tazel_custom.txt` | | [Architecture](architecture.md) | the projects of the solution and how a build runs | | [Development](development.md) | building, testing, fuzzing and benchmarking Tazel, and its CI | diff --git a/docs/architecture.md b/docs/architecture.md index cc6e9db..2eec2df 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -9,6 +9,10 @@ | --- | --- | | `src/Progmasoft.Tazel.Dsl` | the types project files are written against; scripts reference this assembly alone | | `src/Progmasoft.Tazel` | the `tazel` command | +| `src/Progmasoft.Tazel.PluginApi` | the API of plugins and their build steps (NuGet `Progmasoft.Tazel.PluginApi`) | +| `src/Progmasoft.Tazel.PluginSdk` | the MSBuild project SDK of plugins and the task that packs them | +| `src/Progmasoft.Tazel.PluginTemplates` | `dotnet new tazel-plugin` | +| `src/Shared` | the reproducible archive writer, compiled into tazel and the SDK task | | `tests/Progmasoft.Tazel.Tests` | xUnit tests, with CsCheck for properties and Snapshooter for snapshots | | `benchmarks/Progmasoft.Tazel.Benchmarks` | BenchmarkDotNet measurements of the readers | | `fuzz/Progmasoft.Tazel.Fuzz` | SharpFuzz targets for libFuzzer | diff --git a/docs/plugins.md b/docs/plugins.md new file mode 100644 index 0000000..508d517 --- /dev/null +++ b/docs/plugins.md @@ -0,0 +1,100 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> + +# Plugins + +A plugin adds to what `BUILD.csx` files can declare. It is a .NET 10 class library made with the project SDK +`Progmasoft.Tazel.PluginSdk` and packed by `dotnet pack` into `$group.$name-$version.tazel.tar.xz`. + +## Making a plugin + +```text +dotnet new install Progmasoft.Tazel.PluginTemplates +dotnet new tazel-plugin -n Greeter --group com.example.tools --pluginName greeter +cd Greeter +dotnet pack -c Release -o out +``` + +```xml +<Project Sdk="Progmasoft.Tazel.PluginSdk/0.1.0"> + <PropertyGroup> + <TazelPluginGroup>com.example.tools</TazelPluginGroup> + <TazelPluginName>greeter</TazelPluginName> + <Version>0.1.0</Version> + </PropertyGroup> +</Project> +``` + +The SDK: + +- targets `net10.0`, the runtime of Tazel; +- references `Progmasoft.Tazel.PluginApi` of its own version with `ExcludeAssets="runtime"` and `PrivateAssets="all"`: + the plugin compiles against it, never ships it, and does not pass it on; +- stops the build when the group, the name or the SemVer version is missing or wrong; +- writes the group, name and version into the assembly as `TazelPluginAttribute`; +- makes `dotnet pack` write the archive and its `.sha256sums` instead of a `.nupkg`. The archive holds the plugin's + assemblies and those of its `ProjectReference`s and `PackageReference`s, and `tazel-plugin.json`; the plugin API and + the DSL are left out, whatever brought them. + +## The plugin + +```cs +using Progmasoft.Tazel.PluginApi; +using Progmasoft.Tazel.PluginApi.Steps; + +namespace Greeter; + +public sealed class Plugin : ITazelPlugin +{ + public void Apply(IPluginContext context) => context.Import("Greeter"); +} + +public static class Greetings +{ + public static Progmasoft.Tazel.Dsl.Common.Target File(string name, string text) => + Step.Declare(name, new() + { + Outputs = ["greeting.txt"], + Key = text, + Run = async (step, cancel) => + await System.IO.File.WriteAllTextAsync(Path.Combine(step.OutputDirectory, "greeting.txt"), text, cancel), + }); +} +``` + +- The entry assembly has one public class that implements `ITazelPlugin`, with a public constructor without parameters. + Tazel creates it and calls `Apply` before the `BUILD.csx` files of the module run. +- `IPluginContext.Import` lets every `BUILD.csx` of the module use a namespace without a `using`; `Status` prints a line. +- The public types of the plugin's assemblies are there for `BUILD.csx` files to call. + +## Steps + +`Step.Declare(name, new() { ... })` declares a build step; a `BUILD.csx` may call it directly too, with +`using Progmasoft.Tazel.PluginApi.Steps;`. + +| Setting | What it is | +| --- | --- | +| `Inputs` | files below the project file the step reads | +| `Outputs` | files the step writes, relative to its output directory | +| `Key` | text that changes what the step makes, such as its options | +| `Run` | the work: `(IStepContext step, CancellationToken cancel) => Task` | +| `Depends`, `Visibility`, `TargetConstraints`, `Tags` | as for every target | + +A step runs again only when its key, an input, an output or what it depends on changed. A step may depend on an +executable the build makes; `step.Dependencies["//:gen"]` is its path, and `step.RunAsync` runs a program directly with +the environment of the actions. A C-family or Zig target that depends on a step runs after it and finds headers in its +output directory. A step fails by throwing `PluginException` with a message; that message, the lines of `step.Log`, and +an output the step did not write are reported with it. + +## Loading + +```cs +// MODULE.csx +plugins = Plugins.Define(LocalPlugin.From("plugins/com.example.tools.greeter-0.1.0.tazel.tar.xz")); +``` + +Tazel unpacks the archive once below `.tazel/plugins`, checks `tazel-plugin.json` (group, name, SemVer version, and a +plugin API with the MAJOR and, before 1.0.0, the MINOR of this Tazel's), and loads the plugin's assemblies into a load +context of their own, so two plugins' libraries do not clash; `Progmasoft.Tazel.PluginApi` and +`Progmasoft.Tazel.Dsl` are Tazel's own copies, shared by every plugin. `Plugin.From`, a plugin of Tazel Portal, is +refused by this Tazel, which fetches nothing. diff --git a/docs/project-files.md b/docs/project-files.md index e0fd050..f3c6b56 100644 --- a/docs/project-files.md +++ b/docs/project-files.md @@ -53,8 +53,9 @@ toolchains = Toolchains.Define("//toolchains:clang"); - A dependency is a `LocalModule`: Tazel checks its archive against the SHA-256 and unpacks it once below `.tazel/`. Its public targets are `@name//dir:x`. `Module.From`, a module of Tazel Portal Modules, is refused by this Tazel, which fetches nothing. -- This Tazel reads `Cache.Remote`, `Execution.Remote`, `Execution.Memory` and `plugins` and says, as a warning, that - it does not act on them. +- `plugins` loads local plugin archives ([Plugins](plugins.md)). +- This Tazel reads `Cache.Remote`, `Execution.Remote` and `Execution.Memory` and says, as a warning, that it does not + act on them. ## BUILD.csx diff --git a/docs/reference/docfx.json b/docs/reference/docfx.json index beb01ba..d3e8516 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": [{ "src": "../..", "files": ["src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj", "src/Progmasoft.Tazel.PluginApi/Progmasoft.Tazel.PluginApi.csproj"] }], "dest": "api", "properties": { "TargetFramework": "net10.0" } } diff --git a/src/Progmasoft.Tazel.Dsl/Declarations.cs b/src/Progmasoft.Tazel.Dsl/Declarations.cs index ef12e03..66514d5 100644 --- a/src/Progmasoft.Tazel.Dsl/Declarations.cs +++ b/src/Progmasoft.Tazel.Dsl/Declarations.cs @@ -36,6 +36,9 @@ internal enum Family CC, ObjectiveC, Zig, + + /// <summary>A build step a plugin adds.</summary> + Plugin, } /// <summary>What a target makes.</summary> @@ -46,6 +49,9 @@ internal enum TargetKind Executable, Test, Module, + + /// <summary>A build step of a plugin.</summary> + Step, } /// <summary>A target as a project file declared it, before anything is checked against other files.</summary> diff --git a/src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj b/src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj index 4044ccc..2f0f7fc 100644 --- a/src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj +++ b/src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj @@ -4,9 +4,14 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <RootNamespace>Progmasoft.Tazel.Dsl</RootNamespace> + <IsPackable>true</IsPackable> + <PackageId>Progmasoft.Tazel.Dsl</PackageId> + <Description>The types MODULE.csx and BUILD.csx files of Tazel are written against.</Description> + <PackageTags>tazel;build</PackageTags> </PropertyGroup> <ItemGroup> <InternalsVisibleTo Include="tazel" /> <InternalsVisibleTo Include="Progmasoft.Tazel.Tests" /> + <InternalsVisibleTo Include="Progmasoft.Tazel.PluginApi" /> </ItemGroup> </Project> diff --git a/src/Progmasoft.Tazel.PluginApi/Plugin.cs b/src/Progmasoft.Tazel.PluginApi/Plugin.cs new file mode 100644 index 0000000..7bed5d5 --- /dev/null +++ b/src/Progmasoft.Tazel.PluginApi/Plugin.cs @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using Progmasoft.Tazel.Dsl.Common; + +namespace Progmasoft.Tazel.PluginApi; + +/// <summary> +/// A Tazel plugin: the one public class of its entry assembly that implements this interface and has a public +/// constructor without parameters. Tazel creates it and calls <see cref="Apply"/> before the BUILD.csx files of the +/// module run; the public types of the plugin's assemblies are then there for those files to use. +/// </summary> +public interface ITazelPlugin +{ + /// <summary>Prepares the plugin for one build of a module.</summary> + void Apply(IPluginContext context); +} + +/// <summary>What a plugin learns about the build, and what it can ask of Tazel when it is applied.</summary> +public interface IPluginContext +{ + /// <summary>The group of the plugin, as in <c>com.example.plugins</c>.</summary> + string Group { get; } + + /// <summary>The name of the plugin.</summary> + string Name { get; } + + /// <summary>The version of the plugin.</summary> + string Version { get; } + + /// <summary>The platform the build is for.</summary> + Platform Platform { get; } + + /// <summary>Whether the build is a debug or a release build.</summary> + BuildMode Mode { get; } + + /// <summary>The root of the module that uses the plugin.</summary> + string ModuleRoot { get; } + + /// <summary> + /// Lets every BUILD.csx of the module use the types of <paramref name="namespace"/> without a <c>using</c>. + /// </summary> + void Import(string @namespace); + + /// <summary>Says something to the user, as a status line of the build.</summary> + void Status(string message); +} + +/// <summary>The group, name and version of a plugin; Progmasoft.Tazel.PluginSdk writes it into the assembly.</summary> +/// <param name="group">The group, as in <c>com.example.plugins</c>.</param> +/// <param name="name">The name.</param> +/// <param name="version">The SemVer version.</param> +[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] +public sealed class TazelPluginAttribute(string group, string name, string version) : Attribute +{ + /// <summary>The group.</summary> + public string Group { get; } = group; + + /// <summary>The name.</summary> + public string Name { get; } = name; + + /// <summary>The version.</summary> + public string Version { get; } = version; +} + +/// <summary>What a plugin or one of its steps reports as a failure, with a message for the user.</summary> +public sealed class PluginException : Exception +{ + /// <summary>A failure and what to say about it.</summary> + public PluginException(string message) + : base(message) + { + } + + /// <summary>Nothing to say.</summary> + public PluginException() + { + } + + /// <summary>A failure and its cause.</summary> + public PluginException(string message, Exception inner) + : base(message, inner) + { + } +} diff --git a/src/Progmasoft.Tazel.PluginApi/Progmasoft.Tazel.PluginApi.csproj b/src/Progmasoft.Tazel.PluginApi/Progmasoft.Tazel.PluginApi.csproj new file mode 100644 index 0000000..0f21f11 --- /dev/null +++ b/src/Progmasoft.Tazel.PluginApi/Progmasoft.Tazel.PluginApi.csproj @@ -0,0 +1,19 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<!-- The API Tazel plugins are written against; the NuGet package Progmasoft.Tazel.PluginApi. --> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <RootNamespace>Progmasoft.Tazel.PluginApi</RootNamespace> + <IsPackable>true</IsPackable> + <PackageId>Progmasoft.Tazel.PluginApi</PackageId> + <Description>The API of Tazel plugins: a plugin, and the build steps it adds to BUILD.csx files.</Description> + <PackageTags>tazel;build;plugin</PackageTags> + </PropertyGroup> + <ItemGroup> + <ProjectReference Include="../Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj" /> + </ItemGroup> + <ItemGroup> + <InternalsVisibleTo Include="tazel" /> + <InternalsVisibleTo Include="Progmasoft.Tazel.Tests" /> + </ItemGroup> +</Project> diff --git a/src/Progmasoft.Tazel.PluginApi/Steps/Step.cs b/src/Progmasoft.Tazel.PluginApi/Steps/Step.cs new file mode 100644 index 0000000..d85c8c3 --- /dev/null +++ b/src/Progmasoft.Tazel.PluginApi/Steps/Step.cs @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Dsl.Build.Prelude; +using Progmasoft.Tazel.Dsl.Common; + +namespace Progmasoft.Tazel.PluginApi.Steps; + +/// <summary> +/// A build step: work of a plugin that reads <see cref="Inputs"/> and writes <see cref="Outputs"/> into its output +/// directory. It runs again only when its inputs, its outputs or its <see cref="Key"/> changed. A C-family or Zig target +/// that depends on it runs after it and finds headers in its output directory. +/// </summary> +public sealed class StepSettings : TargetSettings +{ + /// <summary>The files the step reads, below the project file.</summary> + public Files Inputs { get; init; } = Files.None; + + /// <summary>The files the step writes, relative to its output directory.</summary> + public IReadOnlyList<string> Outputs { get; init; } = []; + + /// <summary>What else changes what the step makes, such as its options; a different key runs it again.</summary> + public string Key { get; init; } = ""; + + /// <summary>The work of the step.</summary> + public Func<IStepContext, CancellationToken, Task>? Run { get; init; } +} + +/// <summary>Declares build steps; the methods of a plugin call it from the BUILD.csx files that use them.</summary> +public static class Step +{ + /// <summary>Declares the step <paramref name="name"/> in the BUILD.csx that is running.</summary> + public static Target Declare( + string name, StepSettings settings, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) + { + ArgumentNullException.ThrowIfNull(settings); + if (settings.Run is null) + { + throw new DslException($"{Declarations.Current.Place(line)}: the step '{name}' needs its Run"); + } + + return Declarations.Declare(Family.Plugin, TargetKind.Step, name, settings, file, line); + } +} + +/// <summary>Where a step runs and what it can ask of Tazel.</summary> +public interface IStepContext +{ + /// <summary>The label of the step.</summary> + string Label { get; } + + /// <summary>The root of the module of the step.</summary> + string ModuleRoot { get; } + + /// <summary>The directory of the project file that declared the step.</summary> + string PackageDirectory { get; } + + /// <summary>The directory the step writes its outputs to; it exists when the step runs.</summary> + string OutputDirectory { get; } + + /// <summary>The full paths of the inputs.</summary> + IReadOnlyList<string> Inputs { get; } + + /// <summary>The program or library each target the step depends on made, by its label, as a full path.</summary> + IReadOnlyDictionary<string, string> Dependencies { get; } + + /// <summary>The platform the build is for.</summary> + Platform Platform { get; } + + /// <summary>Whether the build is a debug or a release build.</summary> + BuildMode Mode { get; } + + /// <summary>The full path of a program on PATH, or null.</summary> + string? FindProgram(string name); + + /// <summary> + /// Runs <paramref name="program"/> directly, without a shell, with the environment of the actions of the build, in + /// <paramref name="workingDirectory"/> or the root of the module; the result has its exit status and output. + /// </summary> + Task<StepRun> RunAsync( + string program, IReadOnlyList<string> arguments, string? workingDirectory = null, + CancellationToken cancellationToken = default); + + /// <summary>Adds a line to what the step prints, shown with the step when the build reports it.</summary> + void Log(string message); +} + +/// <summary>What a program a step ran did.</summary> +/// <param name="ExitCode">Its exit status.</param> +/// <param name="Output">What it printed, its errors among it.</param> +public sealed record StepRun(int ExitCode, string Output); diff --git a/src/Progmasoft.Tazel.PluginSdk/PackTazelPlugin.cs b/src/Progmasoft.Tazel.PluginSdk/PackTazelPlugin.cs new file mode 100644 index 0000000..fef53df --- /dev/null +++ b/src/Progmasoft.Tazel.PluginSdk/PackTazelPlugin.cs @@ -0,0 +1,109 @@ +// 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; +using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; +using Progmasoft.Tazel.Archive; + +namespace Progmasoft.Tazel.PluginSdk; + +/// <summary> +/// Makes <c>$group.$name-$version.tazel.tar.xz</c> and its <c>.sha256sums</c> from the output of a plugin: its +/// assemblies and those of its references, with <c>tazel-plugin.json</c>. The plugin API and the DSL are left out, +/// whatever brought them, as Tazel has its own. +/// </summary> +public sealed class PackTazelPlugin : Task +{ + private static readonly string[] Shared = ["Progmasoft.Tazel.PluginApi.dll", "Progmasoft.Tazel.Dsl.dll"]; + + /// <summary>The output directory of the build.</summary> + [Required] + public string OutputDirectory { get; set; } = ""; + + /// <summary>The file of the plugin's own assembly.</summary> + [Required] + public string EntryAssembly { get; set; } = ""; + + /// <summary>The group of the plugin.</summary> + [Required] + public string Group { get; set; } = ""; + + /// <summary>The name of the plugin.</summary> + [Required] + public string Name { get; set; } = ""; + + /// <summary>The version of the plugin.</summary> + [Required] + public string Version { get; set; } = ""; + + /// <summary>The version of the plugin API the plugin was built against.</summary> + [Required] + public string PluginApiVersion { get; set; } = ""; + + /// <summary>Where the archive goes.</summary> + [Required] + public string PackageOutputPath { get; set; } = ""; + + /// <summary>The archive that was written.</summary> + [Output] + public string Archive { get; set; } = ""; + + /// <inheritdoc/> + public override bool Execute() + { + var files = Directory.EnumerateFiles(OutputDirectory, "*.dll", SearchOption.TopDirectoryOnly) + .Select(Path.GetFileName).OfType<string>() + .Where(file => !Shared.Contains(file, StringComparer.Ordinal)) + .Order(StringComparer.Ordinal) + .ToList(); + if (!files.Contains(EntryAssembly, StringComparer.Ordinal)) + { + Log.LogError($"{EntryAssembly} is not in {OutputDirectory}"); + return false; + } + + var staging = Path.Combine(Path.GetTempPath(), "tazel-plugin-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(staging); + try + { + foreach (var file in files) + { + 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"); + 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)); + Log.LogMessage(MessageImportance.High, $"Tazel plugin: {Archive}"); + return true; + } + catch (IOException error) + { + Log.LogError($"The plugin archive could not be written: {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 new file mode 100644 index 0000000..e72f031 --- /dev/null +++ b/src/Progmasoft.Tazel.PluginSdk/Progmasoft.Tazel.PluginSdk.csproj @@ -0,0 +1,44 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<!-- + The MSBuild project SDK of Tazel plugins: <Project Sdk="Progmasoft.Tazel.PluginSdk/x.y.z">. The package holds + Sdk/Sdk.props and Sdk/Sdk.targets, and in tasks/ the task that makes the plugin archive on dotnet pack. +--> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <RootNamespace>Progmasoft.Tazel.PluginSdk</RootNamespace> + <IsPackable>true</IsPackable> + <PackageId>Progmasoft.Tazel.PluginSdk</PackageId> + <PackageType>MSBuildSdk</PackageType> + <Description>The MSBuild project SDK of Tazel plugins: it references the plugin API, checks the plugin, and makes its .tazel.tar.xz on dotnet pack.</Description> + <PackageTags>tazel;build;plugin;msbuildsdk</PackageTags> + <IncludeBuildOutput>false</IncludeBuildOutput> + <SuppressDependenciesWhenPacking>true</SuppressDependenciesWhenPacking> + <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> + <NoWarn>$(NoWarn);NU5100;NU5128</NoWarn> + </PropertyGroup> + <ItemGroup> + <Compile Include="../Shared/*.cs" LinkBase="Shared" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Microsoft.Build.Utilities.Core" ExcludeAssets="runtime" PrivateAssets="all" /> + <PackageReference Include="Lzma.Net" PrivateAssets="all" /> + </ItemGroup> + <ItemGroup> + <None Include="Sdk/Sdk.targets" Pack="true" PackagePath="Sdk/" /> + </ItemGroup> + + <!-- Sdk.props carries the version of the SDK, which is the version of the plugin API it references. --> + <Target Name="WriteSdkProps" BeforeTargets="GenerateNuspec;_GetPackageFiles"> + <PropertyGroup> + <_TazelSdkProps>$(IntermediateOutputPath)Sdk.props</_TazelSdkProps> + </PropertyGroup> + <WriteLinesToFile File="$(_TazelSdkProps)" Overwrite="true" WriteOnlyWhenDifferent="true" + Lines="$([System.IO.File]::ReadAllText('$(MSBuildProjectDirectory)/Sdk/Sdk.props.in').Replace('@VERSION@', '$(Version)'))" /> + <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)LzmaNet.dll" Pack="true" PackagePath="tasks/net10.0/" /> + </ItemGroup> + </Target> +</Project> diff --git a/src/Progmasoft.Tazel.PluginSdk/Sdk/Sdk.props.in b/src/Progmasoft.Tazel.PluginSdk/Sdk/Sdk.props.in new file mode 100644 index 0000000..80abf48 --- /dev/null +++ b/src/Progmasoft.Tazel.PluginSdk/Sdk/Sdk.props.in @@ -0,0 +1,18 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<!-- The first half of the SDK of Tazel plugins, imported before the project. --> +<Project> + <PropertyGroup> + <TazelPluginSdkVersion>@VERSION@</TazelPluginSdkVersion> + </PropertyGroup> + <Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" /> + <PropertyGroup> + <TargetFramework>net10.0</TargetFramework> + <!-- The assemblies of the plugin's references go beside it, into its archive. --> + <EnableDynamicLoading>true</EnableDynamicLoading> + <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> + <ImplicitUsings Condition="'$(ImplicitUsings)' == ''">enable</ImplicitUsings> + <Nullable Condition="'$(Nullable)' == ''">enable</Nullable> + <IsPackable>true</IsPackable> + </PropertyGroup> +</Project> diff --git a/src/Progmasoft.Tazel.PluginSdk/Sdk/Sdk.targets b/src/Progmasoft.Tazel.PluginSdk/Sdk/Sdk.targets new file mode 100644 index 0000000..1e4a19e --- /dev/null +++ b/src/Progmasoft.Tazel.PluginSdk/Sdk/Sdk.targets @@ -0,0 +1,55 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<!-- The second half of the SDK of Tazel plugins, imported after the project. --> +<Project> + <!-- + The plugin compiles against the plugin API and never ships it: Tazel loads its own copy once, so every plugin shares + its types. The API is not passed on to what depends on the plugin either. + --> + <ItemGroup Condition="'$(ManagePackageVersionsCentrally)' != 'true'"> + <PackageReference Include="Progmasoft.Tazel.PluginApi" Version="$(TazelPluginSdkVersion)" + ExcludeAssets="runtime" PrivateAssets="all" /> + </ItemGroup> + <!-- With central package management the version of the SDK still decides the version of the API. --> + <ItemGroup Condition="'$(ManagePackageVersionsCentrally)' == 'true'"> + <PackageReference Include="Progmasoft.Tazel.PluginApi" VersionOverride="$(TazelPluginSdkVersion)" + ExcludeAssets="runtime" PrivateAssets="all" /> + </ItemGroup> + + <Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" /> + + <ItemGroup> + <AssemblyAttribute Include="Progmasoft.Tazel.PluginApi.TazelPluginAttribute"> + <_Parameter1>$(TazelPluginGroup)</_Parameter1> + <_Parameter2>$(TazelPluginName)</_Parameter2> + <_Parameter3>$(Version)</_Parameter3> + </AssemblyAttribute> + </ItemGroup> + + <Target Name="TazelPluginCheck" BeforeTargets="CoreCompile"> + <Error Condition="'$(TazelPluginGroup)' == ''" + Text="A Tazel plugin needs its group: <TazelPluginGroup>com.example.plugins</TazelPluginGroup>" /> + <Error Condition="'$(TazelPluginGroup)' != '' and !$([System.Text.RegularExpressions.Regex]::IsMatch('$(TazelPluginGroup)', '^[A-Za-z0-9_+-]+(\.[A-Za-z0-9_+-]+)*$'))" + Text="The group '$(TazelPluginGroup)' must be names joined by dots, such as com.example.plugins" /> + <Error Condition="'$(TazelPluginName)' == ''" + Text="A Tazel plugin needs its name: <TazelPluginName>plugin</TazelPluginName>" /> + <Error Condition="'$(TazelPluginName)' != '' and !$([System.Text.RegularExpressions.Regex]::IsMatch('$(TazelPluginName)', '^[A-Za-z0-9_+.-]+$'))" + Text="The name '$(TazelPluginName)' must be letters, digits and _ + . -" /> + <Error Condition="!$([System.Text.RegularExpressions.Regex]::IsMatch('$(Version)', '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$'))" + Text="The version '$(Version)' of a Tazel plugin is a SemVer version such as 0.1.0" /> + <Error Condition="'$(TargetFramework)' != 'net10.0'" + Text="A Tazel plugin targets net10.0, the runtime of Tazel, not $(TargetFramework)" /> + </Target> + + <UsingTask TaskName="Progmasoft.Tazel.PluginSdk.PackTazelPlugin" + AssemblyFile="$(MSBuildThisFileDirectory)../tasks/net10.0/Progmasoft.Tazel.PluginSdk.dll" /> + + <!-- dotnet pack makes the plugin's .tazel.tar.xz and its .sha256sums instead of a .nupkg. --> + <Target Name="Pack" DependsOnTargets="Build"> + <PackTazelPlugin OutputDirectory="$(TargetDir)" EntryAssembly="$(TargetFileName)" Group="$(TazelPluginGroup)" + Name="$(TazelPluginName)" Version="$(Version)" PluginApiVersion="$(TazelPluginSdkVersion)" + PackageOutputPath="$([System.IO.Path]::GetFullPath('$(PackageOutputPath)'))"> + <Output TaskParameter="Archive" PropertyName="TazelPluginArchive" /> + </PackTazelPlugin> + </Target> +</Project> diff --git a/src/Progmasoft.Tazel.PluginTemplates/Progmasoft.Tazel.PluginTemplates.csproj b/src/Progmasoft.Tazel.PluginTemplates/Progmasoft.Tazel.PluginTemplates.csproj new file mode 100644 index 0000000..f6867e5 --- /dev/null +++ b/src/Progmasoft.Tazel.PluginTemplates/Progmasoft.Tazel.PluginTemplates.csproj @@ -0,0 +1,34 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<!-- The template of dotnet new tazel-plugin. --> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <IsPackable>true</IsPackable> + <PackageId>Progmasoft.Tazel.PluginTemplates</PackageId> + <PackageType>Template</PackageType> + <Description>dotnet new tazel-plugin: a Tazel plugin with a build step.</Description> + <PackageTags>tazel;build;plugin;template</PackageTags> + <IncludeBuildOutput>false</IncludeBuildOutput> + <IncludeContentInPack>true</IncludeContentInPack> + <ContentTargetFolders>content</ContentTargetFolders> + <NoDefaultExcludes>true</NoDefaultExcludes> + <EnableDefaultCompileItems>false</EnableDefaultCompileItems> + <SuppressDependenciesWhenPacking>true</SuppressDependenciesWhenPacking> + <NoWarn>$(NoWarn);NU5128</NoWarn> + </PropertyGroup> + + <!-- The project of the template names the SDK of this version. --> + <Target Name="WriteTemplateProject" BeforeTargets="GenerateNuspec;_GetPackageFiles"> + <PropertyGroup> + <_TazelTemplateProject>$(IntermediateOutputPath)PluginProject.csproj</_TazelTemplateProject> + </PropertyGroup> + <WriteLinesToFile File="$(_TazelTemplateProject)" Overwrite="true" WriteOnlyWhenDifferent="true" + Lines="$([System.IO.File]::ReadAllText('$(MSBuildProjectDirectory)/content/tazel-plugin/PluginProject.csproj.in').Replace('@VERSION@', '$(Version)'))" /> + <ItemGroup> + <Content Include="content/tazel-plugin/.template.config/template.json" Pack="true" + PackagePath="content/tazel-plugin/.template.config/template.json" /> + <Content Include="content/tazel-plugin/Plugin.cs" Pack="true" PackagePath="content/tazel-plugin/Plugin.cs" /> + <Content Include="$(_TazelTemplateProject)" Pack="true" PackagePath="content/tazel-plugin/PluginProject.csproj" /> + </ItemGroup> + </Target> +</Project> diff --git a/src/Progmasoft.Tazel.PluginTemplates/content/tazel-plugin/.template.config/template.json b/src/Progmasoft.Tazel.PluginTemplates/content/tazel-plugin/.template.config/template.json new file mode 100644 index 0000000..2736b0d --- /dev/null +++ b/src/Progmasoft.Tazel.PluginTemplates/content/tazel-plugin/.template.config/template.json @@ -0,0 +1,28 @@ +{ + "$schema": "http://json.schemastore.org/template", + "author": "Progmasoft", + "classifications": ["Tazel", "Plugin", "Library"], + "identity": "Progmasoft.Tazel.PluginTemplates.TazelPlugin", + "name": "Tazel plugin", + "shortName": "tazel-plugin", + "description": "A Tazel plugin with a build step, packed by dotnet pack into a .tazel.tar.xz.", + "sourceName": "PluginProject", + "preferNameDirectory": true, + "tags": { "language": "C#", "type": "project" }, + "symbols": { + "group": { + "type": "parameter", + "datatype": "text", + "defaultValue": "com.example.plugins", + "replaces": "com.example.plugins", + "description": "The group of the plugin, as in com.example.plugins." + }, + "pluginName": { + "type": "parameter", + "datatype": "text", + "defaultValue": "plugin", + "replaces": "PLUGIN_NAME", + "description": "The name of the plugin." + } + } +} diff --git a/src/Progmasoft.Tazel.PluginTemplates/content/tazel-plugin/Plugin.cs b/src/Progmasoft.Tazel.PluginTemplates/content/tazel-plugin/Plugin.cs new file mode 100644 index 0000000..90e659c --- /dev/null +++ b/src/Progmasoft.Tazel.PluginTemplates/content/tazel-plugin/Plugin.cs @@ -0,0 +1,29 @@ +using Progmasoft.Tazel.PluginApi; +using Progmasoft.Tazel.PluginApi.Steps; + +namespace PluginProject; + +/// <summary>The plugin: Tazel creates it and applies it before the BUILD.csx files of a module run.</summary> +public sealed class Plugin : ITazelPlugin +{ + /// <inheritdoc/> + public void Apply(IPluginContext context) + { + // BUILD.csx files see PluginProject.Greetings without a using. + context.Import("PluginProject"); + } +} + +/// <summary>What BUILD.csx files of a module with this plugin can write: <c>Greetings.File("hello", "Hello!")</c>.</summary> +public static class Greetings +{ + /// <summary>A step that writes <paramref name="text"/> to <c>greeting.txt</c> in its output directory.</summary> + public static Progmasoft.Tazel.Dsl.Common.Target File(string name, string text) => + Step.Declare(name, new() + { + Outputs = ["greeting.txt"], + Key = text, + Run = async (step, cancel) => + await System.IO.File.WriteAllTextAsync(Path.Combine(step.OutputDirectory, "greeting.txt"), text + "\n", cancel), + }); +} diff --git a/src/Progmasoft.Tazel.PluginTemplates/content/tazel-plugin/PluginProject.csproj.in b/src/Progmasoft.Tazel.PluginTemplates/content/tazel-plugin/PluginProject.csproj.in new file mode 100644 index 0000000..13c9c6c --- /dev/null +++ b/src/Progmasoft.Tazel.PluginTemplates/content/tazel-plugin/PluginProject.csproj.in @@ -0,0 +1,7 @@ +<Project Sdk="Progmasoft.Tazel.PluginSdk/@VERSION@"> + <PropertyGroup> + <TazelPluginGroup>com.example.plugins</TazelPluginGroup> + <TazelPluginName>PLUGIN_NAME</TazelPluginName> + <Version>0.1.0</Version> + </PropertyGroup> +</Project> diff --git a/src/Progmasoft.Tazel/Archive/ModuleArchive.cs b/src/Progmasoft.Tazel/Archive/ModuleArchive.cs index 58835b4..7f0cb9a 100644 --- a/src/Progmasoft.Tazel/Archive/ModuleArchive.cs +++ b/src/Progmasoft.Tazel/Archive/ModuleArchive.cs @@ -28,14 +28,6 @@ internal static class ModuleArchive /// <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><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}"; @@ -83,58 +75,15 @@ 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) - { - 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 = System.IO.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 = System.IO.File.OpenRead(source); - entry.DataStream = data; - tar.WriteEntry(entry); - } - } - } - - System.IO.File.Move(temporary, archive, overwrite: true); - } - finally - { - System.IO.File.Delete(temporary); - } - } + public static void Write(string root, string baseName, string archive, IReadOnlyList<string> files) => + ReproducibleArchive.Write(root, baseName, archive, files); /// <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"/>. /// </summary> - public static string Unpack(string archive, string destination) + public static string Unpack(string archive, string destination, string requiredFile = ModuleFiles.ModuleFile) { var shown = Path.GetFileName(archive); var parent = Path.GetDirectoryName(Path.GetFullPath(destination))!; @@ -198,9 +147,9 @@ internal static class ModuleArchive throw new ProjectException($"{shown} is empty"); } - if (!System.IO.File.Exists(Path.Combine(work, top, ModuleFiles.ModuleFile))) + if (!System.IO.File.Exists(Path.Combine(work, top, requiredFile))) { - throw new ProjectException($"{shown} has no {top}/{ModuleFiles.ModuleFile}"); + throw new ProjectException($"{shown} has no {top}/{requiredFile}"); } Directory.Move(work, destination); @@ -219,39 +168,16 @@ internal static class ModuleArchive } } - private static bool IsExecutable(string file) => - !OperatingSystem.IsWindows() && - (System.IO.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); - } } /// <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) - { - using var stream = System.IO.File.OpenRead(file); - return Convert.ToHexStringLower(SHA256.HashData(stream)); - } + public static string Sha256(string file) => ReproducibleArchive.Sha256(file); /// <summary>The line of a <c>.sha256sums</c> file for <paramref name="file"/>.</summary> - public static string SumsLine(string file) => $"{Sha256(file)} {Path.GetFileName(file)}\n"; + public static string SumsLine(string file) => ReproducibleArchive.SumsLine(file); /// <summary> /// The SHA-256 that the <c>.sha256sums</c> text <paramref name="sums"/> gives for <paramref name="name"/>. Lines are diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index c44e801..650f0ee 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -99,11 +99,6 @@ internal sealed class Commands(Reporter reporter, string workingDirectory) { reporter.Warning("MODULE.csx sets Execution.Memory; this Tazel limits the actions by Jobs only"); } - - if (globals.plugins?.Items.Count > 0) - { - reporter.Warning("MODULE.csx names plugins; this Tazel loads no plugins"); - } } private int Clean(CleanCommand clean) @@ -198,8 +193,8 @@ internal sealed class Commands(Reporter reporter, string workingDirectory) var platform = flags.Platform ?? options.Platform ?? Host.Platform; var mode = flags.Mode ?? BuildMode.Debug; reporter.Status($"loading the module for {platform.Name()}, {mode.ToString().ToLowerInvariant()}"); - var workspace = await Workspace.LoadAsync(workingDirectory, new BuildContext(mode, platform), TazelVersion) - .ConfigureAwait(false); + var workspace = await Workspace.LoadAsync(workingDirectory, new BuildContext(mode, platform), TazelVersion, + reporter.Status).ConfigureAwait(false); WarnAboutWhatThisTazelDoesNotDo(workspace.Main.Globals); var execution = workspace.Main.Globals.execution?.Settings; var buildOptions = new BuildOptions diff --git a/src/Progmasoft.Tazel/Driver/Actions.cs b/src/Progmasoft.Tazel/Driver/Actions.cs index ad55a7d..9dfd349 100644 --- a/src/Progmasoft.Tazel/Driver/Actions.cs +++ b/src/Progmasoft.Tazel/Driver/Actions.cs @@ -38,6 +38,9 @@ internal sealed class BuildAction /// <summary>Work done in Tazel after the command succeeded, such as the links of a shared library.</summary> public Action? After { get; init; } + /// <summary>Work that runs in Tazel instead of <see cref="Command"/>, such as a step of a plugin.</summary> + public Func<System.Threading.CancellationToken, System.Threading.Tasks.Task<ProcessResult>>? Work { get; init; } + /// <summary>The actions whose outputs this one reads.</summary> public List<BuildAction> Prerequisites { get; } = []; diff --git a/src/Progmasoft.Tazel/Driver/Executor.cs b/src/Progmasoft.Tazel/Driver/Executor.cs index 63042d9..e52b24a 100644 --- a/src/Progmasoft.Tazel/Driver/Executor.cs +++ b/src/Progmasoft.Tazel/Driver/Executor.cs @@ -77,8 +77,10 @@ internal sealed class Executor(int jobs, bool keepGoing, ActionCache cache, Repo } cache.Forget(action); - var result = await Processes.RunAsync(action.Command, action.Directory, action.Environment, null, stop.Token) - .ConfigureAwait(false); + var result = action.Work is { } work + ? await work(stop.Token).ConfigureAwait(false) + : await Processes.RunAsync(action.Command, action.Directory, action.Environment, null, stop.Token) + .ConfigureAwait(false); if (result.Canceled) { // Stopped because another action failed: that one is reported, this one did not fail. diff --git a/src/Progmasoft.Tazel/Driver/Planner.cs b/src/Progmasoft.Tazel/Driver/Planner.cs index e5b7d62..2b0f5b7 100644 --- a/src/Progmasoft.Tazel/Driver/Planner.cs +++ b/src/Progmasoft.Tazel/Driver/Planner.cs @@ -79,7 +79,12 @@ internal sealed partial class Planner return known; } - var products = target.Family == Family.Zig ? PlanZig(target) : PlanCC(target); + var products = target.Family switch + { + Family.Zig => PlanZig(target), + Family.Plugin => PlanStep(target), + _ => PlanCC(target), + }; _planned[target] = products; return products; } diff --git a/src/Progmasoft.Tazel/Driver/StepPlanner.cs b/src/Progmasoft.Tazel/Driver/StepPlanner.cs new file mode 100644 index 0000000..0137330 --- /dev/null +++ b/src/Progmasoft.Tazel/Driver/StepPlanner.cs @@ -0,0 +1,155 @@ +// 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; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.PluginApi; +using Progmasoft.Tazel.PluginApi.Steps; +using Progmasoft.Tazel.Project; + +namespace Progmasoft.Tazel.Driver; + +/// <summary>The build steps of plugins: work that runs in Tazel, cached by its inputs, outputs and key.</summary> +internal sealed partial class Planner +{ + private TargetProducts PlanStep(ProjectTarget target) + { + var settings = (StepSettings)target.Settings; + var products = new TargetProducts(); + var directory = $"{Layout.PackageOut(target)}/_steps/{target.Label.Name}"; + var stamp = $"{directory}.step"; + var inputs = FileSets.Resolve(settings.Inputs, target.PackageDirectory, Layout.MainRoot, target.Place); + var outputs = settings.Outputs.Select(output => $"{directory}/{output}").ToList(); + var dependencies = new Dictionary<string, string>(StringComparer.Ordinal); + var prerequisites = new List<BuildAction>(); + foreach (var dependency in target.Dependencies) + { + var planned = Plan(dependency); + if (planned.Main is { } main) + { + prerequisites.Add(main); + } + + prerequisites.AddRange(planned.HeaderActions); + if ((planned.Executable ?? planned.Library) is { } made) + { + dependencies[dependency.Label.ToString()] = Layout.Full(made); + } + } + + // The command is the step's key: what it is apart from its files. + var command = new List<string> { "tazel-step", target.Label.ToString(), settings.Key }; + command.AddRange(settings.Outputs); + var action = new BuildAction + { + Description = $"Running {target.Label}", + Command = command, + Directory = Layout.MainRoot, + Inputs = inputs.Concat(dependencies.Values.Select(full => FileSets.ToRoot(full, Layout.MainRoot))).ToList(), + Outputs = [stamp, .. outputs], + Environment = ActionEnvironment, + Work = cancel => RunStepAsync(target, settings, directory, stamp, outputs, inputs, dependencies, cancel), + }; + action.Prerequisites.AddRange(prerequisites); + products.Main = action; + products.HeaderActions.Add(action); + products.PublicIncludes.Add(directory); + return products; + } + + private async Task<ProcessResult> RunStepAsync( + ProjectTarget target, StepSettings settings, string directory, string stamp, IReadOnlyList<string> outputs, + IReadOnlyList<string> inputs, IReadOnlyDictionary<string, string> dependencies, CancellationToken cancel) + { + var full = Layout.Full(directory); + Directory.CreateDirectory(full); + var context = new StepContext(this, target, full, inputs.Select(Layout.Full).ToList(), dependencies); + try + { + await settings.Run!(context, cancel).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancel.IsCancellationRequested) + { + return new ProcessResult(-1, context.Text, Canceled: true); + } + catch (PluginException error) + { + return new ProcessResult(1, context.Text + error.Message + "\n"); + } + catch (Exception error) when (error is not OutOfMemoryException) + { + return new ProcessResult(1, context.Text + $"{target.Place}: the step threw {error.GetType().Name}: {error.Message}\n"); + } + + var missing = outputs.FirstOrDefault(output => !File.Exists(Layout.Full(output))); + if (missing is not null) + { + return new ProcessResult(1, context.Text + $"the step said it writes {missing}, and did not\n"); + } + + await File.WriteAllTextAsync(Layout.Full(stamp), $"{target.Label}\n", cancel).ConfigureAwait(false); + return new ProcessResult(0, context.Text); + } + + private sealed class StepContext( + Planner planner, ProjectTarget target, string directory, IReadOnlyList<string> inputs, + IReadOnlyDictionary<string, string> dependencies) : IStepContext + { + private readonly StringBuilder _log = new(); + + public string Label => target.Label.ToString(); + + public string ModuleRoot => target.Module.Root; + + public string PackageDirectory => target.PackageDirectory; + + public string OutputDirectory => directory; + + public IReadOnlyList<string> Inputs => inputs; + + /// <summary>The program or library each dependency made, by its label.</summary> + public IReadOnlyDictionary<string, string> Dependencies => dependencies; + + public Platform Platform => planner.Options.Platform; + + public BuildMode Mode => planner.Options.Mode; + + public string Text + { + get + { + lock (_log) + { + return _log.ToString(); + } + } + } + + public string? FindProgram(string name) => Host.Which(name); + + public async Task<StepRun> RunAsync( + string program, IReadOnlyList<string> arguments, string? workingDirectory = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(arguments); + var found = Host.Which(program) ?? throw new PluginException($"{Label}: the program '{program}' is not found"); + var result = await Processes.RunAsync([found, .. arguments], workingDirectory ?? ModuleRoot, + planner.ActionEnvironment, null, cancellationToken).ConfigureAwait(false); + return new StepRun(result.ExitCode, result.Output); + } + + public void Log(string message) + { + lock (_log) + { + _log.Append(message).Append('\n'); + } + } + } +} diff --git a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj index e08f47b..e38dee0 100644 --- a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj +++ b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj @@ -11,6 +11,10 @@ </PropertyGroup> <ItemGroup> <ProjectReference Include="../Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj" /> + <ProjectReference Include="../Progmasoft.Tazel.PluginApi/Progmasoft.Tazel.PluginApi.csproj" /> + </ItemGroup> + <ItemGroup> + <Compile Include="../Shared/*.cs" LinkBase="Shared" /> </ItemGroup> <ItemGroup> <PackageReference Include="Spectre.Console" /> diff --git a/src/Progmasoft.Tazel/Project/Plugins.cs b/src/Progmasoft.Tazel/Project/Plugins.cs new file mode 100644 index 0000000..a571a7c --- /dev/null +++ b/src/Progmasoft.Tazel/Project/Plugins.cs @@ -0,0 +1,335 @@ +// 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.Reflection; +using System.Runtime.Loader; +using System.Text.Json; +using MetadataReference = Microsoft.CodeAnalysis.MetadataReference; +using Microsoft.CodeAnalysis.Scripting.Hosting; +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.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) +{ + public PluginManifest Manifest { get; } = manifest; + + public string Directory { get; } = directory; + + public AssemblyLoadContext Context { get; } = context; + + /// <summary>The plugin's own assemblies, every one loaded.</summary> + public List<Assembly> Assemblies { get; } = assemblies; + + /// <summary>The namespaces BUILD.csx files see without a <c>using</c>.</summary> + public List<string> Imports { get; } = []; + + public string Id => $"{Manifest.Group}.{Manifest.Name}"; +} + +/// <summary> +/// The plugins a MODULE.csx names. Each is a <c>.tazel.tar.xz</c> of the module with <c>tazel-plugin.json</c> at its top, +/// unpacked once below <c>.tazel/plugins</c>; its assemblies load into a load context of their own, so two plugins' +/// libraries never clash, while Progmasoft.Tazel.PluginApi and Progmasoft.Tazel.Dsl are Tazel's, so every plugin shares +/// their types with Tazel. +/// </summary> +internal static class Plugins +{ + public const string ManifestFile = "tazel-plugin.json"; + + private static readonly string[] Shared = ["Progmasoft.Tazel.PluginApi", "Progmasoft.Tazel.Dsl"]; + + /// <summary>The version of Progmasoft.Tazel.PluginApi this Tazel has.</summary> + public static Version ApiVersion { get; } = typeof(ITazelPlugin).Assembly.GetName().Version ?? new Version(0, 1, 0); + + /// <summary>Loads and applies the plugins of <paramref name="module"/>.</summary> + public static IReadOnlyList<LoadedPlugin> Load( + string mainRoot, LoadedModule module, BuildContext build, Action<string> status) + { + ArgumentNullException.ThrowIfNull(module); + var place = module.Shown(ModuleFiles.ModuleFile); + var loaded = new List<LoadedPlugin>(); + foreach (var reference in module.Globals.plugins?.Items ?? []) + { + if (reference.Path is null) + { + throw new ProjectException( + $"{place}: {reference.Group}.{reference.Name} is a plugin of Tazel Portal, and this Tazel fetches no " + + "plugins; use LocalPlugin.From with its archive"); + } + + var plugin = LoadOne(mainRoot, module, reference, place); + if (loaded.Any(other => other.Id == plugin.Id)) + { + throw new ProjectException($"{place}: the plugin {plugin.Id} is named twice"); + } + + Apply(plugin, module, build, status, place); + loaded.Add(plugin); + } + + return loaded; + } + + /// <summary>The references, imports and loader that let the BUILD.csx files of a module use its plugins.</summary> + public static ScriptEnvironment EnvironmentFor(IReadOnlyList<LoadedPlugin> plugins) + { + ArgumentNullException.ThrowIfNull(plugins); + if (plugins.Count == 0) + { + return ScriptEnvironment.Default; + } + + var loader = new InteractiveAssemblyLoader(); + var references = new List<MetadataReference>(); + foreach (var assembly in plugins.SelectMany(plugin => plugin.Assemblies)) + { + loader.RegisterDependency(assembly); + references.Add(MetadataReference.CreateFromFile(assembly.Location)); + } + + return ScriptEnvironment.Default.With(references, plugins.SelectMany(plugin => plugin.Imports), loader); + } + + private static LoadedPlugin LoadOne(string mainRoot, LoadedModule module, PluginReference reference, string place) + { + var path = reference.Path!; + if (path.Length == 0 || Path.IsPathRooted(path) || !path.EndsWith(ModuleArchive.Extension, StringComparison.Ordinal)) + { + throw new ProjectException($"{place}: '{path}' is not a {ModuleArchive.Extension} of this module"); + } + + var archive = Path.Combine(module.Root, path); + if (!File.Exists(archive) || new FileInfo(archive).LinkTarget is not null) + { + throw new ProjectException($"{place}: the plugin '{path}' is not a file of this module"); + } + + var sha = Sha256Sums.Sha256(archive); + var destination = Path.Combine(mainRoot, ModuleFiles.StateDirectory, "plugins", sha[..32]); + var marker = Path.Combine(destination, ".unpacked"); + string directory; + if (File.Exists(marker)) + { + directory = Path.Combine(destination, File.ReadAllText(marker).Trim()); + } + else + { + if (Directory.Exists(destination)) + { + Directory.Delete(destination, recursive: true); + } + + directory = ModuleArchive.Unpack(archive, destination, ManifestFile); + File.WriteAllText(marker, Path.GetFileName(directory)); + } + + var manifest = ReadManifest(Path.Combine(directory, ManifestFile), path); + CheckManifest(manifest, path); + var context = new PluginLoadContext(manifest.Group + "." + manifest.Name, directory); + var assemblies = new List<Assembly>(); + Assembly? entry = null; + foreach (var file in Directory.EnumerateFiles(directory, "*.dll").Order(StringComparer.Ordinal)) + { + var name = Path.GetFileNameWithoutExtension(file); + if (Shared.Contains(name, StringComparer.Ordinal)) + { + // Tazel's own copy is the one every plugin uses. + continue; + } + + Assembly assembly; + try + { + assembly = context.LoadFromAssemblyPath(Path.GetFullPath(file)); + } + catch (BadImageFormatException error) + { + throw new ProjectException($"{path}: {Path.GetFileName(file)} is not a .NET assembly: {error.Message}", error); + } + + assemblies.Add(assembly); + if (string.Equals(Path.GetFileName(file), manifest.EntryAssembly, StringComparison.Ordinal)) + { + entry = assembly; + } + } + + if (entry is null) + { + throw new ProjectException($"{path}: its manifest names the entry assembly {manifest.EntryAssembly}, which it does not hold"); + } + + var plugin = new LoadedPlugin(manifest, directory, context, assemblies); + plugin.Assemblies.Remove(entry); + plugin.Assemblies.Insert(0, entry); + return plugin; + } + + private static PluginManifest 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); + } + } + + private static void CheckManifest(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"); + } + + if (!Version.TryParse(manifest.PluginApi ?? "", out var api)) + { + throw new ProjectException($"{shown}: '{manifest.PluginApi}' is not the version of a plugin API"); + } + + // Before 1.0.0 a new MINOR may change the API, so a plugin needs the MAJOR and MINOR it was built against. + var compatible = ApiVersion.Major == 0 + ? api.Major == 0 && api.Minor == ApiVersion.Minor + : api.Major == ApiVersion.Major && api.Minor <= ApiVersion.Minor; + if (!compatible) + { + throw new ProjectException( + $"{shown} was built against Progmasoft.Tazel.PluginApi {api.ToString(3)}, and this Tazel has " + + $"{ApiVersion.ToString(3)}"); + } + + if (string.IsNullOrEmpty(manifest.EntryAssembly) || manifest.EntryAssembly.Contains('/', StringComparison.Ordinal) || + manifest.EntryAssembly.Contains('\\', StringComparison.Ordinal) || + !manifest.EntryAssembly.EndsWith(".dll", StringComparison.Ordinal)) + { + throw new ProjectException($"{shown}: the entry assembly '{manifest.EntryAssembly}' is not a .dll at the top"); + } + } + + private static void Apply(LoadedPlugin plugin, LoadedModule module, BuildContext build, Action<string> status, string place) + { + var entry = plugin.Assemblies[0]; + Type[] types; + try + { + types = entry.GetExportedTypes(); + } + catch (Exception error) when (error is ReflectionTypeLoadException or FileNotFoundException or FileLoadException) + { + throw new ProjectException($"{place}: the plugin {plugin.Id} cannot be loaded: {error.Message}", error); + } + + var candidates = types.Where(type => typeof(ITazelPlugin).IsAssignableFrom(type) && type is { IsClass: true, IsAbstract: false }) + .ToList(); + if (candidates.Count != 1) + { + throw new ProjectException( + $"{place}: the entry assembly of {plugin.Id} has {candidates.Count} public classes that implement ITazelPlugin; it needs one"); + } + + if (candidates[0].GetConstructor(Type.EmptyTypes) is null) + { + throw new ProjectException($"{place}: {candidates[0].FullName} of {plugin.Id} has no public constructor without parameters"); + } + + try + { + var instance = (ITazelPlugin)Activator.CreateInstance(candidates[0])!; + instance.Apply(new Context(plugin, module, build, status)); + } + catch (TargetInvocationException error) when (error.InnerException is not null) + { + throw Failed(plugin, place, error.InnerException); + } + catch (PluginException error) + { + throw new ProjectException($"{place}: the plugin {plugin.Id}: {error.Message}", error); + } + catch (Exception error) when (error is not ProjectException and not OutOfMemoryException) + { + throw Failed(plugin, place, error); + } + } + + private static ProjectException Failed(LoadedPlugin plugin, string place, Exception error) => + new($"{place}: the plugin {plugin.Id} failed when it was applied: {error.GetType().Name}: {error.Message}", error); + + private sealed class Context(LoadedPlugin plugin, LoadedModule module, BuildContext build, Action<string> status) : IPluginContext + { + public string Group => plugin.Manifest.Group; + + public string Name => plugin.Manifest.Name; + + public string Version => plugin.Manifest.Version; + + public Platform Platform => build.Platform; + + public BuildMode Mode => build.Mode; + + public string ModuleRoot => module.Root; + + public void Import(string @namespace) + { + if (string.IsNullOrWhiteSpace(@namespace) || @namespace.Split('.').Any(part => part.Length == 0)) + { + throw new PluginException($"'{@namespace}' is not a namespace"); + } + + if (!plugin.Imports.Contains(@namespace, StringComparer.Ordinal)) + { + plugin.Imports.Add(@namespace); + } + } + + public void Status(string message) => status($"{plugin.Id}: {message}"); + } + + /// <summary>The load context of one plugin: its own assemblies from its directory, Tazel's shared ones from Tazel.</summary> + private sealed class PluginLoadContext(string name, string directory) : AssemblyLoadContext(name, isCollectible: false) + { + protected override Assembly? Load(AssemblyName assemblyName) + { + if (assemblyName.Name is null || Shared.Contains(assemblyName.Name, StringComparer.Ordinal)) + { + return null; + } + + var file = Path.Combine(directory, assemblyName.Name + ".dll"); + return File.Exists(file) ? LoadFromAssemblyPath(Path.GetFullPath(file)) : null; + } + } +} diff --git a/src/Progmasoft.Tazel/Project/ScriptHost.cs b/src/Progmasoft.Tazel/Project/ScriptHost.cs index e944513..0b1c3a6 100644 --- a/src/Progmasoft.Tazel/Project/ScriptHost.cs +++ b/src/Progmasoft.Tazel/Project/ScriptHost.cs @@ -12,6 +12,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; +using Microsoft.CodeAnalysis.Scripting.Hosting; using Progmasoft.Tazel.Dsl; namespace Progmasoft.Tazel.Project; @@ -43,16 +44,19 @@ internal static class ScriptHost /// <summary>The namespace every project file sees without a <c>using</c>.</summary> public const string CommonNamespace = "Progmasoft.Tazel.Dsl.Common"; - private static readonly ScriptOptions BaseOptions = CreateOptions(); + /// <summary>The options every project file is compiled with.</summary> + internal static ScriptOptions BaseOptions { get; } = CreateOptions(); /// <summary> /// Compiles and runs <paramref name="code"/> with <paramref name="globals"/>; <paramref name="shownPath"/> names /// the file in messages. A compile error or an exception of the script becomes a <see cref="ProjectException"/>. /// </summary> - public static async Task RunAsync<TGlobals>(string code, string shownPath, TGlobals globals) + public static async Task RunAsync<TGlobals>( + string code, string shownPath, TGlobals globals, ScriptEnvironment? environment = null) where TGlobals : class { - var script = CSharpScript.Create(code, BaseOptions.WithFilePath(shownPath), typeof(TGlobals)); + var used = environment ?? ScriptEnvironment.Default; + var script = CSharpScript.Create(code, used.Options.WithFilePath(shownPath), typeof(TGlobals), used.Loader); var errors = script.Compile().Where(d => d.Severity == DiagnosticSeverity.Error).ToList(); if (errors.Count > 0) { @@ -90,7 +94,11 @@ internal static class ScriptHost } } - foreach (var assembly in new[] { typeof(object).Assembly, typeof(Enumerable).Assembly, typeof(DslException).Assembly }) + foreach (var assembly in new[] + { + typeof(object).Assembly, typeof(Enumerable).Assembly, typeof(DslException).Assembly, + typeof(PluginApi.ITazelPlugin).Assembly, + }) { references.Add(MetadataReference.CreateFromFile(assembly.Location)); } @@ -134,10 +142,27 @@ internal static class ScriptHost return ""; } +} + +/// <summary>What a project file is compiled with beyond the DSL: the plugins' references, imports and loader.</summary> +internal sealed class ScriptEnvironment +{ + private ScriptEnvironment(ScriptOptions options, InteractiveAssemblyLoader? loader) + { + Options = options; + Loader = loader; + } + + /// <summary>The DSL alone.</summary> + public static ScriptEnvironment Default { get; } = new(ScriptHost.BaseOptions, null); + + public ScriptOptions Options { get; } - /// <summary>Whether a type is from the DSL, for messages that name what a script returned.</summary> - public static bool IsDslType(Type type) => type.Assembly == typeof(DslException).Assembly; + /// <summary>The loader that finds the plugins' assemblies in their load contexts; null without plugins.</summary> + public InteractiveAssemblyLoader? Loader { get; } - /// <summary>The assembly of the DSL, for diagnostics.</summary> - public static Assembly DslAssembly => typeof(DslException).Assembly; + /// <summary>This environment with more references and imports, and the loader of the plugins.</summary> + public ScriptEnvironment With( + IEnumerable<MetadataReference> references, IEnumerable<string> imports, InteractiveAssemblyLoader loader) => + new(Options.AddReferences(references).AddImports(imports), loader); } diff --git a/src/Progmasoft.Tazel/Project/TargetChecks.cs b/src/Progmasoft.Tazel/Project/TargetChecks.cs index 1d06ae9..7e05b43 100644 --- a/src/Progmasoft.Tazel/Project/TargetChecks.cs +++ b/src/Progmasoft.Tazel/Project/TargetChecks.cs @@ -61,6 +61,18 @@ internal static class TargetChecks } } + if (target.Family == Family.Plugin) + { + foreach (var output in ((PluginApi.Steps.StepSettings)target.Settings).Outputs) + { + if (output.Length == 0 || System.IO.Path.IsPathRooted(output) || output.Contains('\\', StringComparison.Ordinal) || + output.Split('/').Any(part => part is "" or "." or "..")) + { + throw new ProjectException($"{place}: the output '{output}' must be a path below the step's output directory"); + } + } + } + if (target.Family == Family.Zig && target.Settings is not ZigModuleSettings) { throw new ProjectException($"{place}: {target.Label} has settings of another family"); diff --git a/src/Progmasoft.Tazel/Project/Workspace.cs b/src/Progmasoft.Tazel/Project/Workspace.cs index 2986964..49fa7e3 100644 --- a/src/Progmasoft.Tazel/Project/Workspace.cs +++ b/src/Progmasoft.Tazel/Project/Workspace.cs @@ -96,16 +96,17 @@ internal sealed class Workspace public List<ProjectToolchain> Registered { get; } = []; /// <summary>Loads the module that <paramref name="directory"/> is in, with the modules it depends on.</summary> - public static async Task<Workspace> LoadAsync(string directory, BuildContext build, Version tazelVersion) + public static async Task<Workspace> LoadAsync( + string directory, BuildContext build, Version tazelVersion, Action<string>? status = null) { var root = ModuleFiles.FindRoot(directory); var main = await LoadModuleAsync(root, null, tazelVersion).ConfigureAwait(false); var workspace = new Workspace(main); await workspace.LoadDependenciesAsync(main, tazelVersion).ConfigureAwait(false); - await workspace.LoadPackagesAsync(main, build).ConfigureAwait(false); + await workspace.LoadPackagesAsync(main, build, status ?? (_ => { })).ConfigureAwait(false); foreach (var module in workspace.External.Values) { - await workspace.LoadPackagesAsync(module, build).ConfigureAwait(false); + await workspace.LoadPackagesAsync(module, build, status ?? (_ => { })).ConfigureAwait(false); } workspace.Resolve(); @@ -184,8 +185,14 @@ internal sealed class Workspace } } - private async Task LoadPackagesAsync(LoadedModule module, BuildContext build) + /// <summary>The plugins each module loaded, by its repository (null for the main module).</summary> + public Dictionary<string, IReadOnlyList<LoadedPlugin>> PluginsOf { get; } = new(StringComparer.Ordinal); + + private async Task LoadPackagesAsync(LoadedModule module, BuildContext build, Action<string> status) { + var plugins = Plugins.Load(Main.Root, module, build, status); + PluginsOf[module.Repository ?? ""] = plugins; + var environment = Plugins.EnvironmentFor(plugins); var packages = ModuleFiles.Packages(module.Root); var scopes = await Task.WhenAll(packages.Select(package => Task.Run(async () => { @@ -194,7 +201,7 @@ internal sealed class Workspace var code = await File.ReadAllTextAsync(package.File).ConfigureAwait(false); using (Declarations.Enter(scope)) { - await ScriptHost.RunAsync(code, shown, new BuildGlobals(build)).ConfigureAwait(false); + await ScriptHost.RunAsync(code, shown, new BuildGlobals(build), environment).ConfigureAwait(false); } return (Package: package, Scope: scope); @@ -241,7 +248,8 @@ internal sealed class Workspace foreach (var reference in target.Settings.Depends.Items) { var found = Find(reference.Label, target); - if (found.Kind is TargetKind.Executable or TargetKind.Test) + // A step may need a program the build makes; what compiles and links takes libraries and steps. + if (found.Kind is TargetKind.Executable or TargetKind.Test && target.Family != Family.Plugin) { throw new ProjectException($"{target.Place}: {found.Label} is a {Describe(found)}; only libraries are linked"); } diff --git a/src/Shared/ReproducibleArchive.cs b/src/Shared/ReproducibleArchive.cs new file mode 100644 index 0000000..ff4c5de --- /dev/null +++ b/src/Shared/ReproducibleArchive.cs @@ -0,0 +1,106 @@ +// 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/PluginTests.cs b/tests/Progmasoft.Tazel.Tests/PluginTests.cs new file mode 100644 index 0000000..740e285 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/PluginTests.cs @@ -0,0 +1,219 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Progmasoft.Tazel.Archive; +using Progmasoft.Tazel.Project; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class StepTests +{ + private const string Build = """ + using System.IO; + using Progmasoft.Tazel.Dsl.Build.Prelude; + using Progmasoft.Tazel.PluginApi; + using Progmasoft.Tazel.PluginApi.Steps; + Step.Declare("copy", new() + { + Inputs = ["in.txt"], + Outputs = ["out.txt"], + Key = "1", + Run = async (step, cancel) => + { + step.Log("copying"); + File.WriteAllText(Path.Combine(step.OutputDirectory, "out.txt"), File.ReadAllText(step.Inputs[0]).ToUpperInvariant()); + await System.Threading.Tasks.Task.CompletedTask; + }, + }); + Step.Declare("lies", new() { Outputs = ["never.txt"], Tags = ["manual"], Run = (step, cancel) => System.Threading.Tasks.Task.CompletedTask }); + Step.Declare("fails", new() { Tags = ["manual"], Run = (step, cancel) => throw new PluginException("the step cannot go on") }); + """; + + [Fact] + public async Task AStepRunsOnceUntilItsInputChanges() + { + using var module = new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile).Write("BUILD.csx", Build).Write("in.txt", "hello"); + var (status, output) = await module.TazelAsync(".", "build", "//..."); + Assert.True(status == 0, output); + Assert.Contains("Running //:copy\ncopying", output, StringComparison.Ordinal); + var made = Directory.GetFiles(Path.Combine(module.Root, ".tazel"), "out.txt", SearchOption.AllDirectories).Single(); + Assert.Equal("HELLO", await File.ReadAllTextAsync(made, TestContext.Current.CancellationToken)); + + (status, output) = await module.TazelAsync(".", "build", "//..."); + Assert.True(status == 0, output); + Assert.DoesNotContain("Running", output, StringComparison.Ordinal); + + module.Write("in.txt", "again"); + (status, output) = await module.TazelAsync(".", "build", "//..."); + Assert.True(status == 0, output); + Assert.Contains("Running //:copy", output, StringComparison.Ordinal); + } + + [Theory] + [InlineData("//:lies", "the step said it writes")] + [InlineData("//:fails", "the step cannot go on")] + public async Task AFailedStepSaysWhy(string label, string message) + { + using var module = new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile).Write("BUILD.csx", Build).Write("in.txt", "hello"); + var (status, output) = await module.TazelAsync(".", "build", label); + Assert.Equal(1, status); + Assert.Contains($"FAILED Running {label}", output, StringComparison.Ordinal); + Assert.Contains(message, output, StringComparison.Ordinal); + } + + [Fact] + public async Task AStepNeedsItsWork() + { + using var module = new TemporaryModule().Write("MODULE.csx", TemporaryModule.ModuleFile).Write("BUILD.csx", """ + using Progmasoft.Tazel.PluginApi.Steps; + Step.Declare("idle", new()); + """); + var error = await Assert.ThrowsAsync<ProjectException>(() => module.LoadAsync()); + Assert.Contains("BUILD.csx:2: the step 'idle' needs its Run", error.Message, StringComparison.Ordinal); + } +} + +public sealed class PluginLoadingTests +{ + [Fact] + public async Task APluginOfTazelPortalIsRefused() + { + using var module = new TemporaryModule() + .Write("MODULE.csx", TemporaryModule.ModuleFile + "\nplugins = Plugins.Define(Plugin.From(\"com.example\", \"x\", \"1.0.0\"));"); + var error = await Assert.ThrowsAsync<ProjectException>(() => module.LoadAsync()); + Assert.Contains("this Tazel fetches no plugins; use LocalPlugin.From", error.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData("""{"group":"com.example","name":"x","version":"1.0.0","pluginApi":"9.0.0","entryAssembly":"X.dll"}""", "was built against Progmasoft.Tazel.PluginApi 9.0.0")] + [InlineData("""{"group":"com.example","name":"x","version":"1.0","pluginApi":"0.1.0","entryAssembly":"X.dll"}""", "'1.0' is not a SemVer version")] + [InlineData("""{"group":"com..example","name":"x","version":"1.0.0","pluginApi":"0.1.0","entryAssembly":"X.dll"}""", "is not names joined by dots")] + [InlineData("""{"group":"com.example","name":"x","version":"1.0.0","pluginApi":"0.1.0","entryAssembly":"X.dll"}""", "names the entry assembly X.dll, which it does not hold")] + [InlineData("""not json""", "cannot be read")] + public async Task APluginArchiveIsChecked(string manifest, string message) + { + using var module = new TemporaryModule(); + module.Write("plugin/tazel-plugin.json", manifest); + ModuleArchive.Write(Path.Combine(module.Root, "plugin"), "com.example.x-1.0.0", + Path.Combine(module.Root, "plugins", "x.tazel.tar.xz"), ["tazel-plugin.json"]); + module.Write("MODULE.csx", TemporaryModule.ModuleFile + "\nplugins = Plugins.Define(LocalPlugin.From(\"plugins/x.tazel.tar.xz\"));"); + var error = await Assert.ThrowsAsync<ProjectException>(() => module.LoadAsync()); + Assert.Contains(message, error.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task AnArchiveWithoutAManifestIsNotAPlugin() + { + using var module = new TemporaryModule(); + module.Write("plugin/readme.txt", "x"); + ModuleArchive.Write(Path.Combine(module.Root, "plugin"), "x", Path.Combine(module.Root, "x.tazel.tar.xz"), ["readme.txt"]); + module.Write("MODULE.csx", TemporaryModule.ModuleFile + "\nplugins = Plugins.Define(LocalPlugin.From(\"x.tazel.tar.xz\"));"); + var error = await Assert.ThrowsAsync<ProjectException>(() => module.LoadAsync()); + Assert.Contains("has no x/tazel-plugin.json", error.Message, StringComparison.Ordinal); + } +} + +/// <summary> +/// The packages of the plugin API, the SDK and the template, packed and used as a plugin author uses them: dotnet new +/// tazel-plugin, dotnet pack, and a module that loads the archive. +/// </summary> +public sealed class PluginSdkTests +{ + [Fact] + public async Task APluginFromTheTemplateIsPackedAndLoaded() + { + var repository = Repository(); + Assert.SkipWhen(repository is null || Environment.GetEnvironmentVariable("TAZEL_SKIP_SDK_TESTS") == "1", + "the sources of the packages are not beside the tests"); + using var work = new TemporaryModule(); + var feed = Path.Combine(work.Root, "feed"); + string[] isolated = [$"NUGET_PACKAGES={Path.Combine(work.Root, "packages")}"]; + foreach (var project in new[] { "Dsl", "PluginApi", "PluginSdk", "PluginTemplates" }) + { + await Run(work.Root, isolated, "pack", Path.Combine(repository!, "src", $"Progmasoft.Tazel.{project}"), + "-c", "Release", "-o", feed); + } + + work.Write("nuget.config", $""" + <?xml version="1.0" encoding="utf-8"?> + <configuration> + <packageSources> + <clear /> + <add key="local" value="{feed}" /> + <add key="nuget.org" value="https://api.nuget.org/v3/index.json" /> + </packageSources> + </configuration> + """); + var hive = Path.Combine(work.Root, "hive"); + await Run(work.Root, isolated, "new", "install", Path.Combine(feed, "Progmasoft.Tazel.PluginTemplates.0.1.0.nupkg"), + "--debug:custom-hive", hive); + await Run(work.Root, isolated, "new", "tazel-plugin", "-n", "Greeter", "--group", "com.example.tools", + "--pluginName", "greeter", "--debug:custom-hive", hive); + 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), + 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")); + work.Write("module/MODULE.csx", TemporaryModule.ModuleFile + "\nplugins = Plugins.Define(LocalPlugin.From(\"plugins/greeter.tazel.tar.xz\"));") + .Write("module/BUILD.csx", "Greetings.File(\"hello\", \"Hello from a plugin\");"); + var (status, output) = await work.TazelAsync("module", "build", "//..."); + Assert.True(status == 0, output); + var greeting = Directory.GetFiles(Path.Combine(work.Root, "module", ".tazel"), "greeting.txt", SearchOption.AllDirectories) + .Single(); + Assert.Equal("Hello from a plugin\n", await File.ReadAllTextAsync(greeting, TestContext.Current.CancellationToken)); + } + + private static string? Repository() + { + for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent) + { + if (File.Exists(Path.Combine(directory.FullName, "Tazel.slnx"))) + { + return directory.FullName; + } + } + + return null; + } + + private static async Task Run(string directory, string[] environment, params string[] arguments) + { + var start = new ProcessStartInfo("dotnet") + { + WorkingDirectory = directory, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }; + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + foreach (var entry in environment) + { + var equals = entry.IndexOf('=', StringComparison.Ordinal); + start.Environment[entry[..equals]] = entry[(equals + 1)..]; + } + + // The SDK of the test run would otherwise pass its own build to the dotnet it starts. + start.Environment.Remove("MSBuildExtensionsPath"); + start.Environment.Remove("MSBuildSDKsPath"); + start.Environment.Remove("MSBUILD_EXE_PATH"); + using var process = Process.Start(start)!; + var output = process.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken); + var errors = process.StandardError.ReadToEndAsync(TestContext.Current.CancellationToken); + await process.WaitForExitAsync(TestContext.Current.CancellationToken); + Assert.True(process.ExitCode == 0, $"dotnet {string.Join(' ', arguments)} failed:\n{await output}{await errors}"); + } +}