tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Read the text files in layers and add the options, custom-cmds and envs commands
- Commit
8de676e8cd3ba59cbaba05afc193260c14d214f6- Author
- Leitwolf11 ·
- Parents
486bdd58f180
Changes
CHANGELOG.md | 5 + docs/commands.md | 26 +- src/Progmasoft.Tazel/Cli/CommandLine.cs | 50 +++- src/Progmasoft.Tazel/Cli/Commands.cs | 59 +++- src/Progmasoft.Tazel/Cli/ConfigurationCommands.cs | 320 +++++++++++++++++++++ src/Progmasoft.Tazel/Cli/Help.cs | 29 ++ .../Dsl/Configuration/ConfigurationLayers.cs | 125 ++++++++ .../Dsl/Configuration/ConfigurationResolver.cs | 16 +- .../Dsl/Configuration/ProjectKey.cs | 89 ++++++ src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs | 42 ++- src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs | 111 +++++-- src/Progmasoft.Tazel/Project/Workspace.cs | 2 +- .../ConfigurationLayersTests.cs | 306 ++++++++++++++++++++ 13 files changed, 1132 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 85aa0e5..07eba24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ ## Unreleased +- Configuration in layers: `$TAZEL_HOME/User/`, the directories above, `$TAZEL_HOME/Projects/<key>/` and the current + directory, for `tazel_options.txt`, `tazel_custom.txt` and the main module's `tazel_envs.txt`. The project key is + Agenceland's. New commands `tazel options validate|get|what-is|update`, `tazel custom-cmds validate` and + `tazel envs validate`, with `--user`, `--project`, `--local` and `--create`. + - `--dotnet-settings Name=Value[,...]` and `dotnet-settings: [ ... ];` in `tazel_options.txt` set the .NET runtime of the Tazel process: the GC heap hard limits (in bytes or percent, whole or per object heap), the GC latency mode, and the thread pool's minimum and maximum threads. `tazel dotnet get <setting>` reads them; `tazel dotnet what-is <term>` diff --git a/docs/commands.md b/docs/commands.md index e660dd8..6e93195 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -138,8 +138,30 @@ platform: linux-amd64; dotnet-settings: [ "GCHeapHardLimit=512M" 'GCSettings.LatencyMode=Interactive' ]; ``` -The nearest `tazel_options.txt` at or above the current directory holds, except that a sandbox asked for by any file -above stays asked for. This Tazel has no MicroVM to start, so with `sandboxing-with-microvm: true` it refuses every +Configuration comes in layers, lowest first: the user's (`$TAZEL_HOME/User/`), every directory above the current one, +the farthest first, this machine's settings of the project (`$TAZEL_HOME/Projects/<key>/`, outside the module), and the +current directory; the command line is above them all. Each option comes from the highest layer that sets it, an +explicit `false` or `auto` as much as any value; `dotnet-settings` merge name by name; a sandbox asked for in any layer +stays asked for. The project key is the module root's canonical path made readable (`-home-ada-src--app`) with the +first 16 hexadecimal digits of its SHA-256 after it, so every directory of a module shares one, and `identity.txt` in +its directory holds that root; a directory there of another root is refused. + +`tazel_custom.txt` takes the same layers, a command of a higher layer replacing the one of the same name. +`tazel_envs.txt` too, for the main module only, around its root; a module it depends on takes its own file alone. + +```text +tazel options validate [--user | --project | --local] +tazel options get <setting> [--user | --project | --local] +tazel options what-is <setting> +tazel options update <setting> <value> [--user | --project] [--create] +tazel custom-cmds validate [--user | --project | --local] +tazel envs validate [--user | --project | --local] +``` + +`validate` reads each layer, or the one a flag names, and runs nothing. `get` prints the value that holds and the file +it came from. `update` replaces the value where it stands, or adds the entry, and keeps the rest of the file, +comments too; it writes beside the file and moves it into place under a lock, needs `--create` for a file that is not +there, and leaves an option set inside `.if` or in an included file for you to edit. This Tazel has no MicroVM to start, so with `sandboxing-with-microvm: true` it refuses every command that would run what a project brings (`build`, `run`, `test`, `package`, `custom`) rather than run it on this machine. diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index cc27a5e..dfa86df 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -139,7 +139,7 @@ internal static class CommandLine /// <summary>The commands, as <c>tazel help</c> lists them.</summary> public static IReadOnlyList<string> Commands { get; } = ["build", "run", "test", "coverage", "query", "cquery", "aquery", "fetch", "vendor", "clean", "package", "custom", - "portal-modules", "cache", "explain", "version", "help", "dotnet", "limited-time"]; + "portal-modules", "cache", "explain", "version", "help", "dotnet", "limited-time", "options", "custom-cmds", "envs"]; private enum Kind { @@ -161,6 +161,10 @@ internal static class CommandLine new("progress", Kind.Value, ["always", "auto", "never"]), new("quiet", Kind.Flag, null), new("dotnet-settings", Kind.ListAlways, null), + new("user", Kind.Flag, null, "options", "custom-cmds", "envs"), + new("project", Kind.Flag, null, "options", "custom-cmds", "envs"), + new("local", Kind.Flag, null, "options", "custom-cmds", "envs"), + new("create", Kind.Flag, null, "options"), new("message-format", Kind.Value, ["rich-stdio", "script-friendly-stdio", "jsonl", "xml"]), new("help", Kind.Flag, null), new("platform", Kind.Value, Platforms.Names, Building), @@ -321,6 +325,9 @@ internal static class CommandLine ? new MigrateCommand(output) : throw new CommandLineException("tazel limited-time takes one word, C#: tazel limited-time C#"), ["dotnet"] = MakeDaemon, + ["options"] = MakeOptions, + ["custom-cmds"] = (scanned, output) => MakeValidate(scanned, output, ConfigurationKind.Custom), + ["envs"] = (scanned, output) => MakeValidate(scanned, output, ConfigurationKind.Envs), ["cache"] = MakeCache, }; @@ -344,6 +351,47 @@ internal static class CommandLine ? throw new CommandLineException($"tazel {scanned.Command} needs an expression, such as deps(//app:greeter)") : new QueryCommand(output, kind, string.Join(' ', scanned.Positional), Flags(scanned.Seen), Last(scanned.Seen, "output") ?? "label"); + // --user, --project or --local: one at most; null for none. + private static Dsl.Configuration.LayerKind? Scope(Scanned scanned) + { + var given = new[] { ("user", Dsl.Configuration.LayerKind.User), ("project", Dsl.Configuration.LayerKind.Project), ("local", Dsl.Configuration.LayerKind.Local) } + .Where(flag => scanned.Has(flag.Item1)).ToList(); + return given.Count switch + { + 0 => null, + 1 => given[0].Item2, + _ => throw new CommandLineException($"--{given[0].Item1} and --{given[1].Item1} name two layers; give one"), + }; + } + + private static Command MakeOptions(Scanned scanned, OutputOptions output) + { + var positional = scanned.Positional; + var scope = Scope(scanned); + if (scanned.Has("create") && positional is not ["update", ..]) + { + throw new CommandLineException("--create is an option of tazel options update"); + } + + return positional switch + { + ["validate"] => new OptionsCommand(output, "validate", null, null, scope, false), + ["get", var name] => new OptionsCommand(output, "get", name, null, scope, false), + ["what-is", var name] => scope is null ? new OptionsCommand(output, "what-is", name, null, null, false) + : throw new CommandLineException("tazel options what-is reads no file, so it takes no layer"), + ["update", var name, var value] => scope == Dsl.Configuration.LayerKind.Local + ? throw new CommandLineException("tazel options update writes ./tazel_options.txt without a flag; --local is for reading") + : new OptionsCommand(output, "update", name, value, scope, scanned.Has("create")), + _ => throw new CommandLineException( + "tazel options takes validate, get <setting>, what-is <setting> or update <setting> <value>" + + (positional.Count > 0 && Suggestions.Nearest(positional[0], ["validate", "get", "what-is", "update"]) is { } near ? $"; did you mean {near}?" : "")), + }; + } + + private static Command MakeValidate(Scanned scanned, OutputOptions output, ConfigurationKind kind) => scanned.Positional is ["validate"] + ? new ValidateCommand(output, kind, Scope(scanned)) + : throw new CommandLineException($"tazel {scanned.Command} takes validate"); + private static Command MakeDaemon(Scanned scanned, OutputOptions output) { var actions = new[] { "start-daemon", "restart-daemon", "stop-daemon", "get", "what-is" }; diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index a25696c..a3af3bc 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -43,6 +43,8 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector PortalModulesCommand portal => PortalModulesAsync(portal, cancel), PackageCommand => PackageAsync(), CustomCommandLine custom => CustomAsync(custom, cancel), + OptionsCommand options => Task.FromResult(Options(options)), + ValidateCommand validate => Task.FromResult(Validate(validate.Kind, validate.Scope)), _ => Task.FromResult(RunAtOnce(command)), }; } @@ -160,6 +162,49 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector return 0; } + /// <summary> + /// The custom commands that hold here: those of every layer of tazel_custom.txt, a command of a higher layer + /// replacing the one of the same name below it. Their conditions see the platform tazel_options.txt chooses. + /// </summary> + private IReadOnlyList<CustomCommand> CustomCommandsHere() + { + var (options, _) = TazelOptionsFile.Effective(workingDirectory); + var context = Dsl.Configuration.ConfigurationContext.ForThisMachine() with + { + Target = Dsl.Configuration.SystemFacts.Of(options.Platform ?? Driver.Host.Platform), + }; + var merged = new List<CustomCommand>(); + foreach (var layer in CustomLayers()) + { + foreach (var command in CustomParser.Parse(File.ReadAllText(layer.File), Shown(layer.File), layer.File, context)) + { + merged.RemoveAll(other => other.Name == command.Name); + merged.Add(command); + } + } + + return merged; + } + + private IReadOnlyList<Dsl.Configuration.Layer> CustomLayers() + { + try + { + return Dsl.Configuration.ConfigurationLayers.For(CustomCommandFiles.FileName, workingDirectory); + } + catch (Dsl.Configuration.ConfigurationHomeException error) + { + throw new CustomCommandsException(error.Message, error); + } + } + + // A file of a layer as messages show it: from the working directory when it is below it. + private string Shown(string file) + { + var relative = Path.GetRelativePath(workingDirectory, file); + return relative.StartsWith("..", StringComparison.Ordinal) ? file : relative.Replace('\\', '/'); + } + /// <summary>tazel dotnet what-is: a term of .NET explained, offline.</summary> private int WhatIs(string term) { @@ -220,19 +265,13 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector /// <summary>The command of tazel_custom.txt the words name, and its arguments, which must fit what it takes.</summary> private (CustomCommand Command, IReadOnlyList<string> Arguments) FindCustom(IReadOnlyList<string> words) { - var file = Path.Combine(workingDirectory, CustomCommandFiles.FileName); - if (!File.Exists(file)) + var commands = CustomCommandsHere(); + if (commands.Count == 0) { - throw new CustomCommandsException($"there is no {CustomCommandFiles.FileName} in {workingDirectory}"); + throw new CustomCommandsException( + $"there is no {CustomCommandFiles.FileName} in {workingDirectory}, above it, or in the user's or the project's settings"); } - // Its conditions see the platform tazel_options.txt chooses, else this machine's. - var (options, _) = TazelOptionsFile.Effective(workingDirectory); - var context = Dsl.Configuration.ConfigurationContext.ForThisMachine() with - { - Target = Dsl.Configuration.SystemFacts.Of(options.Platform ?? Driver.Host.Platform), - }; - var commands = CustomParser.Parse(File.ReadAllText(file), CustomCommandFiles.FileName, file, context); if (words.Count > CustomCommandFiles.MaxArguments) { throw new CommandLineException($"tazel custom takes at most {CustomCommandFiles.MaxArguments} words"); diff --git a/src/Progmasoft.Tazel/Cli/ConfigurationCommands.cs b/src/Progmasoft.Tazel/Cli/ConfigurationCommands.cs new file mode 100644 index 0000000..90ee02f --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/ConfigurationCommands.cs @@ -0,0 +1,320 @@ +// 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.Security.Cryptography; +using System.Text; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Dsl.Configuration; +using Progmasoft.Tazel.Dsl.Custom; +using Progmasoft.Tazel.Dsl.Custom.Lexer; +using Progmasoft.Tazel.Dsl.Custom.Parser; +using Progmasoft.Tazel.Dsl.Envs; +using Progmasoft.Tazel.Dsl.Options; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>The kinds of text files the configuration commands work on.</summary> +internal enum ConfigurationKind +{ + Options, + Custom, + Envs, +} + +/// <summary><c>tazel options</c>: validate, get, what-is or update.</summary> +internal sealed record OptionsCommand(OutputOptions Output, string Action, string? Name, string? Value, LayerKind? Scope, bool Create) + : Command(Output); + +/// <summary><c>tazel custom-cmds validate</c> and <c>tazel envs validate</c>.</summary> +internal sealed record ValidateCommand(OutputOptions Output, ConfigurationKind Kind, LayerKind? Scope) : Command(Output); + +/// <summary>What <c>tazel options what-is</c> says of an option.</summary> +internal sealed record OptionSchema(string Name, string Type, string Default, string Meaning); + +/// <summary>The commands that read and write the text files: what each layer holds, and checking them.</summary> +internal sealed partial class Commands +{ + /// <summary>The options of tazel_options.txt, as tazel options what-is explains them.</summary> + internal static IReadOnlyList<OptionSchema> Schema { get; } = + [ + new("sandboxing-with-microvm", "true or false", "false", + "Whether what a project brings to run, the build and custom commands among it, runs inside a MicroVM. true in any " + + "layer stays true: no layer above and no command line turns it off."), + new("microvm-network", "true or false", "false", "Whether the MicroVM reaches the network."), + new("microvm-memory", "auto, or a whole number of MiB from 256 to 1048576", "auto", "The memory of the MicroVM."), + new("microvm-cpus", "auto, or a whole number from 1 to 256", "auto", "The processors of the MicroVM."), + new("platform", "a platform name, as --platform takes it", "this machine's", + "The platform commands build for unless --platform names one. It is chosen before what depends on target_system " + + "is read, so it may not be set inside a condition on target_system."), + new("dotnet-settings", "a list of strings, Name=Value each: [ \"GCHeapHardLimit=512M\" ]", "none", + "Settings of the .NET runtime of the Tazel process, merged name by name across the layers, before those of " + + "--dotnet-settings. tazel help dotnet --long lists the thirteen."), + ]; + + private int Options(OptionsCommand command) => command.Action switch + { + "validate" => Validate(ConfigurationKind.Options, command.Scope), + "get" => OptionGet(command.Name!, command.Scope), + "what-is" => OptionWhatIs(command.Name!), + _ => OptionUpdate(command.Name!, command.Value!, command.Scope, command.Create), + }; + + private static string FileName(ConfigurationKind kind) => kind switch + { + ConfigurationKind.Options => TazelOptions.FileName, + ConfigurationKind.Custom => CustomCommandFiles.FileName, + _ => TazelEnvsFile.FileName, + }; + + // The layers of one kind here, or only the one a scope flag names. + private IReadOnlyList<Layer> Layers(ConfigurationKind kind, LayerKind? scope) + { + try + { + var all = ConfigurationLayers.For(FileName(kind), workingDirectory); + if (scope is not { } only) + { + return all; + } + + var file = ConfigurationLayers.FileOf(only, FileName(kind), workingDirectory); + return File.Exists(file) ? [new Layer(only, file)] : []; + } + catch (ConfigurationHomeException error) + { + throw new CommandLineException(error.Message, error); + } + } + + /// <summary> + /// Reads every layer of a kind as the command that uses it would, includes and conditions resolved, and says + /// which it checked. Nothing runs: no shell line of tazel_envs.txt, no program, no project file. + /// </summary> + private int Validate(ConfigurationKind kind, LayerKind? scope) + { + var layers = Layers(kind, scope); + if (layers.Count == 0) + { + reporter.Plain($"no {FileName(kind)} holds here{(scope is null ? "" : " in that layer")}; there is nothing to check"); + return 0; + } + + var (options, _) = kind == ConfigurationKind.Options ? (new TazelOptions(), (string?)null) : TazelOptionsFile.Effective(workingDirectory); + var context = ConfigurationContext.ForThisMachine() with + { + Target = SystemFacts.Of(options.Platform ?? Driver.Host.Platform), + }; + foreach (var layer in layers) + { + var text = File.ReadAllText(layer.File); + switch (kind) + { + case ConfigurationKind.Options: + TazelOptionsFile.Parse(text, Shown(layer.File), layer.File); + break; + case ConfigurationKind.Custom: + CustomParser.Parse(text, Shown(layer.File), layer.File, context); + break; + default: + TazelEnvsFile.Parse(text, Shown(layer.File), layer.File, context); + break; + } + + reporter.Plain($"valid: {Shown(layer.File)} ({layer.Description})"); + } + + reporter.Status("every branch of .if was checked; the files of branches not taken on this machine were not opened"); + return 0; + } + + private int OptionGet(string name, LayerKind? scope) + { + CheckName(name); + if (scope is { } only) + { + var layer = Layers(ConfigurationKind.Options, only).FirstOrDefault(); + if (layer is null) + { + reporter.Plain($"{name}: not set (no {TazelOptions.FileName} in that layer)"); + return 0; + } + + var machine = ConfigurationContext.ForThisMachine(); + var (one, keys) = TazelOptionsFile.Read(File.ReadAllText(layer.File), Shown(layer.File), layer.File, machine.ForItself()); + reporter.Plain(keys.Contains(name) ? $"{name}: {Shown(one, name)}" : $"{name}: not set in {Shown(layer.File)}"); + return 0; + } + + var layered = TazelOptionsFile.Layered(workingDirectory); + var origin = layered.Origins.TryGetValue(name, out var from) ? $"{Shown(from.File)}, {from.Description}" : "default"; + reporter.Plain($"{name}: {Shown(layered.Options, name)} ({origin})"); + return 0; + } + + private static string Shown(TazelOptions options, string name) => name switch + { + "sandboxing-with-microvm" => options.SandboxingWithMicroVM ? "true" : "false", + "microvm-network" => options.MicroVMNetwork ? "true" : "false", + "microvm-memory" => options.MicroVMMemory.Amount?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "auto", + "microvm-cpus" => options.MicroVMCpus.Amount?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "auto", + "platform" => options.Platform?.Name() ?? $"this machine's, {Driver.Host.Platform.Name()}", + _ => options.DotnetSettings.Count == 0 ? "none" + : "[ " + string.Join(' ', Runtime.DotnetSettings.Effective(options.DotnetSettings, []).Values.Select(s => $"\"{s.Name}={Value(s)}\"")) + " ]", + }; + + private static string Value(Runtime.DotnetSetting setting) => Convert.ToString(setting.Value, System.Globalization.CultureInfo.InvariantCulture)!; + + private int OptionWhatIs(string name) + { + var schema = CheckName(name); + reporter.Strong(schema.Name); + reporter.Plain($"type: {schema.Type}"); + reporter.Plain($"default: {schema.Default}"); + reporter.Plain(schema.Meaning); + return 0; + } + + private static OptionSchema CheckName(string name) => Schema.FirstOrDefault(option => option.Name == name) + ?? throw new CommandLineException($"'{name}' is not an option of {TazelOptions.FileName}" + + (Suggestions.Nearest(name, Schema.Select(option => option.Name)) is { } near ? $"; did you mean {near}?" : "")); + + /// <summary> + /// Sets one option in one file, ./tazel_options.txt or the user's or the project's: the value of its entry is + /// replaced where it stands, or the entry is added at the end, and the rest of the file is kept as it was. An + /// option set inside .if or in an included file is left for a person to edit. The file is written beside itself + /// and moved into place, under a lock other Tazel processes wait for. + /// </summary> + private int OptionUpdate(string name, string value, LayerKind? scope, bool create) + { + CheckName(name); + var written = name == "dotnet-settings" + ? "[ " + string.Join(' ', SplitList(value).Select(entry => $"\"{entry}\"")) + " ]" + : value; + string file; + try + { + file = ConfigurationLayers.FileOf(scope ?? LayerKind.Local, TazelOptions.FileName, workingDirectory, create); + } + catch (ConfigurationHomeException error) + { + throw new CommandLineException(error.Message, error); + } + + if (!File.Exists(file) && !create) + { + throw new CommandLineException($"there is no {file}; add --create to make it"); + } + + // The value must be one the option takes. + TazelOptionsFile.Parse($"{name}: {written};", "the new value", Path.Combine(Path.GetTempPath(), TazelOptions.FileName)); + using var held = Lock(file); + var text = File.Exists(file) ? File.ReadAllText(file) : ""; + var updated = Edited(text, file, name, written); + TazelOptionsFile.Parse(updated, Shown(file), file); + Directory.CreateDirectory(Path.GetDirectoryName(file)!); + var partial = $"{file}.{Guid.NewGuid():N}.partial"; + File.WriteAllText(partial, updated, new UTF8Encoding(false)); + File.Move(partial, file, overwrite: true); + reporter.Success($"{name}: {written} in {Shown(file)}"); + return 0; + } + + // The text with the entry of name set to written: replaced where it stands, or added at the end. + private string Edited(string text, string file, string name, string written) + { + var tokens = new CustomLexer(text, Shown(file)).Tokens(); + var depth = 0; + var found = new List<(int Index, int Depth)>(); + for (var i = 0; i < tokens.Count; i++) + { + var token = tokens[i]; + if (token.Kind == TokenKind.Directive) + { + depth += token.Text == "if" ? 1 : token.Text == "end" ? -1 : 0; + continue; + } + + var startsEntry = i == 0 || tokens[i - 1].Kind is TokenKind.Semicolon or TokenKind.Directive; + if (startsEntry && token is { Kind: TokenKind.Name } && token.Text == name && i + 1 < tokens.Count && tokens[i + 1].Kind == TokenKind.Colon) + { + found.Add((i, depth)); + } + } + + if (found.Any(entry => entry.Depth > 0)) + { + throw new CommandLineException($"{Shown(file)} sets {name} inside .if; edit it there by hand"); + } + + if (found.Count > 1) + { + throw new CommandLineException($"{Shown(file)} sets {name} {found.Count} times; keep one by hand first"); + } + + if (found.Count == 0) + { + var (_, keys) = TazelOptionsFile.Read(text, Shown(file), file, ConfigurationContext.ForThisMachine().ForItself()); + if (keys.Contains(name)) + { + throw new CommandLineException($"{name} is set in a file that {Shown(file)} includes; edit that file"); + } + + // Added at the end, after a ';' the last entry may have left out. + var last = tokens.LastOrDefault(token => token.Kind != TokenKind.Directive); + var trimmed = text.TrimEnd(); + var join = trimmed.Length == 0 ? "" : last is { Kind: not TokenKind.Semicolon } && !trimmed.EndsWith(';') ? ";\n" : "\n"; + return trimmed + join + $"{name}: {written};\n"; + } + + // The value runs from after the ':' to the ';', or to the end of the file for its last entry. + var first = found[0].Index + 2; + if (first >= tokens.Count || tokens[first].Kind == TokenKind.Semicolon) + { + throw new CommandLineException($"{Shown(file)} sets {name} with no value; give it one by hand first"); + } + + var semicolon = tokens.Skip(first).TakeWhile(token => token.Kind != TokenKind.Semicolon).Count(); + var start = Offset(text, tokens[first]); + var endToken = tokens[first + semicolon - 1]; + var end = Offset(text, endToken) + endToken.Text.Length + (endToken.Kind == TokenKind.String ? 2 : 0); + return text[..start] + written + text[end..]; + } + + // The offset in text of where a token starts. + private static int Offset(string text, Token token) + { + var offset = 0; + for (var line = 1; line < token.Line; line++) + { + offset = text.IndexOf('\n', offset) + 1; + } + + return offset + token.Column - 1; + } + + private static List<string> SplitList(string value) => [.. CommandLine.SplitList(value)]; + + // An OS lock on the file's lock in TAZEL_HOME/Locks, released when this process ends, however it ends. + private static FileStream Lock(string file) + { + var locks = Path.Combine(TazelHome.Directory(), "Locks"); + Directory.CreateDirectory(locks); + var name = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetFullPath(file))))[..16]; + var path = Path.Combine(locks, $"options-{name}.lock"); + for (var attempt = 0; ; attempt++) + { + try + { + return new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + } + catch (IOException) when (attempt < 100) + { + System.Threading.Thread.Sleep(50); + } + } + } +} diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 231da7c..66638a6 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -212,6 +212,35 @@ internal static class Help --algorithm ed25519|rsa-4096|ml-dsa the algorithm; default: ed25519. ml-dsa is ML-DSA-65 (FIPS 204). """), + ["options"] = new("tazel options validate|get|what-is|update: the options of tazel_options.txt, layer by layer.", """ + tazel options validate [--user | --project | --local] + tazel options get <setting> [--user | --project | --local] + tazel options what-is <setting> + tazel options update <setting> <value> [--user | --project] [--create] + + The layers of tazel_options.txt, lowest first: the user's ($TAZEL_HOME/User/), the directories above this one, + farthest first, this machine's for the project ($TAZEL_HOME/Projects/<key>/), and this directory; the + command line is above them all. Each option comes from the highest layer that sets it; a sandbox asked + for anywhere stays asked for. validate reads every layer, or the one a flag names, and runs nothing. get + prints the value that holds and the file it came from, or with a flag the value of that layer alone. + what-is says what an option takes and means. update sets an option in ./tazel_options.txt, or the user's + or the project's file: it replaces the value where it stands or adds the entry, keeps the rest of the file, + and needs --create for a file that is not there yet. An option set inside .if or in an included file is + left for you to edit. + """), + ["custom-cmds"] = new("tazel custom-cmds validate: checks the layers of tazel_custom.txt.", """ + tazel custom-cmds validate [--user | --project | --local] + + Reads every layer of tazel_custom.txt, or the one a flag names, as tazel custom would, and runs nothing. + A command of a higher layer replaces the one of the same name below it. + """), + ["envs"] = new("tazel envs validate: checks the layers of tazel_envs.txt.", """ + tazel envs validate [--user | --project | --local] + + Reads every layer of tazel_envs.txt, or the one a flag names, and runs none of its programs or shell lines. + The main module takes the layers around its root, a value of a higher layer replacing the one of the same + name, and runs every value in its root; a module it depends on takes its own file alone. + """), ["dotnet"] = new("tazel dotnet get|what-is: the .NET runtime of this Tazel process and terms of .NET.", """ tazel dotnet get <setting> tazel dotnet what-is <term> diff --git a/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationLayers.cs b/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationLayers.cs new file mode 100644 index 0000000..0ddb049 --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationLayers.cs @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace Progmasoft.Tazel.Dsl.Configuration; + +/// <summary>Where a layer of configuration comes from, lowest first; the command line is above them all.</summary> +public enum LayerKind +{ + /// <summary><c>$TAZEL_HOME/User/</c>: the user's own settings.</summary> + User, + + /// <summary>A directory above the one the command runs in.</summary> + Parent, + + /// <summary><c>$TAZEL_HOME/Projects/<key>/</c>: this machine's settings of the module, outside it.</summary> + Project, + + /// <summary>The directory the command runs in.</summary> + Local, +} + +/// <summary>One file of a layer.</summary> +/// <param name="Kind">The layer.</param> +/// <param name="File">Its full path.</param> +public sealed record Layer(LayerKind Kind, string File) +{ + /// <summary>The layer in words, for <c>tazel options get</c>.</summary> + public string Description => Kind switch + { + LayerKind.User => "the user's", + LayerKind.Parent => "a directory above", + LayerKind.Project => "this machine's for the project", + _ => "the current directory's", + }; +} + +/// <summary> +/// The files of a kind that hold in a directory, lowest first: <c>$TAZEL_HOME/User/</c>, the directories above, the +/// farthest first, <c>$TAZEL_HOME/Projects/<key>/</c> of the module the directory is in, and the directory itself. +/// So the project's settings outrank every directory above, the module root too unless it is the directory itself. +/// A file counted in one layer is not counted again in another. +/// </summary> +public static class ConfigurationLayers +{ + /// <summary>The files named <paramref name="fileName"/> that apply in <paramref name="directory"/>, lowest first.</summary> + public static IReadOnlyList<Layer> For(string fileName, string directory, bool withProject = true) + { + var full = Path.GetFullPath(directory); + var candidates = new List<Layer> { new(LayerKind.User, Path.Combine(TazelHome.Directory(), "User", fileName)) }; + var above = new List<string>(); + for (var parent = Directory.GetParent(full); parent is not null; parent = parent.Parent) + { + above.Add(Path.Combine(parent.FullName, fileName)); + } + + candidates.AddRange(above.AsEnumerable().Reverse().Select(file => new Layer(LayerKind.Parent, file))); + if (withProject && ModuleRoot(full) is { } root) + { + candidates.Add(new Layer(LayerKind.Project, Path.Combine(ProjectKey.Directory(root), fileName))); + } + + candidates.Add(new Layer(LayerKind.Local, Path.Combine(full, fileName))); + var seen = new HashSet<string>(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + var layers = new List<Layer>(); + + // The highest layer keeps a file two layers name. + foreach (var layer in candidates.AsEnumerable().Reverse()) + { + if (IsFile(layer.File) && seen.Add(ConfigurationResolver.Canonical(layer.File))) + { + layers.Add(layer); + } + } + + layers.Reverse(); + return layers; + } + + /// <summary>The file of one layer for <paramref name="directory"/>, whether it exists or not.</summary> + public static string FileOf(LayerKind kind, string fileName, string directory, bool create = false) => kind switch + { + LayerKind.User => Path.Combine(TazelHome.Directory(), "User", fileName), + LayerKind.Project => Path.Combine( + ProjectKey.Directory(ModuleRoot(Path.GetFullPath(directory)) + ?? throw new ConfigurationHomeException($"{Path.GetFullPath(directory)} is in no module, so it has no project settings"), create), + fileName), + _ => Path.Combine(Path.GetFullPath(directory), fileName), + }; + + // The nearest directory at or above with a MODULE.csx, or null. + private static string? ModuleRoot(string directory) + { + for (var current = new DirectoryInfo(directory); current is not null; current = current.Parent) + { + if (File.Exists(Path.Combine(current.FullName, "MODULE.csx"))) + { + return current.FullName; + } + } + + return null; + } + + // A file that cannot be looked at is an error, never a file that is not there, so no layer is skipped quietly. + private static bool IsFile(string file) + { + try + { + return (File.GetAttributes(file) & FileAttributes.Directory) == 0; + } + catch (Exception error) when (error is FileNotFoundException or DirectoryNotFoundException) + { + return false; + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + throw new ConfigurationHomeException($"{file} could not be inspected: {error.Message}", error); + } + } +} diff --git a/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationResolver.cs b/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationResolver.cs index aa20c1d..6461587 100644 --- a/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationResolver.cs +++ b/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationResolver.cs @@ -338,16 +338,24 @@ public static class ConfigurationResolver /// <summary> /// <paramref name="path"/> with every link of it followed, so two names of one file are one file and a link - /// cannot lead out of a directory. + /// cannot lead out of a directory; on Windows each part is written as the directory holds it, so a path typed in + /// another case is the same path. /// </summary> - internal static string Canonical(string path) + public static string Canonical(string path) { var full = Path.GetFullPath(path); var root = Path.GetPathRoot(full)!; - var current = root; + var current = OperatingSystem.IsWindows() ? root.ToUpperInvariant() : root; foreach (var part in full[root.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) { - var next = Path.Combine(current, part); + var name = part; + if (OperatingSystem.IsWindows() && System.IO.Directory.Exists(current)) + { + name = System.IO.Directory.EnumerateFileSystemEntries(current, part).Select(Path.GetFileName) + .FirstOrDefault(entry => string.Equals(entry, part, StringComparison.OrdinalIgnoreCase)) ?? part; + } + + var next = Path.Combine(current, name); FileSystemInfo info = Directory.Exists(next) ? new DirectoryInfo(next) : new FileInfo(next); current = info.LinkTarget is not null && info.ResolveLinkTarget(returnFinalTarget: true) is { } resolved ? Path.GetFullPath(resolved.FullName) diff --git a/src/Progmasoft.Tazel/Dsl/Configuration/ProjectKey.cs b/src/Progmasoft.Tazel/Dsl/Configuration/ProjectKey.cs new file mode 100644 index 0000000..bb51f30 --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Configuration/ProjectKey.cs @@ -0,0 +1,89 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Progmasoft.Tazel.Dsl.Configuration; + +/// <summary> +/// The key of a project in <c>$TAZEL_HOME/Projects/</c>: the algorithm of Agenceland's <c>projectKey</c>, applied to the +/// canonical root of the module (the directory of its <c>MODULE.csx</c>), so every directory of a module shares it. +/// </summary> +public static class ProjectKey +{ + /// <summary>The most characters of the readable part; with the hash the key stays well below 255 bytes.</summary> + public const int MaxReadableLength = 200; + + /// <summary>The name of the file that keeps the canonical root of a project's directory.</summary> + public const string IdentityFile = "identity.txt"; + + /// <summary> + /// The key of <paramref name="canonicalPath"/>: each UTF-16 unit outside A-Z, a-z and 0-9 becomes <c>-</c>; on + /// Unix the last part is joined to the rest by <c>--</c>; the readable part keeps at most its last 200 characters, + /// and <c>-</c> and the first 16 hexadecimal digits of the SHA-256 of the whole path in UTF-8 follow. + /// </summary> + public static string Of(string canonicalPath, bool windows) + { + ArgumentNullException.ThrowIfNull(canonicalPath); + var readable = Encode(canonicalPath); + if (!windows) + { + var last = canonicalPath.LastIndexOf('/'); + if (last > 0) + { + readable = $"{Encode(canonicalPath[..last])}--{Encode(canonicalPath[(last + 1)..])}"; + } + } + + if (readable.Length > MaxReadableLength) + { + readable = readable[^MaxReadableLength..]; + } + + var hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(canonicalPath)))[..16]; + return $"{readable}-{hash}"; + } + + private static string Encode(string text) + { + var encoded = new StringBuilder(text.Length); + foreach (var unit in text) + { + encoded.Append(char.IsAsciiLetterOrDigit(unit) ? unit : '-'); + } + + return encoded.ToString(); + } + + /// <summary> + /// <c>$TAZEL_HOME/Projects/<key>/</c> of the module rooted at <paramref name="moduleRoot"/>. A directory there that + /// keeps another root in its identity file belongs to another project whose key is the same, and is refused; so is + /// one with no identity file. With <paramref name="create"/>, a missing directory is made with its identity. + /// </summary> + public static string Directory(string moduleRoot, bool create = false) + { + var canonical = ConfigurationResolver.Canonical(moduleRoot); + var directory = Path.Combine(TazelHome.Directory(), "Projects", Of(canonical, OperatingSystem.IsWindows())); + var identity = Path.Combine(directory, IdentityFile); + if (System.IO.Directory.Exists(directory)) + { + var kept = File.Exists(identity) ? File.ReadAllText(identity).TrimEnd('\n', '\r') : null; + if (kept != canonical) + { + throw new ConfigurationHomeException(kept is null + ? $"{directory} has no {IdentityFile}, so Tazel cannot tell whose it is; remove it or write {canonical} in it" + : $"{directory} belongs to {kept}, whose key is the same as {canonical}'s; move one of them"); + } + } + else if (create) + { + System.IO.Directory.CreateDirectory(directory); + File.WriteAllText(identity, canonical + "\n"); + } + + return directory; + } +} diff --git a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs index 7b7fb2e..de3181b 100644 --- a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs +++ b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs @@ -223,17 +223,45 @@ internal sealed class ModuleEnvironment : IEnvironmentValues /// The values of the module at <paramref name="root"/>, or null when it has no <c>tazel_envs.txt</c>; its /// conditions see <paramref name="target"/> as the platform built for (this machine's when null). /// </summary> - public static ModuleEnvironment? Load(string root, string shown, Common.Platform? target = null) + public static ModuleEnvironment? Load(string root, string shown, Common.Platform? target = null, bool inherit = false) { - var file = Path.Combine(root, TazelEnvsFile.FileName); - if (!File.Exists(file)) + var context = Configuration.ConfigurationContext.ForThisMachine(); + context = context with { Target = Configuration.SystemFacts.Of(target ?? Driver.Host.Platform) }; + + // The main module takes the layers of tazel_envs.txt around its root, a value of a higher layer replacing the + // one of the same name; a module it depends on takes its own file alone, so it sees nothing of the user's or + // the main module's. Every value runs in the root of its module. + IEnumerable<string> files; + if (inherit) { - return null; + try + { + files = Configuration.ConfigurationLayers.For(TazelEnvsFile.FileName, root).Select(layer => layer.File); + } + catch (Configuration.ConfigurationHomeException error) + { + throw new CustomCommandsException(error.Message, error); + } + } + else + { + var own = Path.Combine(root, TazelEnvsFile.FileName); + files = File.Exists(own) ? [own] : []; } - var context = Configuration.ConfigurationContext.ForThisMachine(); - context = context with { Target = Configuration.SystemFacts.Of(target ?? Driver.Host.Platform) }; - return new ModuleEnvironment(root, shown, TazelEnvsFile.Parse(File.ReadAllText(file), shown, file, context)); + var entries = new Dictionary<string, EnvEntry>(StringComparer.Ordinal); + var any = false; + foreach (var file in files) + { + any = true; + var name = file == Path.Combine(root, TazelEnvsFile.FileName) ? shown : file; + foreach (var entry in TazelEnvsFile.Parse(File.ReadAllText(file), name, file, context)) + { + entries[entry.Name] = entry; + } + } + + return any ? new ModuleEnvironment(root, shown, entries.Values.ToList()) : null; } public string? Get(string name) diff --git a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs index e0f8819..d3d60aa 100644 --- a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs +++ b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs @@ -50,6 +50,15 @@ public sealed record TazelOptions public IReadOnlyList<Runtime.DotnetSetting> DotnetSettings { get; init; } = []; } +/// <summary>The options that hold in a directory, with the layer each came from and the layers read.</summary> +/// <param name="Options">The options.</param> +/// <param name="SandboxFile">The file of the layer that asked for the sandbox, or null.</param> +/// <param name="Origins">For each option set somewhere, the layer that decided it.</param> +/// <param name="Layers">The layers read, lowest first.</param> +public sealed record LayeredOptions( + TazelOptions Options, string? SandboxFile, IReadOnlyDictionary<string, Configuration.Layer> Origins, + IReadOnlyList<Configuration.Layer> Layers); + /// <summary>What is wrong with a <c>tazel_options.txt</c>, with where it is.</summary> public sealed class TazelOptionsException : Exception { @@ -105,12 +114,14 @@ public static class TazelOptionsFile public static TazelOptions Parse(string text, string file, string? path = null, Platform? requested = null) { var machine = Configuration.ConfigurationContext.ForThisMachine(); - var chosen = Read(text, file, path, machine); + var chosen = Read(text, file, path, machine).Options; var platform = requested ?? chosen.Platform ?? Driver.Host.Platform; - return Read(text, file, path, machine with { Target = Configuration.SystemFacts.Of(platform) }); + return Read(text, file, path, machine with { Target = Configuration.SystemFacts.Of(platform) }).Options; } - private static TazelOptions Read(string text, string file, string? path, Configuration.ConfigurationContext context) + /// <summary>The options of one file and the names it sets, read for <paramref name="context"/>.</summary> + internal static (TazelOptions Options, IReadOnlySet<string> Keys) Read( + string text, string file, string? path, Configuration.ConfigurationContext context) { IReadOnlyList<Token> tokens; try @@ -122,7 +133,8 @@ public static class TazelOptionsFile throw error.Diagnostic is { } diagnostic ? new TazelOptionsException(diagnostic) : new TazelOptionsException(error.Message, error); } - return new Reader(tokens, file, text).Options(); + var reader = new Reader(tokens, file, text); + return (reader.Options(), reader.SetNames); } /// <summary>Every <c>tazel_options.txt</c> at or above <paramref name="directory"/>, the nearest first.</summary> @@ -165,49 +177,102 @@ public static class TazelOptionsFile } /// <summary> - /// The options that hold in <paramref name="directory"/>: those of the nearest file, except that a sandbox asked - /// for in any file above stays asked for, so a project cannot turn off what a directory around it requires. - /// Default options, and no file, without any. + /// The options that hold in <paramref name="directory"/>, from the layers of + /// <see cref="Configuration.ConfigurationLayers"/>: each option from the highest layer that sets it, an explicit + /// <c>false</c> or <c>auto</c> as much as any value; <c>dotnet-settings</c> name by name. A sandbox asked for in any + /// layer stays asked for, so no layer above can turn off what one below requires. The platform is chosen first, from + /// <paramref name="requested"/> or the highest layer that sets it outside conditions on <c>target_system</c>, and + /// every layer is then read for it. /// </summary> public static (TazelOptions Options, string? SandboxFile) Effective(string directory, Platform? requested = null) { - var files = Find(directory).Select(file => (File: file, Options: Read(file, requested))).ToList(); - if (files.Count == 0) + var layered = Layered(directory, requested); + return (layered.Options, layered.SandboxFile); + } + + /// <summary><see cref="Effective"/>, with the file each option came from.</summary> + public static LayeredOptions Layered(string directory, Platform? requested = null) + { + IReadOnlyList<Configuration.Layer> layers; + try + { + layers = Configuration.ConfigurationLayers.For(TazelOptions.FileName, directory); + } + catch (Configuration.ConfigurationHomeException error) { - return (new TazelOptions(), null); + throw new TazelOptionsException(error.Message, error); } - var asking = files.FirstOrDefault(entry => entry.Options.SandboxingWithMicroVM).File; - return (files[0].Options with { SandboxingWithMicroVM = asking is not null }, asking); + var texts = layers.Select(layer => (Layer: layer, Text: ReadText(layer.File))).ToList(); + var machine = Configuration.ConfigurationContext.ForThisMachine(); + var platform = requested; + if (platform is null) + { + foreach (var (layer, text) in texts) + { + var (options, keys) = Read(text, layer.File, layer.File, machine); + platform = keys.Contains("platform") ? options.Platform : platform; + } + } + + var context = machine with { Target = Configuration.SystemFacts.Of(platform ?? Driver.Host.Platform) }; + var merged = new TazelOptions(); + var origins = new Dictionary<string, Configuration.Layer>(StringComparer.Ordinal); + var settings = new List<Runtime.DotnetSetting>(); + Configuration.Layer? sandbox = null; + foreach (var (layer, text) in texts) + { + var (options, keys) = Read(text, layer.File, layer.File, context); + foreach (var key in keys) + { + origins[key] = layer; + merged = key switch + { + "sandboxing-with-microvm" => merged with { SandboxingWithMicroVM = merged.SandboxingWithMicroVM || options.SandboxingWithMicroVM }, + "microvm-network" => merged with { MicroVMNetwork = options.MicroVMNetwork }, + "microvm-memory" => merged with { MicroVMMemory = options.MicroVMMemory }, + "microvm-cpus" => merged with { MicroVMCpus = options.MicroVMCpus }, + "platform" => merged with { Platform = options.Platform }, + _ => merged, + }; + } + + settings.AddRange(options.DotnetSettings); + sandbox = options.SandboxingWithMicroVM ? layer : sandbox; + } + + if (sandbox is not null) + { + // The layer that asked keeps the say, whatever a layer above wrote. + origins["sandboxing-with-microvm"] = sandbox; + } + + return new LayeredOptions(merged with { DotnetSettings = settings }, sandbox?.File, origins, layers); } - private static TazelOptions Read(string file, Platform? requested) + private static string ReadText(string file) { - string text; try { - text = File.ReadAllText(file); + return File.ReadAllText(file); } - catch (IOException problem) + catch (Exception problem) when (problem is IOException or UnauthorizedAccessException) { throw new TazelOptionsException($"{file} could not be read: {problem.Message}", problem); } - catch (UnauthorizedAccessException problem) - { - throw new TazelOptionsException($"{file} could not be read: {problem.Message}", problem); - } - - return Parse(text, file, file, requested); } private sealed class Reader(IReadOnlyList<Token> tokens, string file, string text) { private int _position; + /// <summary>The names the file set, once <see cref="Options"/> has read it.</summary> + public HashSet<string> SetNames { get; } = new(StringComparer.Ordinal); + public TazelOptions Options() { var options = new TazelOptions(); - var seen = new HashSet<string>(StringComparer.Ordinal); + var seen = SetNames; while (_position < tokens.Count) { var key = Take(TokenKind.Name, "the name of an option"); diff --git a/src/Progmasoft.Tazel/Project/Workspace.cs b/src/Progmasoft.Tazel/Project/Workspace.cs index 583db50..928c6e4 100644 --- a/src/Progmasoft.Tazel/Project/Workspace.cs +++ b/src/Progmasoft.Tazel/Project/Workspace.cs @@ -154,7 +154,7 @@ internal sealed class Workspace var shown = repository is null ? Dsl.Envs.TazelEnvsFile.FileName : $"@{repository}//{Dsl.Envs.TazelEnvsFile.FileName}"; try { - return Dsl.Envs.ModuleEnvironment.Load(root, shown, target); + return Dsl.Envs.ModuleEnvironment.Load(root, shown, target, inherit: repository is null); } catch (Dsl.Custom.CustomCommandsException error) { diff --git a/tests/Progmasoft.Tazel.Tests/ConfigurationLayersTests.cs b/tests/Progmasoft.Tazel.Tests/ConfigurationLayersTests.cs new file mode 100644 index 0000000..2da966b --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/ConfigurationLayersTests.cs @@ -0,0 +1,306 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Dsl.Configuration; +using Progmasoft.Tazel.Dsl.Envs; +using Progmasoft.Tazel.Dsl.Options; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class ProjectKeyTests +{ + // Made with Agenceland's projectKey (extensions/agenceland/src/core/paths.ts), so both give the same key. + [Theory] + [InlineData(false, "/home/ada/Projects/example", "-home-ada-Projects--example-4438d2120e07e07e")] + [InlineData(false, "/example", "-example-99d0533064c83d04")] + [InlineData(true, "C:\\Users\\Ada\\Projects\\example", "C--Users-Ada-Projects-example-f02e6912f5bd8b46")] + [InlineData(false, "/a/b-c/d", "-a-b-c--d-f454c3d357078a1d")] + [InlineData(false, "/a-b/c/d", "-a-b-c--d-80f3776f287feca0")] + [InlineData(false, "/home/ada/Projekte/Über", "-home-ada-Projekte---ber-277c6621570ad431")] + [InlineData(false, "/home/ada/😀/x", "-home-ada-----x-a14b49261c6fbba2")] + public void IsTheKeyOfAgenceland(bool windows, string path, string key) => Assert.Equal(key, ProjectKey.Of(path, windows)); + + [Fact] + public void ALongPathKeepsTheEndOfItsReadablePart() + { + var deep = $"/home/ada/{string.Join('/', Enumerable.Range(0, 40).Select(i => $"directory{i}"))}/example"; + var key = ProjectKey.Of(deep, windows: false); + Assert.Equal("directory24-directory25-directory26-directory27-directory28-directory29-directory30-directory31-directory32-" + + "directory33-directory34-directory35-directory36-directory37-directory38-directory39--example-c7091a666fbcdce7", key); + Assert.Equal(ProjectKey.MaxReadableLength + 17, key.Length); + } +} + +[Collection(nameof(TazelHomeCollection))] +public sealed class ConfigurationLayersTests +{ + private sealed class Home : IDisposable + { + private readonly string? _was = Environment.GetEnvironmentVariable(TazelHome.Variable); + + public Home(string value) => Environment.SetEnvironmentVariable(TazelHome.Variable, value); + + public void Dispose() => Environment.SetEnvironmentVariable(TazelHome.Variable, _was); + } + + // A home, a directory above a module, the module, and a directory in it to run in. + private static (TemporaryModule Tree, Home Home, string Here) Tree() + { + var tree = new TemporaryModule() + .Write("outer/mod/MODULE.csx", TemporaryModule.ModuleFile) + .Write("outer/mod/sub/keep", "") + .Write("home/User/keep", ""); + return (tree, new Home(Path.Combine(tree.Root, "home")), Path.Combine(tree.Root, "outer", "mod", "sub")); + } + + private static string ProjectFile(string here, string name) => ConfigurationLayers.FileOf(LayerKind.Project, name, here, create: true); + + [Fact] + public void EachOptionComesFromTheHighestLayerThatSetsIt() + { + var (tree, home, here) = Tree(); + using (tree) + using (home) + { + tree.Write("home/User/tazel_options.txt", "microvm-cpus: 1; microvm-memory: 300; microvm-network: true; platform: windows-x64;") + .Write("outer/tazel_options.txt", "microvm-cpus: 2; microvm-memory: 400;") + .Write("outer/mod/tazel_options.txt", "microvm-cpus: 3;"); + File.WriteAllText(ProjectFile(here, "tazel_options.txt"), "microvm-cpus: 4; microvm-network: false;"); + File.WriteAllText(Path.Combine(here, "tazel_options.txt"), "microvm-cpus: 5;"); + var layered = TazelOptionsFile.Layered(here); + Assert.Equal(5, layered.Options.MicroVMCpus.Amount); + Assert.Equal(400, layered.Options.MicroVMMemory.Amount); + // An explicit false is a value: the project's beats the user's true. + Assert.False(layered.Options.MicroVMNetwork); + Assert.Equal(LayerKind.Project, layered.Origins["microvm-network"].Kind); + Assert.Equal(Platform.WindowsX64, layered.Options.Platform); + Assert.Equal([LayerKind.User, LayerKind.Parent, LayerKind.Parent, LayerKind.Project, LayerKind.Local], layered.Layers.Select(l => l.Kind)); + // The command line is above every layer. + Assert.Equal(Platform.LinuxAarch64, TazelOptionsFile.Parse("", "x", Path.Combine(here, "x"), Platform.LinuxAarch64).Platform ?? Platform.LinuxAarch64); + } + } + + [Fact] + public void TheProjectOutranksTheModuleRootWhenItIsAbove() + { + var (tree, home, here) = Tree(); + using (tree) + using (home) + { + tree.Write("outer/mod/tazel_options.txt", "microvm-cpus: 3;"); + File.WriteAllText(ProjectFile(here, "tazel_options.txt"), "microvm-cpus: 4;"); + Assert.Equal(4, TazelOptionsFile.Effective(here).Options.MicroVMCpus.Amount); + // Run in the module root, its own file is the highest layer. + Assert.Equal(3, TazelOptionsFile.Effective(Path.Combine(tree.Root, "outer", "mod")).Options.MicroVMCpus.Amount); + } + } + + [Fact] + public void ASandboxAskedForInAnyLayerStays() + { + var (tree, home, here) = Tree(); + using (tree) + using (home) + { + tree.Write("home/User/tazel_options.txt", "sandboxing-with-microvm: true;"); + File.WriteAllText(Path.Combine(here, "tazel_options.txt"), "sandboxing-with-microvm: false;"); + var (options, file) = TazelOptionsFile.Effective(here); + Assert.True(options.SandboxingWithMicroVM); + Assert.EndsWith(Path.Combine("User", "tazel_options.txt"), file, StringComparison.Ordinal); + } + } + + [Fact] + public void OutsideAModuleThereIsNoProjectLayer() + { + using var tree = new TemporaryModule().Write("plain/keep", "").Write("home/User/keep", ""); + using var home = new Home(Path.Combine(tree.Root, "home")); + Assert.DoesNotContain(ConfigurationLayers.For("tazel_options.txt", Path.Combine(tree.Root, "plain")), layer => layer.Kind == LayerKind.Project); + Assert.Throws<ConfigurationHomeException>(() => ConfigurationLayers.FileOf(LayerKind.Project, "x", Path.Combine(tree.Root, "plain"))); + } + + [Fact] + public void AProjectDirectoryOfAnotherRootIsRefused() + { + var (tree, home, here) = Tree(); + using (tree) + using (home) + { + var directory = Path.GetDirectoryName(ProjectFile(here, "x"))!; + File.WriteAllText(Path.Combine(directory, ProjectKey.IdentityFile), "/somewhere/else\n"); + var error = Assert.Throws<ConfigurationHomeException>(() => ConfigurationLayers.For("tazel_options.txt", here)); + Assert.Contains("belongs to /somewhere/else", error.Message, StringComparison.Ordinal); + File.Delete(Path.Combine(directory, ProjectKey.IdentityFile)); + Assert.Contains("has no identity.txt", Assert.Throws<ConfigurationHomeException>(() => ConfigurationLayers.For("tazel_options.txt", here)).Message, + StringComparison.Ordinal); + } + } + + [Fact] + public void EveryDirectoryOfAModuleSharesItsProject() + { + var (tree, home, here) = Tree(); + using (tree) + using (home) + { + Assert.Equal(ProjectFile(here, "x"), ProjectFile(Path.Combine(tree.Root, "outer", "mod"), "x")); + } + } + + [Fact] + public void ADotnetSettingIsMergedNameByName() + { + var (tree, home, here) = Tree(); + using (tree) + using (home) + { + tree.Write("home/User/tazel_options.txt", "dotnet-settings: [\"ThreadPool.MinWorkerThreads=4\" \"GCSettings.LatencyMode=Batch\"];"); + File.WriteAllText(Path.Combine(here, "tazel_options.txt"), "dotnet-settings: [\"ThreadPool.MinWorkerThreads=6\"];"); + var effective = Runtime.DotnetSettings.Effective(TazelOptionsFile.Effective(here).Options.DotnetSettings, []); + Assert.Equal(6, effective["ThreadPool.MinWorkerThreads"].Value); + Assert.Equal(System.Runtime.GCLatencyMode.Batch, effective["GCSettings.LatencyMode"].Value); + } + } + + [Fact] + public async Task CustomCommandsAreMergedNameByName() + { + var (tree, home, here) = Tree(); + using (tree) + using (home) + { + // The commands write a file: their own output goes to the terminal, not to the test. + tree.Write("home/User/tazel_custom.txt", "hello: (\"sh\" \"-c\" \"echo user > said\");\nonly-user: (\"sh\" \"-c\" \"echo only > said\");") + .Write("outer/mod/sub/tazel_custom.txt", "hello: (\"sh\" \"-c\" \"echo here > said\");"); + Assert.SkipWhen(OperatingSystem.IsWindows(), "the commands use sh"); + var said = Path.Combine(here, "said"); + var (status, output) = await tree.TazelAsync("outer/mod/sub", "custom", "hello"); + Assert.True(status == 0, output); + Assert.Equal("here\n", File.ReadAllText(said)); + (status, output) = await tree.TazelAsync("outer/mod/sub", "custom", "only-user"); + Assert.True(status == 0, output); + Assert.Equal("only\n", File.ReadAllText(said)); + } + } + + [Fact] + public void TheMainModuleTakesTheLayersOfEnvsAndADependencyItsOwnAlone() + { + var (tree, home, here) = Tree(); + using (tree) + using (home) + { + tree.Write("home/User/tazel_envs.txt", "who: 'user'; color: 'blue';") + .Write("outer/mod/tazel_envs.txt", "who: 'module';"); + var root = Path.Combine(tree.Root, "outer", "mod"); + var main = ModuleEnvironment.Load(root, "tazel_envs.txt", inherit: true)!; + Assert.Equal("module", main.Get("who")); + Assert.Equal("blue", main.Get("color")); + var dependency = ModuleEnvironment.Load(root, "@dep//tazel_envs.txt", inherit: false)!; + Assert.Null(dependency.Get("color")); + } + } + + [Fact] + public async Task GetSaysWhereAValueCameFrom() + { + var (tree, home, here) = Tree(); + using (tree) + using (home) + { + tree.Write("home/User/tazel_options.txt", "microvm-cpus: 3;"); + var (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "get", "microvm-cpus"); + Assert.Equal(0, status); + Assert.Contains("microvm-cpus: 3 (", output, StringComparison.Ordinal); + Assert.Contains("the user's", output, StringComparison.Ordinal); + (_, output) = await tree.TazelAsync("outer/mod/sub", "options", "get", "microvm-memory"); + Assert.Contains("microvm-memory: auto (default)", output, StringComparison.Ordinal); + (_, output) = await tree.TazelAsync("outer/mod/sub", "options", "get", "microvm-cpus", "--local"); + Assert.Contains("not set", output, StringComparison.Ordinal); + (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "what-is", "microvm-cpu"); + Assert.Equal(2, status); + Assert.Contains("did you mean microvm-cpus?", output, StringComparison.Ordinal); + } + } + + [Fact] + public async Task UpdateEditsOneFileAndKeepsTheRest() + { + var (tree, home, here) = Tree(); + using (tree) + using (home) + { + var file = Path.Combine(here, "tazel_options.txt"); + File.WriteAllText(file, "# kept\nmicrovm-cpus: 2; # also kept\nmicrovm-network: true"); + var (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "update", "microvm-cpus", "8"); + Assert.True(status == 0, output); + (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "update", "platform", "linux-aarch64"); + Assert.True(status == 0, output); + Assert.Equal("# kept\nmicrovm-cpus: 8; # also kept\nmicrovm-network: true;\nplatform: linux-aarch64;\n", File.ReadAllText(file)); + (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "update", "microvm-cpus", "lots"); + Assert.Equal(1, status); + Assert.Contains("microvm-cpus: 8;", File.ReadAllText(file), StringComparison.Ordinal); + } + } + + [Fact] + public async Task UpdateNeedsCreateForANewFileAndRefusesWhatItCannotEditSafely() + { + var (tree, home, here) = Tree(); + using (tree) + using (home) + { + var (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "update", "microvm-cpus", "8", "--user"); + Assert.Equal(2, status); + Assert.Contains("add --create", output, StringComparison.Ordinal); + (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "update", "microvm-cpus", "8", "--project", "--create"); + Assert.True(status == 0, output); + Assert.Equal("microvm-cpus: 8;\n", File.ReadAllText(ProjectFile(here, "tazel_options.txt"))); + + tree.Write("outer/mod/sub/inc.options.txt", "microvm-memory: 512"); + File.WriteAllText(Path.Combine(here, "tazel_options.txt"), ".include \"inc.options.txt\"\n.if true\nmicrovm-cpus: 2;\n.end\n"); + (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "update", "microvm-cpus", "4"); + Assert.Contains("inside .if", output, StringComparison.Ordinal); + (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "update", "microvm-memory", "1024"); + Assert.Contains("in a file that tazel_options.txt includes", output, StringComparison.Ordinal); + (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "update", "microvm-cpus", "4", "--local"); + Assert.Contains("--local is for reading", output, StringComparison.Ordinal); + Assert.Equal(2, status); + } + } + + [Fact] + public async Task ValidateChecksEveryLayerOrOne() + { + var (tree, home, here) = Tree(); + using (tree) + using (home) + { + tree.Write("home/User/tazel_options.txt", "microvm-cpus: 3;").Write("outer/tazel_envs.txt", "x: 'y';") + .Write("outer/mod/sub/tazel_custom.txt", "hi: (\"echo\");"); + var (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "validate"); + Assert.True(status == 0, output); + Assert.Contains("(the user's)", output, StringComparison.Ordinal); + (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "validate", "--local"); + Assert.Contains("no tazel_options.txt holds here in that layer", output, StringComparison.Ordinal); + (status, output) = await tree.TazelAsync("outer/mod/sub", "envs", "validate"); + Assert.True(status == 0, output); + Assert.Contains("(a directory above)", output, StringComparison.Ordinal); + (status, output) = await tree.TazelAsync("outer/mod/sub", "custom-cmds", "validate", "--local"); + Assert.True(status == 0, output); + Assert.Contains("valid: tazel_custom.txt", output, StringComparison.Ordinal); + tree.Write("outer/mod/sub/tazel_custom.txt", "hi (\"echo\");"); + (status, _) = await tree.TazelAsync("outer/mod/sub", "custom-cmds", "validate"); + Assert.Equal(1, status); + (status, output) = await tree.TazelAsync("outer/mod/sub", "options", "validate", "--user", "--local"); + Assert.Equal(2, status); + Assert.Contains("name two layers", output, StringComparison.Ordinal); + } + } +}