tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Check the names of Tazel Portal Modules, and fix the remaining findings
- Commit
0647c27f7ae9c5eb61db2479235dcacca547b1b6- Author
- Leitwolf11 ·
- Parents
9b4858da9a79
Changes
THIRD-PARTY-NOTICES.md | 6 +- src/Progmasoft.Tazel.PluginApi/Steps/Step.cs | 11 +- src/Progmasoft.Tazel/Archive/ModuleArchive.cs | 25 ++-- src/Progmasoft.Tazel/Cli/CommandLine.cs | 19 ++- src/Progmasoft.Tazel/Driver/StepPlanner.cs | 4 +- src/Progmasoft.Tazel/Driver/TestRunner.cs | 28 +++-- src/Progmasoft.Tazel/MicroVM/Sandbox.cs | 5 +- src/Progmasoft.Tazel/Portal/PortalModules.cs | 47 ++++++++ src/Progmasoft.Tazel/Program.cs | 12 +- src/Progmasoft.Tazel/Project/Plugins.cs | 113 +++++++++--------- src/Progmasoft.Tazel/Project/PortalDependencies.cs | 130 +++++++++++++-------- src/Progmasoft.Tazel/Project/Workspace.cs | 38 +++--- .../Progmasoft.Tazel.Tests/QueryAndPortalTests.cs | 38 +++++- tests/Progmasoft.Tazel.Tests/Snapshots.cs | 9 +- 14 files changed, 322 insertions(+), 163 deletions(-) diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 01422e4..9560b09 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -23,9 +23,9 @@ Contributors): | Component | License | Source | | --- | --- | --- | -| Linux 6.18.64 | GPL-2.0-only WITH Linux-syscall-note | https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.18.64.tar.xz | -| musl 1.2.6 (Alpine musl-1.2.6-r3) | MIT | https://musl.libc.org | -| libgcc and libstdc++ of GCC 15.2.0 (Alpine 15.2.0-r5) | GPL-3.0-or-later WITH GCC-exception-3.1 | https://gcc.gnu.org | +| Linux 6.18.64 | GPL-2.0-only WITH Linux-syscall-note | <https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.18.64.tar.xz> | +| musl 1.2.6 (Alpine musl-1.2.6-r3) | MIT | <https://musl.libc.org> | +| libgcc and libstdc++ of GCC 15.2.0 (Alpine 15.2.0-r5) | GPL-3.0-or-later WITH GCC-exception-3.1 | <https://gcc.gnu.org> | Cloud Hypervisor (Apache-2.0 AND BSD-3-Clause) and virtiofsd (Apache-2.0 AND BSD-3-Clause) are not shipped: Tazel fetches Cloud Hypervisor from its release and uses the host's virtiofsd. diff --git a/src/Progmasoft.Tazel.PluginApi/Steps/Step.cs b/src/Progmasoft.Tazel.PluginApi/Steps/Step.cs index d85c8c3..68442f3 100644 --- a/src/Progmasoft.Tazel.PluginApi/Steps/Step.cs +++ b/src/Progmasoft.Tazel.PluginApi/Steps/Step.cs @@ -84,8 +84,15 @@ public interface IStepContext /// <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); + string program, IReadOnlyList<string> arguments, string? workingDirectory, CancellationToken cancellationToken); + + /// <summary>Runs <paramref name="program"/> in the root of the module; see the overload with every parameter.</summary> + Task<StepRun> RunAsync(string program, IReadOnlyList<string> arguments) => + RunAsync(program, arguments, null, CancellationToken.None); + + /// <summary>Runs <paramref name="program"/> in <paramref name="workingDirectory"/>; see the overload with every parameter.</summary> + Task<StepRun> RunAsync(string program, IReadOnlyList<string> arguments, string? workingDirectory) => + RunAsync(program, arguments, workingDirectory, CancellationToken.None); /// <summary>Adds a line to what the step prints, shown with the step when the build reports it.</summary> void Log(string message); diff --git a/src/Progmasoft.Tazel/Archive/ModuleArchive.cs b/src/Progmasoft.Tazel/Archive/ModuleArchive.cs index 61306b0..a5957a7 100644 --- a/src/Progmasoft.Tazel/Archive/ModuleArchive.cs +++ b/src/Progmasoft.Tazel/Archive/ModuleArchive.cs @@ -78,6 +78,20 @@ internal static class ModuleArchive public static void Write(string root, string baseName, string archive, IReadOnlyList<string> files) => ReproducibleArchive.Write(root, baseName, archive, files); + /// <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) { @@ -160,16 +174,7 @@ internal static class ModuleArchive } } - 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}"); - } - + CheckUnpacked(work, top, requiredFile, shown); Directory.Move(work, destination); return Path.Combine(destination, top); } diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index c617c67..f846da6 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -203,6 +203,19 @@ internal static class CommandLine public bool Has(string option) => Seen.Any(entry => entry.Option.Long == option); } + private static void ReadOption( + string argument, IReadOnlyList<string> arguments, ref int index, List<(Option, List<string>, string)> seen) + { + if (argument.StartsWith("--", StringComparison.Ordinal)) + { + ReadLong(argument, arguments, ref index, seen); + } + else + { + ReadShort(argument, seen); + } + } + private static Scanned Scan(IReadOnlyList<string> arguments) { string? command = null; @@ -223,13 +236,9 @@ internal static class CommandLine afterDashes.AddRange(arguments.Skip(index)); break; } - else if (argument.StartsWith("--", StringComparison.Ordinal)) - { - ReadLong(argument, arguments, ref index, seen); - } else if (argument.StartsWith('-') && argument.Length > 1) { - ReadShort(argument, seen); + ReadOption(argument, arguments, ref index, seen); } else if (command is null) { diff --git a/src/Progmasoft.Tazel/Driver/StepPlanner.cs b/src/Progmasoft.Tazel/Driver/StepPlanner.cs index 0137330..9418559 100644 --- a/src/Progmasoft.Tazel/Driver/StepPlanner.cs +++ b/src/Progmasoft.Tazel/Driver/StepPlanner.cs @@ -134,8 +134,8 @@ internal sealed partial class Planner public string? FindProgram(string name) => Host.Which(name); public async Task<StepRun> RunAsync( - string program, IReadOnlyList<string> arguments, string? workingDirectory = null, - CancellationToken cancellationToken = default) + string program, IReadOnlyList<string> arguments, string? workingDirectory, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(arguments); var found = Host.Which(program) ?? throw new PluginException($"{Label}: the program '{program}' is not found"); diff --git a/src/Progmasoft.Tazel/Driver/TestRunner.cs b/src/Progmasoft.Tazel/Driver/TestRunner.cs index 54993ef..bb422a8 100644 --- a/src/Progmasoft.Tazel/Driver/TestRunner.cs +++ b/src/Progmasoft.Tazel/Driver/TestRunner.cs @@ -131,17 +131,7 @@ internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporte return cached; } - if (File.Exists(run.Passed)) - { - File.Delete(run.Passed); - } - - if (Directory.Exists(run.Logs)) - { - Directory.Delete(run.Logs, recursive: true); - } - - Directory.CreateDirectory(run.Logs); + Forget(run); var attempts = settings.Flaky ? 3 : 1; var watch = Stopwatch.StartNew(); var log = new StringBuilder(); @@ -166,6 +156,22 @@ internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporte return new TestOutcome(run.Label, timedOut ? TestStatus.TimedOut : TestStatus.Failed, watch.Elapsed, log.ToString()); } + /// <summary>Clears what an earlier run left: its pass and its logs.</summary> + private static void Forget(TestRun run) + { + if (File.Exists(run.Passed)) + { + File.Delete(run.Passed); + } + + if (Directory.Exists(run.Logs)) + { + Directory.Delete(run.Logs, recursive: true); + } + + Directory.CreateDirectory(run.Logs); + } + /// <summary>The outcome of a test that passed with the same key, or null when it has to run.</summary> private static async Task<TestOutcome?> CachedAsync(TestRun run, CancellationToken cancel) { diff --git a/src/Progmasoft.Tazel/MicroVM/Sandbox.cs b/src/Progmasoft.Tazel/MicroVM/Sandbox.cs index d7192a0..03ac6ea 100644 --- a/src/Progmasoft.Tazel/MicroVM/Sandbox.cs +++ b/src/Progmasoft.Tazel/MicroVM/Sandbox.cs @@ -241,7 +241,8 @@ internal sealed class Sandbox : IAsyncDisposable private static async Task WaitForAsync(string socket, Process daemon, string what, CancellationToken cancel) { - for (var i = 0; i < 100 && !File.Exists(socket); i++) + // Thirty seconds: a loaded machine, such as one running a test suite, may be slow to start it. + for (var i = 0; i < 600 && !File.Exists(socket); i++) { if (daemon.HasExited) { @@ -253,7 +254,7 @@ internal sealed class Sandbox : IAsyncDisposable if (!File.Exists(socket)) { - throw new MicroVMException($"{what} did not open {socket} within five seconds"); + throw new MicroVMException($"{what} did not open {socket} within thirty seconds"); } } diff --git a/src/Progmasoft.Tazel/Portal/PortalModules.cs b/src/Progmasoft.Tazel/Portal/PortalModules.cs index cd3adcf..2b6a26e 100644 --- a/src/Progmasoft.Tazel/Portal/PortalModules.cs +++ b/src/Progmasoft.Tazel/Portal/PortalModules.cs @@ -9,6 +9,7 @@ using System.Net; using System.Net.Http; using System.Text.Json; using System.Text.Json.Serialization; +using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using NuGet.Versioning; @@ -47,6 +48,49 @@ internal sealed record CatalogEntry( /// <summary><c>modules.tazel.net/index.json</c>.</summary> internal sealed record Catalog([property: JsonPropertyName("modules")] IReadOnlyList<CatalogEntry> Modules); +/// <summary> +/// The names of Tazel Portal Modules, as the JSON Schema of its index has them. A name becomes a directory below +/// vendor/ and .tazel/ and a part of an address, so a name that is not one is refused before it is used: from the +/// command line, a project file or an index the server sent. +/// </summary> +internal static partial class PortalNames +{ + /// <summary>Throws unless <paramref name="group"/> and <paramref name="module"/> are names of the portal.</summary> + public static void Check(string group, string module, string where) + { + ArgumentNullException.ThrowIfNull(group); + ArgumentNullException.ThrowIfNull(module); + if (!GroupPattern().IsMatch(group)) + { + throw new ProjectException($"{where}: '{group}' is not a group: lower-case names joined by dots, such as com.example"); + } + + if (!ModulePattern().IsMatch(module) || module is "." or "..") + { + throw new ProjectException($"{where}: '{module}' is not the name of a module: letters, digits and _ + . -"); + } + } + + /// <summary>Throws unless <paramref name="version"/> is a SemVer version as the index writes it.</summary> + public static void CheckVersion(string version, string where) + { + ArgumentNullException.ThrowIfNull(version); + if (!VersionPattern().IsMatch(version)) + { + throw new ProjectException($"{where}: '{version}' is not a SemVer version"); + } + } + + [GeneratedRegex("^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)*$")] + private static partial Regex GroupPattern(); + + [GeneratedRegex("^[A-Za-z0-9_+.-]+$")] + private static partial Regex ModulePattern(); + + [GeneratedRegex("^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?(\\+[0-9A-Za-z.-]+)?$")] + private static partial Regex VersionPattern(); +} + /// <summary> /// The client of Tazel Portal Modules, laid out as the Bazel Central Registry is: an index per module, and each version's /// archive with its <c>.sha256sums</c> beside it. The address is <c>https://modules.tazel.net</c>, or @@ -102,6 +146,7 @@ internal sealed class PortalModulesClient : IDisposable /// <summary>The text of an index: from vendor/ when it is there, else from the portal; null for no such module.</summary> public async Task<string?> IndexTextAsync(string group, string module, CancellationToken cancel) { + PortalNames.Check(group, module, "Tazel Portal Modules"); var path = $"{group}/{module}/index.json"; if (_vendor is not null && File.Exists(Path.Combine(_vendor, group, module, "index.json"))) { @@ -118,6 +163,8 @@ internal sealed class PortalModulesClient : IDisposable public async Task<(string Archive, string Sha256)> DownloadAsync( string group, string module, string version, string directory, CancellationToken cancel) { + PortalNames.Check(group, module, "Tazel Portal Modules"); + PortalNames.CheckVersion(version, $"{group}:{module}"); var name = $"{ModuleArchive.BaseName(group, module, version)}{ModuleArchive.Extension}"; var path = $"{group}/{module}/{version}/{name}"; var sums = await GetTextAsync(path + ".sha256sums", cancel).ConfigureAwait(false) diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index a95ad55..3d75b00 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -92,12 +92,14 @@ internal static class Program { for (; error is not null; error = error.InnerException) { - switch (error) + if (error is CustomCommandsException { Diagnostic: { } custom }) { - case CustomCommandsException { Diagnostic: { } custom }: - return custom; - case TazelOptionsException { Diagnostic: { } options }: - return options; + return custom; + } + + if (error is TazelOptionsException { Diagnostic: { } options }) + { + return options; } } diff --git a/src/Progmasoft.Tazel/Project/Plugins.cs b/src/Progmasoft.Tazel/Project/Plugins.cs index a571a7c..e25a768 100644 --- a/src/Progmasoft.Tazel/Project/Plugins.cs +++ b/src/Progmasoft.Tazel/Project/Plugins.cs @@ -62,7 +62,7 @@ internal static class Plugins 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( + public static IReadOnlyList<LoadedPlugin> LoadAll( string mainRoot, LoadedModule module, BuildContext build, Action<string> status) { ArgumentNullException.ThrowIfNull(module); @@ -124,65 +124,55 @@ internal static class Plugins throw new ProjectException($"{place}: the plugin '{path}' is not a file of this module"); } + var directory = Unpacked(mainRoot, archive); + var manifest = ReadManifest(Path.Combine(directory, ManifestFile), path); + CheckManifest(manifest, path); + var context = new PluginLoadContext(manifest.Group + "." + manifest.Name, directory); + // Tazel's own copy of a shared assembly is the one every plugin uses; the entry assembly comes first. + var assemblies = Directory.EnumerateFiles(directory, "*.dll").Order(StringComparer.Ordinal) + .Where(file => !Shared.Contains(Path.GetFileNameWithoutExtension(file), StringComparer.Ordinal)) + .Select(file => (File: Path.GetFileName(file), Assembly: LoadAssembly(context, file, path))) + .OrderBy(loaded => loaded.File == manifest.EntryAssembly ? 0 : 1) + .ToList(); + if (assemblies.Count == 0 || assemblies[0].File != manifest.EntryAssembly) + { + throw new ProjectException($"{path}: its manifest names the entry assembly {manifest.EntryAssembly}, which it does not hold"); + } + + return new LoadedPlugin(manifest, directory, context, assemblies.Select(loaded => loaded.Assembly).ToList()); + } + + /// <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 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)); + return Path.Combine(destination, File.ReadAllText(marker).Trim()); } - 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)) + if (Directory.Exists(destination)) { - var name = Path.GetFileNameWithoutExtension(file); - if (Shared.Contains(name, StringComparer.Ordinal)) - { - // Tazel's own copy is the one every plugin uses. - continue; - } + Directory.Delete(destination, recursive: true); + } - 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); - } + var directory = ModuleArchive.Unpack(archive, destination, ManifestFile); + File.WriteAllText(marker, Path.GetFileName(directory)); + return directory; + } - assemblies.Add(assembly); - if (string.Equals(Path.GetFileName(file), manifest.EntryAssembly, StringComparison.Ordinal)) - { - entry = assembly; - } + private static Assembly LoadAssembly(PluginLoadContext context, string file, string shown) + { + try + { + return context.LoadFromAssemblyPath(Path.GetFullPath(file)); } - - if (entry is null) + catch (BadImageFormatException error) { - throw new ProjectException($"{path}: its manifest names the entry assembly {manifest.EntryAssembly}, which it does not hold"); + throw new ProjectException($"{shown}: {Path.GetFileName(file)} is not a .NET assembly: {error.Message}", error); } - - 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) @@ -200,6 +190,18 @@ internal static class Plugins } 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)) + { + throw new ProjectException($"{shown}: the entry assembly '{entry}' is not a .dll at the top"); + } + } + + private static void CheckNames(PluginManifest manifest, string shown) { if (string.IsNullOrEmpty(manifest.Group) || manifest.Group.Split('.').Any(part => part.Length == 0 || !Labels.IsName(part))) { @@ -215,13 +217,19 @@ internal static class Plugins { throw new ProjectException($"{shown}: '{manifest.Version}' is not a SemVer version"); } + } + /// <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) + { 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; @@ -231,13 +239,6 @@ internal static class Plugins $"{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) @@ -319,7 +320,7 @@ internal static class Plugins } /// <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) + private sealed class PluginLoadContext(string name, string directory) : AssemblyLoadContext(name) { protected override Assembly? Load(AssemblyName assemblyName) { diff --git a/src/Progmasoft.Tazel/Project/PortalDependencies.cs b/src/Progmasoft.Tazel/Project/PortalDependencies.cs index 2f056cc..328ba50 100644 --- a/src/Progmasoft.Tazel/Project/PortalDependencies.cs +++ b/src/Progmasoft.Tazel/Project/PortalDependencies.cs @@ -40,91 +40,119 @@ internal static class PortalDependencies PortalModulesClient client, CancellationToken cancel) { ArgumentNullException.ThrowIfNull(direct); - var wanted = new Dictionary<string, NuGetVersion>(StringComparer.Ordinal); - var names = new Dictionary<string, string>(StringComparer.Ordinal); - var why = new Dictionary<string, string>(StringComparer.Ordinal); - var queue = new Queue<string>(); + var resolution = new Resolution(client); foreach (var (group, module, text, alias, place) in direct) + { + resolution.AddDirect(group, module, text, alias, place); + } + + await resolution.RunAsync(cancel).ConfigureAwait(false); + return resolution.Result(); + } + + /// <summary>One resolution: each module at the highest version anything asks for, followed through the indexes.</summary> + private sealed class Resolution(PortalModulesClient client) + { + private readonly Dictionary<string, NuGetVersion> _wanted = new(StringComparer.Ordinal); + private readonly Dictionary<string, string> _names = new(StringComparer.Ordinal); + private readonly Dictionary<string, string> _why = new(StringComparer.Ordinal); + private readonly Dictionary<string, ModuleIndex> _indexes = new(StringComparer.Ordinal); + private readonly Dictionary<string, NuGetVersion> _done = new(StringComparer.Ordinal); + private readonly Queue<string> _queue = new(); + + public void AddDirect(string group, string module, string text, string? alias, string place) { if (!NuGetVersion.TryParseStrict(text, out var version)) { throw new ProjectException($"{place}: '{text}' is not a SemVer version"); } + Portal.PortalNames.Check(group, module, place); var key = $"{group}:{module}"; var repository = alias ?? module; - if (names.TryGetValue(key, out var other) && other != repository) + if (_names.TryGetValue(key, out var other) && other != repository) { throw new ProjectException($"{place}: {key} is named twice, as @{other} and @{repository}"); } - names[key] = repository; + _names[key] = repository; Ask(key, version, place); } - var indexes = new Dictionary<string, ModuleIndex>(StringComparer.Ordinal); - var done = new Dictionary<string, NuGetVersion>(StringComparer.Ordinal); - while (queue.Count > 0) + public async Task RunAsync(CancellationToken cancel) { - var key = queue.Dequeue(); - var version = wanted[key]; - if (done.TryGetValue(key, out var seen) && seen == version) + while (_queue.Count > 0) { - continue; + var key = _queue.Dequeue(); + var version = _wanted[key]; + if (_done.TryGetValue(key, out var seen) && seen == version) + { + continue; + } + + _done[key] = version; + var entry = await EntryAsync(key, version, cancel).ConfigureAwait(false); + foreach (var dependency in entry.Dependencies.Where(d => !d.Test)) + { + Follow(key, version, dependency); + } } + } + + public List<ResolvedModule> Result() + { + var resolved = _wanted.Select(entry => + { + var parts = entry.Key.Split(':'); + return new ResolvedModule(_names[entry.Key], parts[0], parts[1], entry.Value); + }).OrderBy(module => module.Key, StringComparer.Ordinal).ToList(); + var clash = resolved.GroupBy(module => module.Repository).FirstOrDefault(group => group.Count() > 1); + return clash is null + ? resolved + : throw new ProjectException( + $"{string.Join(" and ", clash.Select(m => m.Key))} would both be @{clash.Key}; give one of them an Alias"); + } - done[key] = version; - if (!indexes.TryGetValue(key, out var index)) + /// <summary>The entry of <paramref name="version"/> in the index of <paramref name="key"/>, which must not be yanked.</summary> + private async Task<IndexVersion> EntryAsync(string key, NuGetVersion version, CancellationToken cancel) + { + if (!_indexes.TryGetValue(key, out var index)) { var parts = key.Split(':'); index = await client.IndexAsync(parts[0], parts[1], cancel).ConfigureAwait(false) - ?? throw new ProjectException($"{why[key]}: Tazel Portal Modules has no module {key}"); - indexes[key] = index; + ?? throw new ProjectException($"{_why[key]}: Tazel Portal Modules has no module {key}"); + _indexes[key] = index; } - var entry = index.Versions.FirstOrDefault(v => - NuGetVersion.TryParseStrict(v.Version, out var listed) && listed == version) + var entry = index.Versions.FirstOrDefault(v => NuGetVersion.TryParseStrict(v.Version, out var listed) && listed == version) ?? throw new ProjectException( - $"{why[key]}: {key} has no version {version}; it has {string.Join(", ", index.Versions.Select(v => v.Version))}"); - if (entry.Yanked) - { - throw new ProjectException($"{why[key]}: {key} {version} is yanked, so it takes part in no resolution"); - } + $"{_why[key]}: {key} has no version {version}; it has {string.Join(", ", index.Versions.Select(v => v.Version))}"); + return entry.Yanked + ? throw new ProjectException($"{_why[key]}: {key} {version} is yanked, so it takes part in no resolution") + : entry; + } - foreach (var dependency in entry.Dependencies.Where(d => !d.Test)) + /// <summary>A dependency an index names, whose names and version are checked, as the server sent them.</summary> + private void Follow(string key, NuGetVersion version, IndexDependency dependency) + { + if (!NuGetVersion.TryParseStrict(dependency.Version, out var needed)) { - if (!NuGetVersion.TryParseStrict(dependency.Version, out var needed)) - { - throw new ProjectException($"the index of {key} names {dependency.Group}:{dependency.Module} at '{dependency.Version}'"); - } - - var next = $"{dependency.Group}:{dependency.Module}"; - names.TryAdd(next, dependency.Module); - Ask(next, needed, $"{key} {version}"); + throw new ProjectException($"the index of {key} names {dependency.Group}:{dependency.Module} at '{dependency.Version}'"); } - } - var resolved = wanted.Select(entry => - { - var parts = entry.Key.Split(':'); - return new ResolvedModule(names[entry.Key], parts[0], parts[1], entry.Value); - }).OrderBy(module => module.Key, StringComparer.Ordinal).ToList(); - var clash = resolved.GroupBy(module => module.Repository).FirstOrDefault(group => group.Count() > 1); - if (clash is not null) - { - throw new ProjectException( - $"{string.Join(" and ", clash.Select(m => m.Key))} would both be @{clash.Key}; give one of them an Alias"); + Portal.PortalNames.Check(dependency.Group, dependency.Module, $"the index of {key}"); + var next = $"{dependency.Group}:{dependency.Module}"; + _names.TryAdd(next, dependency.Module); + Ask(next, needed, $"{key} {version}"); } - return resolved; - - void Ask(string key, NuGetVersion version, string place) + private void Ask(string key, NuGetVersion version, string place) { - if (!wanted.TryGetValue(key, out var current) || version > current) + if (!_wanted.TryGetValue(key, out var current) || version > current) { - wanted[key] = version; - why[key] = place; - queue.Enqueue(key); + _wanted[key] = version; + _why[key] = place; + _queue.Enqueue(key); } } } diff --git a/src/Progmasoft.Tazel/Project/Workspace.cs b/src/Progmasoft.Tazel/Project/Workspace.cs index 6a8a4fc..d1ab5c7 100644 --- a/src/Progmasoft.Tazel/Project/Workspace.cs +++ b/src/Progmasoft.Tazel/Project/Workspace.cs @@ -127,24 +127,37 @@ internal sealed class Workspace var file = Path.Combine(root, ModuleFiles.ModuleFile); var shown = repository is null ? ModuleFiles.ModuleFile : $"@{repository}//{ModuleFiles.ModuleFile}"; var globals = new ModuleGlobals(); - var envsShown = repository is null ? Dsl.Envs.TazelEnvsFile.FileName : $"@{repository}//{Dsl.Envs.TazelEnvsFile.FileName}"; - Dsl.Envs.ModuleEnvironment? environment; + var environment = EnvironmentOf(root, repository); + using (Dsl.Environment.EnvironmentValues.Enter(environment)) + { + await ScriptHost.RunAsync(await File.ReadAllTextAsync(file).ConfigureAwait(false), shown, globals) + .ConfigureAwait(false); + } + + var definition = globals.module?.Definition + ?? throw new ProjectException($"{shown} sets no module: module = Module.Define(new() {{ ... }});"); + var version = Checked(definition, shown, tazelVersion); + return new LoadedModule(root, repository, globals, new ModuleInfo(definition.Group, definition.Name, version, definition), + environment); + } + + /// <summary>The values of the module's tazel_envs.txt, or null when it has none.</summary> + private static Dsl.Envs.ModuleEnvironment? EnvironmentOf(string root, string? repository) + { + var shown = repository is null ? Dsl.Envs.TazelEnvsFile.FileName : $"@{repository}//{Dsl.Envs.TazelEnvsFile.FileName}"; try { - environment = Dsl.Envs.ModuleEnvironment.Load(root, envsShown); + return Dsl.Envs.ModuleEnvironment.Load(root, shown); } catch (Dsl.Custom.CustomCommandsException error) { throw new ProjectException(error.Message, error); } + } - using (Dsl.Environment.EnvironmentValues.Enter(environment)) - { - await ScriptHost.RunAsync(await File.ReadAllTextAsync(file).ConfigureAwait(false), shown, globals) - .ConfigureAwait(false); - } - var definition = globals.module?.Definition - ?? throw new ProjectException($"{shown} sets no module: module = Module.Define(new() {{ ... }});"); + /// <summary>The version of a module, once its name, group, version and Tazel compatibility are checked.</summary> + private static NuGetVersion Checked(ModuleDefinition definition, string shown, Version tazelVersion) + { if (!Labels.IsName(definition.Name)) { throw new ProjectException($"{shown}: the module name '{definition.Name}' must be letters, digits and _ + . -"); @@ -167,8 +180,7 @@ internal sealed class Workspace $"{shown} builds with Tazel {compatibility}; this is Tazel {tazelVersion.ToString(3)}"); } - return new LoadedModule(root, repository, globals, new ModuleInfo(definition.Group, definition.Name, version, definition), - environment); + return version; } private static bool IsGroup(string group) => @@ -257,7 +269,7 @@ internal sealed class Workspace private async Task LoadPackagesAsync(LoadedModule module, BuildContext build, Action<string> status) { - var plugins = Plugins.Load(Main.Root, module, build, status); + var plugins = Plugins.LoadAll(Main.Root, module, build, status); PluginsOf[module.Repository ?? ""] = plugins; var environment = Plugins.EnvironmentFor(plugins); var packages = ModuleFiles.Packages(module.Root); diff --git a/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs b/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs index 17dc0ec..e3abc2d 100644 --- a/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs +++ b/tests/Progmasoft.Tazel.Tests/QueryAndPortalTests.cs @@ -246,8 +246,10 @@ internal sealed class FakePortal : IDisposable return; } - var file = Path.Combine(Directory, context.Request.Url!.AbsolutePath.TrimStart('/')); - if (File.Exists(file)) + // The portal serves its own directory and nothing above it. + var root = Path.GetFullPath(Directory) + Path.DirectorySeparatorChar; + var file = Path.GetFullPath(Path.Combine(root, context.Request.Url!.AbsolutePath.TrimStart('/'))); + if (file.StartsWith(root, StringComparison.Ordinal) && File.Exists(file)) { var bytes = await File.ReadAllBytesAsync(file); context.Response.StatusCode = 200; @@ -306,6 +308,38 @@ public sealed class PortalTests Assert.Contains("fetched 2 modules (2 of Tazel Portal Modules)", output, StringComparison.Ordinal); } + [Theory] + [InlineData("com.example", "..", "is not the name of a module")] + [InlineData("../etc", "json", "is not a group")] + [InlineData("Com.Example", "json", "is not a group")] + public async Task ANameThatIsNotOneIsRefusedBeforeItBecomesAPath(string group, string name, string message) + { + using var module = new TemporaryModule(); + module.Write("MODULE.csx", TemporaryModule.ModuleFile + $$""" + + dependencies = Dependencies.Define(Module.From(new() { Group = "{{group}}", Name = "{{name}}", Version = "1.0.0" })); + """); + using var address = new EnvironmentVariable("TAZEL_PORTAL_MODULES_URL", "http://127.0.0.1:9"); + var error = await Assert.ThrowsAsync<Project.ProjectException>(() => module.LoadAsync()); + Assert.Contains(message, error.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task AnIndexThatNamesAPathIsRefused() + { + using var served = new TemporaryModule(); + using var portal = new FakePortal(served.Root); + portal.Push("com.example", "json", "1.0.0", Library, ("com.example", "..", "1.0.0")); + using var module = new TemporaryModule(); + module.Write("MODULE.csx", TemporaryModule.ModuleFile + """ + + dependencies = Dependencies.Define(Module.From(new() { Group = "com.example", Name = "json", Version = "1.0.0" })); + """); + using var address = new EnvironmentVariable("TAZEL_PORTAL_MODULES_URL", portal.Address); + var error = await Assert.ThrowsAsync<Project.ProjectException>(() => module.LoadAsync()); + Assert.Contains("the index of com.example:json: '..' is not the name of a module", error.Message, StringComparison.Ordinal); + } + [Fact] public async Task SearchesAndShowsModules() { diff --git a/tests/Progmasoft.Tazel.Tests/Snapshots.cs b/tests/Progmasoft.Tazel.Tests/Snapshots.cs index 5bdbf92..8397f87 100644 --- a/tests/Progmasoft.Tazel.Tests/Snapshots.cs +++ b/tests/Progmasoft.Tazel.Tests/Snapshots.cs @@ -84,7 +84,8 @@ internal static class Snapshots } /// <summary>A line diff by the longest common subsequence: ' ' for kept, '-' for stored only, '+' for new only.</summary> - private static List<(char Kind, string Line)> Diff(string[] expected, string[] actual) + /// <summary>The length of the longest common run of lines from each pair of positions on.</summary> + private static int[,] CommonLengths(string[] expected, string[] actual) { var lengths = new int[expected.Length + 1, actual.Length + 1]; for (var i = expected.Length - 1; i >= 0; i--) @@ -97,6 +98,12 @@ internal static class Snapshots } } + return lengths; + } + + private static List<(char Kind, string Line)> Diff(string[] expected, string[] actual) + { + var lengths = CommonLengths(expected, actual); var result = new List<(char, string)>(); int a = 0, b = 0; while (a < expected.Length || b < actual.Length)