tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Add tazel tool launch and tazel tool create-wrapper
- Commit
bbc8dbef71de3b7ede18690f93dfca372a220d3a- Author
- Leitwolf11 ·
- Parents
3cd19083d209
Changes
CHANGELOG.md | 4 + docs/commands.md | 21 ++ src/Progmasoft.Tazel/Cli/CommandLine.cs | 41 +++- src/Progmasoft.Tazel/Cli/Commands.cs | 20 +- src/Progmasoft.Tazel/Cli/Help.cs | 15 ++ src/Progmasoft.Tazel/Cli/ToolCommands.cs | 251 ++++++++++++++++++++++ src/Progmasoft.Tazel/Output/ErrorCodes.cs | 9 + src/Progmasoft.Tazel/Program.cs | 6 + tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs | 2 +- tests/Progmasoft.Tazel.Tests/MicroVMTests.cs | 2 +- tests/Progmasoft.Tazel.Tests/ToolTests.cs | 216 +++++++++++++++++++ 11 files changed, 579 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 07eba24..06c0ef1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ## Unreleased +- `tazel tool launch <name>` runs `TAZEL_TOOL_EXECUTABLE`, or the first `tazel-<name>` of `PATH` this user may run, + with its arguments as written, and passes its exit status on; `tazel tool create-wrapper <name> [-o dir]` writes a + `tazel-<name>` that runs `<name>`. Error `E0507`. + - 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 diff --git a/docs/commands.md b/docs/commands.md index 6e93195..bdb04cf 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -199,6 +199,27 @@ tazel dotnet what-is CLI .NET, CLI (the Common Language Infrastructure), CIL, CLR, C++/CLI, C#, WorkstationGC, BackgroundGC, daemon, CTS, VES and ECMA-335, offline. Tazel has no daemon: `tazel dotnet start-daemon` and the like say so. +## External tools + +```text +tazel tool launch <name> [arguments] +TAZEL_TOOL_EXECUTABLE=bin/formatter tazel tool launch formatter --check src/ +tazel tool create-wrapper <name> [-o <dir> | --output-dir <dir>] +``` + +`tazel tool launch` runs the program `TAZEL_TOOL_EXECUTABLE` names when it is set, absolute or from the current +directory, and nothing else then: an empty value, a missing file or one this user may not run is an error. Otherwise +it runs the first `tazel-<name>` of `PATH` this user may run (on Unix by `access(X_OK)`, on Windows by `PATHEXT`), +skipping empty entries, `.`, relative entries and the current directory, and searching nowhere else. Every argument +after the name reaches the tool as written, empty ones, `--` and `--help` too. The tool runs as a process of its own, +in this directory, with this environment and terminal, and its exit status is Tazel's; with +`sandboxing-with-microvm` it does not run. On Windows a batch file runs through `cmd.exe` with each argument quoted; +an argument holding `"`, `%` or a line break is refused, since `cmd.exe` would change it. + +`tazel tool create-wrapper` writes `tazel-<name>` (`tazel-<name>.bat` on Windows) into an existing directory, the +current one by default. It runs `<name>` with its arguments, `exec <name> "$@"` or `<name> %*`; Tazel never overwrites +a file, runs the wrapper or changes `PATH`. A name is a letter or digit, then letters, digits, `.`, `_` and `-`. + ## Directives of the text files `tazel_options.txt`, `tazel_custom.txt` and `tazel_envs.txt` share one grammar: besides their entries they take diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index 99550a9..6a872a4 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", "options", "custom-cmds", "envs"]; + "portal-modules", "cache", "explain", "version", "help", "dotnet", "limited-time", "options", "custom-cmds", "envs", "tool"]; private enum Kind { @@ -165,6 +165,7 @@ internal static class CommandLine 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("output-dir", Kind.Value, null, "tool"), new("message-format", Kind.Value, ["rich-stdio", "script-friendly-stdio", "jsonl", "xml"]), new("help", Kind.Flag, null), new("platform", Kind.Value, Platforms.Names, Building), @@ -261,7 +262,7 @@ internal static class CommandLine } else { - ReadShort(argument, seen); + ReadShort(argument, arguments, ref index, seen); } } @@ -275,9 +276,10 @@ internal static class CommandLine while (index < arguments.Count) { var argument = arguments[index++]; - if (command == "custom") + if (command == "custom" || (command == "tool" && positional is ["launch", _, ..])) { - // Everything after `tazel custom` belongs to the custom command, its options too. + // Everything after `tazel custom`, and after the name of `tazel tool launch`, belongs to what runs, + // its options and -- too. positional.Add(argument); } else if (argument == "--") @@ -328,6 +330,7 @@ internal static class CommandLine : throw new CommandLineException("tazel limited-time takes one word, C#: tazel limited-time C#"), ["dotnet"] = MakeDaemon, ["options"] = MakeOptions, + ["tool"] = MakeTool, ["custom-cmds"] = (scanned, output) => MakeValidate(scanned, output, ConfigurationKind.Custom), ["envs"] = (scanned, output) => MakeValidate(scanned, output, ConfigurationKind.Envs), ["cache"] = MakeCache, @@ -390,6 +393,26 @@ internal static class CommandLine }; } + private static Command MakeTool(Scanned scanned, OutputOptions output) + { + var positional = scanned.Positional; + var directory = Last(scanned.Seen, "output-dir"); + if (directory is not null && positional is not ["create-wrapper", ..]) + { + throw new CommandLineException("-o and --output-dir are options of tazel tool create-wrapper"); + } + + return positional switch + { + ["launch", var name, .. var rest] => new ToolLaunchCommand(output, name, rest), + ["create-wrapper", var name] => new ToolWrapperCommand(output, name, directory), + ["launch"] or ["create-wrapper"] => throw new CommandLineException($"tazel tool {positional[0]} needs the name of a tool"), + ["create-wrapper", ..] => throw new CommandLineException("tazel tool create-wrapper takes one name"), + _ => throw new CommandLineException("tazel tool takes launch <name> [arguments] or create-wrapper <name> [-o dir]" + + (positional.Count > 0 && Suggestions.Nearest(positional[0], ["launch", "create-wrapper"]) 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"); @@ -517,8 +540,16 @@ internal static class CommandLine seen.Add((option, values, $"--{name}")); } - private static void ReadShort(string argument, List<(Option, List<string>, string)> seen) + private static void ReadShort( + string argument, IReadOnlyList<string> arguments, ref int index, List<(Option, List<string>, string)> seen) { + if (argument == "-o") + { + var value = index < arguments.Count ? arguments[index++] : throw new CommandLineException("-o needs a directory"); + seen.Add((Options.First(o => o.Long == "output-dir"), value.Length > 0 ? [value] : throw new CommandLineException("-o has an empty value"), "-o")); + return; + } + if (argument == "-h") { seen.Add((Options.First(o => o.Long == "help"), [], "-h")); diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 5f87eeb..d805d94 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), + ToolLaunchCommand tool => Task.FromResult(LaunchTool(tool)), + ToolWrapperCommand wrapper => Task.FromResult(CreateWrapper(wrapper)), OptionsCommand options => Task.FromResult(new ConfigurationCommands(reporter, workingDirectory).Options(options)), ValidateCommand validate => Task.FromResult(new ConfigurationCommands(reporter, workingDirectory).Validate(validate.Kind, validate.Scope)), _ => Task.FromResult(RunAtOnce(command)), @@ -114,10 +116,26 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector { throw new ProjectException( $"{file} asks for sandboxing-with-microvm; this Tazel runs tazel custom inside its MicroVM, and not " + - "builds, tests or plugins, so nothing ran; set it to false to run them without the sandbox"); + "builds, tests, plugins or tools, so nothing ran; set it to false to run them without the sandbox"); } } + /// <summary>tazel tool launch: the tool as a process of its own, attached to this terminal; its status is ours.</summary> + private int LaunchTool(ToolLaunchCommand command) + { + RefuseWithoutSandbox(); + var file = Tools.Find(command.Name, workingDirectory); + return Processes.RunAttached(Tools.Command(file, command.Arguments), workingDirectory, Processes.Inherited()); + } + + /// <summary>tazel tool create-wrapper: writes the wrapper, runs nothing and changes no PATH.</summary> + private int CreateWrapper(ToolWrapperCommand command) + { + var file = Tools.CreateWrapper(command.Name, command.OutputDirectory ?? workingDirectory, OperatingSystem.IsWindows()); + reporter.Success($"wrote {file}; it runs {command.Name}, and tazel tool launch {command.Name} finds it once its directory is on PATH"); + return 0; + } + /// <summary>Says which settings of MODULE.csx this Tazel reads but does not act on, so none is taken for granted.</summary> private void WarnAboutWhatThisTazelDoesNotDo(Dsl.Module.Prelude.ModuleGlobals globals) { diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 66638a6..8303e17 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -212,6 +212,21 @@ internal static class Help --algorithm ed25519|rsa-4096|ml-dsa the algorithm; default: ed25519. ml-dsa is ML-DSA-65 (FIPS 204). """), + ["tool"] = new("tazel tool launch|create-wrapper: runs tazel-<name> tools, or writes a wrapper for a program.", """ + tazel tool launch <name> [arguments] + tazel tool create-wrapper <name> [-o <dir> | --output-dir <dir>] + + launch runs the program TAZEL_TOOL_EXECUTABLE names, when it is set, with no search after it; otherwise + the first tazel-<name> of PATH this user may run, skipping empty entries, '.' and the current directory, + and searching nowhere else. Every argument after the name goes to the tool as written, -- and --help + too. The tool runs as a process of its own in this directory, with this environment and terminal, and + its exit status is Tazel's. With sandboxing-with-microvm it does not run. On Windows a batch file runs + through cmd.exe; an argument with ", % or a line break is refused, as cmd.exe would change it. + + create-wrapper writes tazel-<name> (tazel-<name>.bat on Windows) into the directory, the current one by + default, which must exist; it runs <name> with the arguments it gets. An existing file is never + overwritten, and neither PATH nor the wrapper is touched after. + """), ["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] diff --git a/src/Progmasoft.Tazel/Cli/ToolCommands.cs b/src/Progmasoft.Tazel/Cli/ToolCommands.cs new file mode 100644 index 0000000..9f78f21 --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/ToolCommands.cs @@ -0,0 +1,251 @@ +// 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.Runtime.InteropServices; +using System.Text; +using Progmasoft.Tazel.Driver; + +namespace Progmasoft.Tazel.Cli; + +/// <summary><c>tazel tool launch <name> [arguments]</c>: runs <c>tazel-<name></c> with the arguments as given.</summary> +internal sealed record ToolLaunchCommand(OutputOptions Output, string Name, IReadOnlyList<string> Arguments) : Command(Output); + +/// <summary><c>tazel tool create-wrapper <name> [-o dir]</c>: writes <c>tazel-<name></c>, which runs <c><name></c>.</summary> +internal sealed record ToolWrapperCommand(OutputOptions Output, string Name, string? OutputDirectory) : Command(Output); + +/// <summary>A tool Tazel cannot find or start, or an argument it cannot pass on as written.</summary> +internal sealed class ToolException : Exception +{ + public ToolException(string message) + : base(message) + { + } + + public ToolException() + { + } + + public ToolException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// <summary> +/// External tools: programs named <c>tazel-<name></c> on <c>PATH</c>, or the one <c>TAZEL_TOOL_EXECUTABLE</c> +/// names. A tool runs as a process of its own, with Tazel's directory, environment and terminal, and its exit status is +/// Tazel's. No shell line is ever built from its arguments. +/// </summary> +internal static class Tools +{ + /// <summary>The variable that names the executable to run instead of searching <c>PATH</c>.</summary> + public static string ExecutableVariable { get; } = "TAZEL_TOOL_EXECUTABLE"; + + /// <summary> + /// Whether <paramref name="name"/> can name a tool: a letter or digit, then letters, digits, '.', '_' or '-', + /// with no '..', at most 64 characters, so <c>tazel-<name></c> is one plain file name and a safe word in a + /// shell or batch line. + /// </summary> + public static bool IsName(string name) => + name.Length is > 0 and <= 64 && char.IsAsciiLetterOrDigit(name[0]) && !name.Contains("..", StringComparison.Ordinal) && + name.All(letter => char.IsAsciiLetterOrDigit(letter) || letter is '.' or '_' or '-'); + + private static void CheckName(string name) + { + if (!IsName(name)) + { + throw new ToolException( + $"'{name}' is not a tool name: a letter or digit, then letters, digits, '.', '_' or '-', with no '..' and no path"); + } + } + + /// <summary> + /// The executable of the tool <paramref name="name"/>: <c>TAZEL_TOOL_EXECUTABLE</c> when it is set, with no + /// search after it, else the first <c>tazel-<name></c> of <c>PATH</c> that this user may run. Empty entries, + /// <c>.</c> and entries that are the working directory are skipped, and nothing else is searched. + /// </summary> + public static string Find(string name, string workingDirectory) + { + CheckName(name); + var chosen = Environment.GetEnvironmentVariable(ExecutableVariable); + if (chosen is not null) + { + return Chosen(chosen, workingDirectory); + } + + var here = Path.TrimEndingDirectorySeparator(Path.GetFullPath(workingDirectory)); + foreach (var entry in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator)) + { + if (entry.Length == 0 || entry == "." || !Path.IsPathFullyQualified(entry) || + string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(entry)), here, PathComparison)) + { + continue; + } + + foreach (var file in Candidates(Path.Combine(entry, $"tazel-{name}"))) + { + if (IsRunnable(file)) + { + return file; + } + } + } + + throw new ToolException( + $"no tazel-{name} on PATH that this user may run; put one in a directory of PATH, make one with " + + $"tazel tool create-wrapper {name}, or name it with {ExecutableVariable}"); + } + + private static StringComparison PathComparison => + OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + // TAZEL_TOOL_EXECUTABLE: a path, absolute or from the working directory; anything wrong with it is an error. + private static string Chosen(string chosen, string workingDirectory) + { + if (chosen.Trim().Length == 0) + { + throw new ToolException($"{ExecutableVariable} is set but empty; name an executable, or unset it to search PATH"); + } + + string file; + try + { + file = Path.GetFullPath(chosen, workingDirectory); + } + catch (Exception error) when (error is ArgumentException or NotSupportedException or PathTooLongException) + { + throw new ToolException($"{ExecutableVariable}='{chosen}' is not a path: {error.Message}", error); + } + + if (!File.Exists(file)) + { + throw new ToolException($"{ExecutableVariable}='{chosen}' is not a file ({file})"); + } + + return IsRunnable(file) ? file + : throw new ToolException($"{ExecutableVariable}='{chosen}' is not a program this user may run ({file})"); + } + + // The names a program may have: as written on Unix; with each extension of PATHEXT on Windows. + private static IEnumerable<string> Candidates(string stem) + { + if (!OperatingSystem.IsWindows()) + { + return [stem]; + } + + var extensions = (Environment.GetEnvironmentVariable("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD") + .Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Where(extension => extension.StartsWith('.')); + return extensions.Select(extension => stem + extension.ToLowerInvariant()); + } + + /// <summary> + /// Whether this user may run <paramref name="file"/>: on Unix what <c>access(X_OK)</c> says, which weighs owner, + /// group, others and the user's rights; on Windows a native program or batch file by its extension. + /// </summary> + internal static bool IsRunnable(string file) + { + try + { + if ((File.GetAttributes(file) & FileAttributes.Directory) != 0) + { + return false; + } + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + return false; + } + + return OperatingSystem.IsWindows() + ? Path.GetExtension(file).ToLowerInvariant() is ".exe" or ".com" or ".bat" or ".cmd" + : Access(file, 1) == 0; + } + + [DllImport("libc", EntryPoint = "access", SetLastError = true, CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)] + [DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)] + private static extern int Access(string path, int mode); + + /// <summary> + /// The command that runs <paramref name="file"/> with <paramref name="arguments"/>: the program itself, or for a + /// batch file cmd.exe with a line in which every argument is quoted. cmd.exe expands <c>%</c> and ends a quoted + /// word at <c>"</c> whatever stands around them, so an argument with either, or with a line break or NUL, is + /// refused rather than changed. + /// </summary> + public static IReadOnlyList<string> Command(string file, IReadOnlyList<string> arguments) + { + ArgumentNullException.ThrowIfNull(arguments); + if (!IsBatch(file)) + { + return [file, .. arguments]; + } + + var unsafeArgument = arguments.Select((argument, index) => (argument, index)) + .FirstOrDefault(entry => !IsBatchSafe(entry.argument)); + if (unsafeArgument.argument is not null) + { + throw new ToolException( + $"argument {unsafeArgument.index + 1} ('{unsafeArgument.argument}') holds \", %, a line break or NUL, which a batch " + + "file cannot be given as written; Tazel does not change it, so nothing ran"); + } + + if (!IsBatchSafe(file)) + { + throw new ToolException($"the path of the batch file {file} holds \" or %, which cmd.exe cannot be given as written"); + } + + var line = new StringBuilder("\"\"").Append(file).Append('"'); + foreach (var argument in arguments) + { + line.Append(" \"").Append(argument).Append('"'); + } + + line.Append('"'); + var cmd = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe"); + return [cmd, "/d", "/s", "/c", line.ToString()]; + } + + private static bool IsBatch(string file) => + OperatingSystem.IsWindows() && Path.GetExtension(file).ToLowerInvariant() is ".bat" or ".cmd"; + + internal static bool IsBatchSafe(string text) => text.IndexOfAny(['"', '%', '\r', '\n', '\0']) < 0; + + /// <summary>Writes the wrapper of <paramref name="name"/> in <paramref name="directory"/>, which must exist, and returns it.</summary> + public static string CreateWrapper(string name, string directory, bool windows) + { + CheckName(name); + var full = Path.GetFullPath(directory); + if (!Directory.Exists(full)) + { + throw new ToolException($"{full} is not a directory; make it first, Tazel does not"); + } + + var file = Path.Join(full, windows ? $"tazel-{name}.bat" : $"tazel-{name}"); + var text = windows + ? $"@echo off\r\n{name} %*\r\nexit /b %errorlevel%\r\n" + : $"#!/bin/sh\nexec {name} \"$@\"\n"; + try + { + // CreateNew: an existing file, or one made in the meantime, is never overwritten. + using var stream = new FileStream(file, FileMode.CreateNew, FileAccess.Write, FileShare.None); + stream.Write(new UTF8Encoding(false).GetBytes(text)); + } + catch (IOException error) when (File.Exists(file) || Directory.Exists(file)) + { + throw new ToolException($"{file} is already there; Tazel does not overwrite it", error); + } + + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | + UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + } + + return file; + } +} diff --git a/src/Progmasoft.Tazel/Output/ErrorCodes.cs b/src/Progmasoft.Tazel/Output/ErrorCodes.cs index 53a8b81..29c8b04 100644 --- a/src/Progmasoft.Tazel/Output/ErrorCodes.cs +++ b/src/Progmasoft.Tazel/Output/ErrorCodes.cs @@ -86,6 +86,7 @@ internal static partial class ErrorCodes public const string MicroVM = "E0504"; public const string CacheKey = "E0505"; public const string DotnetSettingRefused = "E0506"; + public const string Tool = "E0507"; public const string Label = "E0600"; private const string Lexer = "the text files: tazel_custom.txt, tazel_options.txt and tazel_envs.txt"; @@ -163,6 +164,14 @@ internal static partial class ErrorCodes "and in percent. Limits per object heap need both SOH and LOH; their percentages are each below 100, and so is " + "their sum. .NET itself may refuse a heap limit below what this process has committed, a latency mode its GC " + "cannot take, or thread counts it does not allow. Nothing of the command ran.", null, null, "tazel"), + new(Tool, "a tool Tazel cannot find, start or give its arguments", + "tazel tool launch <name> runs TAZEL_TOOL_EXECUTABLE when it is set, and nothing else then: it must be a " + + "program this user may run, its path absolute or from the working directory. Otherwise it runs the first " + + "tazel-<name> of PATH this user may run, skipping empty entries, '.' and the working directory, and searching " + + "nowhere else. A name is letters, digits, '.', '_' and '-'. On Windows a batch file runs through cmd.exe, which " + + "cannot be given an argument with \", % or a line break as written, so such an argument is refused. " + + "tazel tool create-wrapper writes tazel-<name> into a directory that exists and never overwrites a file.", + "TAZEL_TOOL_EXECUTABLE= tazel tool launch fmt", "TAZEL_TOOL_EXECUTABLE=./bin/fmt tazel tool launch fmt", "tazel"), new(CommandLine, "a command line Tazel cannot take", "The command, an option or a value is not one Tazel knows, or a command got arguments it does not take. Tazel " + "suggests the nearest spelling when there is one. tazel help lists the commands, and tazel help <command> --long " + diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index d4ebf65..d152e21 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -76,6 +76,12 @@ internal static class Program "A key with no name on it opens nothing, least of all a cache."); return 1; } + catch (ToolException error) + { + reporter.Error(ErrorCodes.Tool, error.Message, "tazel explain E0507 says where Tazel looks for tools", + "Tazel looked everywhere it promised to, and nowhere else."); + return 1; + } catch (MicroVM.MicroVMException error) { reporter.Error(ErrorCodes.MicroVM, error.Message, null, diff --git a/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs b/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs index cee04a4..e1aaec2 100644 --- a/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs +++ b/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs @@ -110,7 +110,7 @@ public sealed class BuildCommandTests module.Write("tazel_options.txt", "sandboxing-with-microvm: true;"); var (status, output) = await module.TazelAsync(".", "build", "//..."); Assert.Equal(1, status); - Assert.Contains("and not builds, tests or plugins, so nothing ran", output, StringComparison.Ordinal); + Assert.Contains("and not builds, tests, plugins or tools, so nothing ran", output, StringComparison.Ordinal); } [Fact] diff --git a/tests/Progmasoft.Tazel.Tests/MicroVMTests.cs b/tests/Progmasoft.Tazel.Tests/MicroVMTests.cs index b07971f..dfe9867 100644 --- a/tests/Progmasoft.Tazel.Tests/MicroVMTests.cs +++ b/tests/Progmasoft.Tazel.Tests/MicroVMTests.cs @@ -122,7 +122,7 @@ public sealed class MicroVMFilesTests .Write("tazel_options.txt", "sandboxing-with-microvm: true;\n"); var (status, output) = await module.TazelAsync(".", "build", "//..."); Assert.Equal(1, status); - Assert.Contains("runs tazel custom inside its MicroVM, and not builds, tests or plugins", output, StringComparison.Ordinal); + Assert.Contains("runs tazel custom inside its MicroVM, and not builds, tests, plugins or tools", output, StringComparison.Ordinal); } } diff --git a/tests/Progmasoft.Tazel.Tests/ToolTests.cs b/tests/Progmasoft.Tazel.Tests/ToolTests.cs new file mode 100644 index 0000000..d2ef71c --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/ToolTests.cs @@ -0,0 +1,216 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class ToolTests +{ + // Another tazel process with its own PATH and TAZEL_TOOL_EXECUTABLE. + private static async Task<(int Status, string Output)> Tazel(string directory, IDictionary<string, string?> environment, params string[] arguments) + { + var start = new ProcessStartInfo("dotnet", ["exec", Path.Combine(AppContext.BaseDirectory, "tazel.dll"), "--color", "never", .. arguments]) + { + WorkingDirectory = directory, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + start.Environment.Remove(Tools.ExecutableVariable); + foreach (var (name, value) in environment) + { + if (value is null) + { + start.Environment.Remove(name); + } + else + { + start.Environment[name] = value; + } + } + + using var process = Process.Start(start)!; + var output = await process.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken); + output += await process.StandardError.ReadToEndAsync(TestContext.Current.CancellationToken); + await process.WaitForExitAsync(TestContext.Current.CancellationToken); + return (process.ExitCode, output); + } + + // A tool that prints each argument in brackets and leaves with status 7. + private static string Tool(string directory, string name, bool executable = true) + { + var file = Path.Combine(directory, name); + File.WriteAllText(file, "#!/bin/sh\nfor a in \"$@\"; do printf '[%s]' \"$a\"; done; echo; exit 7\n"); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(file, executable ? UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute : UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + return file; + } + + private static string WithPath(params string[] directories) => + string.Join(Path.PathSeparator, [.. directories, .. (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator)]); + + [Theory] + [InlineData("fmt")] + [InlineData("clang-format")] + [InlineData("a.b_c-9")] + public void TakesPlainNames(string name) => Assert.True(Tools.IsName(name)); + + [Theory] + [InlineData("")] + [InlineData("../x")] + [InlineData("a/b")] + [InlineData("a\\b")] + [InlineData("a..b")] + [InlineData("-x")] + [InlineData(".x")] + [InlineData("a b")] + [InlineData("a;b")] + [InlineData("a$b")] + [InlineData("a&b")] + public void RefusesNamesThatAreNotPlain(string name) => Assert.False(Tools.IsName(name)); + + [Theory] + [InlineData("plain", true)] + [InlineData("with space & (parentheses) | ^ < > !", true)] + [InlineData("", true)] + [InlineData("a\"b", false)] + [InlineData("100%", false)] + [InlineData("a\nb", false)] + public void KnowsWhatABatchFileCanBeGiven(string argument, bool safe) => Assert.Equal(safe, Tools.IsBatchSafe(argument)); + + [Fact] + public void ANativeToolGetsItsArgumentsAsWritten() => + Assert.Equal(["/bin/tool", "", "--", "--help", "a b", "%x%"], Tools.Command("/bin/tool", ["", "--", "--help", "a b", "%x%"])); + + [Fact] + public void TheCommandLineGivesEverythingAfterTheNameToTheTool() + { + var command = Assert.IsType<ToolLaunchCommand>(CommandLine.Parse(["tool", "launch", "fmt", "--check", "--", "-h", "--color", ""])); + Assert.Equal("fmt", command.Name); + Assert.Equal(["--check", "--", "-h", "--color", ""], command.Arguments); + Assert.Equal("out", Assert.IsType<ToolWrapperCommand>(CommandLine.Parse(["tool", "create-wrapper", "fmt", "-o", "out"])).OutputDirectory); + Assert.Equal("out", Assert.IsType<ToolWrapperCommand>(CommandLine.Parse(["tool", "create-wrapper", "fmt", "--output-dir=out"])).OutputDirectory); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["tool", "launch"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["tool", "create-wrapper", "a", "b"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["tool", "lunch", "x"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["build", "-o", "x"])); + } + + [Fact] + public async Task LaunchFindsTheToolOnPathAndPassesItsStatusOn() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "the tools are shell scripts"); + using var module = new TemporaryModule().Write("bin/keep", "").Write("work/keep", ""); + Tool(Path.Combine(module.Root, "bin"), "tazel-show"); + var (status, output) = await Tazel(Path.Combine(module.Root, "work"), + new Dictionary<string, string?> { ["PATH"] = WithPath(Path.Combine(module.Root, "bin")) }, + "tool", "launch", "show", "", "--", "--version", "a b"); + Assert.Equal(7, status); + Assert.Contains("[][--][--version][a b]", output, StringComparison.Ordinal); + } + + [Fact] + public async Task LaunchSearchesNeitherTheWorkingDirectoryNorDotNorEmptyEntries() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "the tools are shell scripts"); + using var module = new TemporaryModule().Write("work/keep", ""); + var work = Path.Combine(module.Root, "work"); + Tool(work, "tazel-here"); + var path = string.Join(Path.PathSeparator, ".", "", work, "work", "/usr/bin", "/bin"); + var (status, output) = await Tazel(work, new Dictionary<string, string?> { ["PATH"] = path }, "tool", "launch", "here"); + Assert.Equal(1, status); + Assert.Contains("error[E0507]: no tazel-here on PATH", output, StringComparison.Ordinal); + } + + [Fact] + public async Task LaunchSkipsAFileThisUserMayNotRun() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "Unix permissions"); + using var module = new TemporaryModule().Write("a/keep", "").Write("b/keep", ""); + Tool(Path.Combine(module.Root, "a"), "tazel-two", executable: false); + Tool(Path.Combine(module.Root, "b"), "tazel-two"); + var (status, output) = await Tazel(module.Root, + new Dictionary<string, string?> { ["PATH"] = WithPath(Path.Combine(module.Root, "a"), Path.Combine(module.Root, "b")) }, + "tool", "launch", "two", "x"); + Assert.Equal(7, status); + Assert.Contains("[x]", output, StringComparison.Ordinal); + } + + [Fact] + public async Task TheExecutableVariableWinsAndHasNoFallback() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "the tools are shell scripts"); + using var module = new TemporaryModule().Write("bin/keep", ""); + Tool(Path.Combine(module.Root, "bin"), "tazel-x"); + Tool(module.Root, "mine"); + Tool(module.Root, "locked", executable: false); + var path = WithPath(Path.Combine(module.Root, "bin")); + var (status, output) = await Tazel(module.Root, new Dictionary<string, string?> { ["PATH"] = path, [Tools.ExecutableVariable] = "./mine" }, + "tool", "launch", "x", "chosen"); + Assert.Equal(7, status); + Assert.Contains("[chosen]", output, StringComparison.Ordinal); + foreach (var (value, message) in new[] { ("", "is set but empty"), ("./nowhere", "is not a file"), ("./locked", "is not a program this user may run"), ("bin", "is not a file") }) + { + (status, output) = await Tazel(module.Root, new Dictionary<string, string?> { ["PATH"] = path, [Tools.ExecutableVariable] = value }, + "tool", "launch", "x"); + Assert.Equal(1, status); + Assert.Contains(message, output, StringComparison.Ordinal); + } + } + + [Fact] + public async Task LaunchRefusesToRunWhenASandboxIsAskedFor() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "the tools are shell scripts"); + using var module = new TemporaryModule().Write("tazel_options.txt", "sandboxing-with-microvm: true;"); + Tool(module.Root, "mine"); + var (status, output) = await Tazel(module.Root, new Dictionary<string, string?> { [Tools.ExecutableVariable] = "./mine" }, + "tool", "launch", "x"); + Assert.Equal(1, status); + Assert.Contains("builds, tests, plugins or tools, so nothing ran", output, StringComparison.Ordinal); + } + + [Fact] + public void CreateWrapperWritesARunnableWrapperOnceAndNeverOverwrites() + { + using var module = new TemporaryModule(); + var file = Tools.CreateWrapper("fmt", module.Root, windows: false); + Assert.Equal(Path.Combine(module.Root, "tazel-fmt"), file); + Assert.Equal("#!/bin/sh\nexec fmt \"$@\"\n", File.ReadAllText(file)); + if (!OperatingSystem.IsWindows()) + { + Assert.True(Tools.IsRunnable(file)); + } + + Assert.Contains("already there", Assert.Throws<ToolException>(() => Tools.CreateWrapper("fmt", module.Root, windows: false)).Message, + StringComparison.Ordinal); + Assert.Equal("#!/bin/sh\nexec fmt \"$@\"\n", File.ReadAllText(file)); + var batch = Tools.CreateWrapper("fmt", module.Root, windows: true); + Assert.Equal("@echo off\r\nfmt %*\r\nexit /b %errorlevel%\r\n", File.ReadAllText(batch)); + Assert.Throws<ToolException>(() => Tools.CreateWrapper("fmt", Path.Combine(module.Root, "missing"), windows: false)); + Assert.Throws<ToolException>(() => Tools.CreateWrapper("../fmt", module.Root, windows: false)); + } + + [Fact] + public async Task AWrapperIsFoundAndRunsItsProgram() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "Unix wrapper"); + using var module = new TemporaryModule().Write("bin/keep", "").Write("work/keep", ""); + var bin = Path.Combine(module.Root, "bin"); + Tool(bin, "show"); + var (status, output) = await Tazel(Path.Combine(module.Root, "work"), new Dictionary<string, string?>(), "tool", "create-wrapper", "show", "-o", bin); + Assert.True(status == 0, output); + (status, output) = await Tazel(Path.Combine(module.Root, "work"), new Dictionary<string, string?> { ["PATH"] = WithPath(bin) }, + "tool", "launch", "show", "x y", ""); + Assert.Equal(7, status); + Assert.Contains("[x y][]", output, StringComparison.Ordinal); + } +}