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 explain --short and shell-completion for bash, zsh, fish and powershell
- Commit
ff04e2358fe81dd84e8d4fb5ffbb97861792c94a- Author
- Leitwolf11 ·
- Parents
0e3307147194
Changes
CHANGELOG.md | 3 + docs/commands.md | 2 + src/Progmasoft.Tazel/Cli/CommandLine.cs | 46 +- src/Progmasoft.Tazel/Cli/Commands.cs | 3 + src/Progmasoft.Tazel/Cli/Help.cs | 28 +- src/Progmasoft.Tazel/Cli/MoreCommands.cs | 21 +- src/Progmasoft.Tazel/Cli/ShellCompletion.cs | 498 +++++++++++++++++++++ src/Progmasoft.Tazel/Output/Reporter.cs | 19 +- src/Progmasoft.Tazel/Program.cs | 2 +- .../ShellCompletionAndExplainTests.cs | 166 +++++++ 10 files changed, 759 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e2bbbd..517773e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ ## Unreleased +- `tazel explain <code>` now supports `--short` (brief one-line summary) alongside the medium default and `--long` (full). +- `tazel shell-completion bash|zsh|fish|powershell` emits shell completion scripts to standard output without requiring a + module (PowerShell requires 5.1 or later; e.g. `source <(tazel shell-completion zsh)`). - `tazel help [command]` now supports `--short` (brief) alongside the medium default and `--long` (full). - `tazel license [--output|-o text|md|markdown|rst]` prints Tazel's MIT license, the Progmasoft Patent Grant 1.1, and the licenses of the libraries Tazel ships with to standard output. diff --git a/docs/commands.md b/docs/commands.md index 6144fe8..9c9f53c 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -22,7 +22,9 @@ | `tazel package` | writes `.tazel/package/$group.$module-$version.tazel.tar.xz` and its `.sha256sums` | | `tazel custom <name> [arguments]` | runs a command of the `tazel_custom.txt` of the current directory | | `tazel version`, `tazel help [command] [--short\|--long]` | print the version, or what Tazel or one command does (medium by default, `--short` brief, `--long` full) | +| `tazel explain <code> [--short\|--long]` | explains an error code (`--short` one-line summary, medium by default, `--long` full with examples and related codes) | | `tazel license [--output\|-o text\|md\|markdown\|rst]` | prints Tazel's MIT license, the Progmasoft Patent Grant 1.1, and the licenses of shipped libraries to stdout | +| `tazel shell-completion bash\|zsh\|fish\|powershell` | prints a shell completion script to stdout (PowerShell requires 5.1 or later; e.g. `source <(tazel shell-completion zsh)`) | ## Options diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index 58a43e5..6ab0fa8 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -127,7 +127,13 @@ internal sealed record QueryCommand(OutputOptions Output, QueryKind Kind, string internal sealed record FetchCommand(OutputOptions Output) : Command(Output); -internal sealed record ExplainCommand(OutputOptions Output, string Code, bool Long) : Command(Output); +internal sealed record ExplainCommand(OutputOptions Output, string Code, HelpLength Length = HelpLength.Medium) : Command(Output) +{ + public bool Long => Length == HelpLength.Long; +} + +/// <summary><c>tazel shell-completion bash|zsh|fish|powershell</c>: emits a shell completion script to stdout.</summary> +internal sealed record ShellCompletionCommand(OutputOptions Output, ShellKind Shell) : Command(Output); /// <summary><c>tazel dotnet get <setting></c>: what this process has for a .NET setting.</summary> internal sealed record DotnetGetCommand(OutputOptions Output, string Setting) : Command(Output); @@ -166,7 +172,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", "license", "dotnet", "limited-time", "options", "custom-cmds", "envs", "tool", "ignore"]; + "portal-modules", "cache", "explain", "version", "help", "license", "shell-completion", "dotnet", "limited-time", "options", "custom-cmds", "envs", "tool", "ignore"]; private enum Kind { @@ -210,7 +216,7 @@ internal static class CommandLine new("linker-options", Kind.List, null, Building), new("zig-compiler-options", Kind.List, null, Building), new("expunge", Kind.Flag, null, "clean"), - new("short", Kind.Flag, null, "help"), + new("short", Kind.Flag, null, "help", "explain"), new("long", Kind.Flag, null, "help", "explain"), new("exact", Kind.Flag, null, "portal-modules"), new("algorithm", Kind.Value, ["ed25519", "rsa-4096", "ml-dsa"], "cache"), @@ -358,7 +364,7 @@ internal static class CommandLine ["query"] = (scanned, output) => MakeQuery(scanned, output, QueryKind.Query), ["cquery"] = (scanned, output) => MakeQuery(scanned, output, QueryKind.CQuery), ["aquery"] = (scanned, output) => MakeQuery(scanned, output, QueryKind.AQuery), - ["explain"] = (scanned, output) => Explain(output, scanned.Positional, scanned.Has("long")), + ["explain"] = (scanned, output) => Explain(output, scanned.Positional, scanned.Has("short"), scanned.Has("long")), ["fetch"] = (scanned, output) => Bare(scanned, new FetchCommand(output)), ["vendor"] = (scanned, output) => Bare(scanned, new VendorCommand(output)), ["portal-modules"] = (scanned, output) => PortalModules(output, scanned.Positional, scanned.Has("exact")), @@ -369,6 +375,7 @@ internal static class CommandLine : new CustomCommandLine(output, scanned.Positional), ["version"] = (scanned, output) => Bare(scanned, new VersionCommand(output)), ["license"] = MakeLicense, + ["shell-completion"] = MakeShellCompletion, // The one word after it is case-sensitive: C#, as the language is written. ["limited-time"] = (scanned, output) => scanned.Positional is ["C#"] ? new MigrateCommand(output) @@ -835,8 +842,34 @@ internal static class CommandLine return new PortalModulesCommand(output, positional[0] == "search" ? PortalAction.Search : PortalAction.Info, query, exact); } - private static ExplainCommand Explain(OutputOptions output, List<string> positional, bool @long) + private static Command MakeShellCompletion(Scanned scanned, OutputOptions output) + { + if (scanned.Positional.Count != 1) + { + throw new CommandLineException("tazel shell-completion takes one shell: bash, zsh, fish or powershell"); + } + + var raw = scanned.Positional[0]; + if (ShellCompletion.TryParse(raw, out var shell)) + { + return new ShellCompletionCommand(output, shell); + } + + var near = raw.Equals("pwsh", StringComparison.OrdinalIgnoreCase) || raw.Equals("ps", StringComparison.OrdinalIgnoreCase) + ? "powershell" + : Suggestions.Nearest(raw, ShellCompletion.Names); + throw new CommandLineException( + $"tazel shell-completion takes bash, zsh, fish or powershell, not '{raw}'" + + (near is null ? "" : $"; did you mean {near}?")); + } + + private static ExplainCommand Explain(OutputOptions output, List<string> positional, bool @short, bool @long) { + if (@short && @long) + { + throw new CommandLineException("--short and --long cannot be used together"); + } + if (positional.Count != 1) { throw new CommandLineException("tazel explain takes one error code, such as tazel explain E0406"); @@ -854,7 +887,8 @@ internal static class CommandLine throw new CommandLineException($"Tazel has no error {code}{(near is null ? "" : $"; did you mean {near}?")}"); } - return new ExplainCommand(output, code, @long); + var length = @short ? HelpLength.Short : @long ? HelpLength.Long : HelpLength.Medium; + return new ExplainCommand(output, code, length); } private static void NoPositional(string command, List<string> positional) diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 2557a70..156ada4 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -67,6 +67,9 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector case LicenseCommand license: reporter.Plain(LicenseText.Format(license.Format)); return 0; + case ShellCompletionCommand completion: + reporter.Plain(ShellCompletion.Generate(completion.Shell)); + return 0; case ExplainCommand explain: Explain(explain); return 0; diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 33a12f1..4d26f54 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -177,11 +177,12 @@ internal static class Help first: two project files in one directory, or a target Depends names in a way that is not a variable of a declaration of the same file, changes nothing. "C#" is written as here, case and all. """), - ["explain"] = new("tazel explain <code> [--long]: what an error code means and how to fix it.", """ - tazel explain <code> [--long] + ["explain"] = new("tazel explain <code> [--short|--long]: what an error code means and how to fix it.", """ + tazel explain <code> [--short|--long] - Every error of Tazel has a code, E and four digits, as in error[E0406]. tazel explain prints what the code - means and a fixed example; --long says why, and shows the wrong text and the right one side by side. + Every error of Tazel has a code, E and four digits, as in error[E0406]. --short prints a single summary + line; the default medium form prints what the code means and a fixed example; --long says why, and shows + the wrong text and the right one side by side. The first two digits say where an error comes from: 00 the text files (their comments, strings, placeholders and directives) 01 the command line @@ -192,6 +193,7 @@ internal static class Help 06 labels Examples: + tazel explain E0406 --short tazel explain E0406 tazel explain E0406 --long """), @@ -200,10 +202,10 @@ internal static class Help Prints the version of Tazel, the .NET runtime it runs on and the platform of this machine. """), - ["help"] = new("tazel help [command] [--long]: prints help.", """ - tazel help [command] [--long] + ["help"] = new("tazel help [command] [--short|--long]: prints help.", """ + tazel help [command] [--short|--long] - Prints what Tazel can do, or what one command does; --long says more. + Prints what Tazel can do, or what one command does; --short is brief, default is medium, --long says more. """), ["cache"] = new("tazel cache keygen|validate|repair: keys of a remote cache, and checks of the caches.", """ tazel cache keygen [--algorithm ed25519|rsa-4096|ml-dsa] @@ -319,6 +321,18 @@ internal static class Help Tazel ships with, always to standard output. --output, -o text|md|markdown|rst output format; default: text """), + ["shell-completion"] = new("tazel shell-completion bash|zsh|fish|powershell: prints a shell completion script.", """ + tazel shell-completion bash|zsh|fish|powershell + + Prints a completion script for the given shell to standard output. Works outside any module. + PowerShell completion requires PowerShell 5.1 or later. + + Examples: + source <(tazel shell-completion bash) + source <(tazel shell-completion zsh) + tazel shell-completion fish | source + tazel shell-completion powershell | Out-String | Invoke-Expression + """), }; private const string GlobalOptions = """ diff --git a/src/Progmasoft.Tazel/Cli/MoreCommands.cs b/src/Progmasoft.Tazel/Cli/MoreCommands.cs index 91e0e37..07a91a6 100644 --- a/src/Progmasoft.Tazel/Cli/MoreCommands.cs +++ b/src/Progmasoft.Tazel/Cli/MoreCommands.cs @@ -127,31 +127,34 @@ internal sealed partial class Commands return new PackageId(null, path); } - /// <summary>What an error code means; with --long, why, and the wrong and right text side by side.</summary> + /// <summary>What an error code means; --short is one line, default adds the first sentence and example, --long shows all.</summary> private void Explain(ExplainCommand command) { var entry = ErrorCodes.Find(command.Code)!; if (!reporter.Rich) { - reporter.Explanation(entry, command.Long, Related(entry)); + reporter.Explanation(entry, command.Length, Related(entry)); return; } var fancy = reporter.Console.Profile.Capabilities.Unicode; reporter.Console.MarkupLine( $"[red bold]{(fancy ? "✖ " : "")}{Markup.Escape(entry.Code)}[/]: [bold]{Markup.Escape(entry.Title)}[/] [grey]({Markup.Escape(entry.Where)})[/]"); - if (command.Long) + switch (command.Length) { - ExplainLong(entry, fancy); - } - else - { - ExplainShort(entry, fancy); + case HelpLength.Short: + break; + case HelpLength.Long: + ExplainLong(entry, fancy); + break; + default: + ExplainMedium(entry, fancy); + break; } } /// <summary>The first sentence of the explanation and the fixed text.</summary> - private void ExplainShort(ErrorCode entry, bool fancy) + private void ExplainMedium(ErrorCode entry, bool fancy) { var console = reporter.Console; var first = entry.Explanation.IndexOf(". ", StringComparison.Ordinal); diff --git a/src/Progmasoft.Tazel/Cli/ShellCompletion.cs b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs new file mode 100644 index 0000000..38f9e22 --- /dev/null +++ b/src/Progmasoft.Tazel/Cli/ShellCompletion.cs @@ -0,0 +1,498 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Progmasoft.Tazel.Cli; + +/// <summary>The shells <c>tazel shell-completion</c> can emit scripts for.</summary> +internal enum ShellKind +{ + Bash, + Zsh, + Fish, + PowerShell, +} + +/// <summary>Generates shell completion scripts for <c>tazel</c>.</summary> +internal static class ShellCompletion +{ + /// <summary>The accepted shell names, case-sensitive.</summary> + public static IReadOnlyList<string> Names { get; } = ["bash", "zsh", "fish", "powershell"]; + + private static readonly string[] GlobalFlags = + [ + "--color", + "--progress", + "--quiet", + "--dotnet-settings", + "--message-format", + "--help", + "-h", + ]; + + private static readonly string[] BuildFlags = + [ + "--mode", + "--platform", + "--jobs", + "--keep-going", + "--recompile", + "--no-cache", + "--feature", + "--no-feature", + "--compiler-options", + "--c-compiler-options", + "--cpp-compiler-options", + "--linker-options", + "--zig-compiler-options", + ]; + + private static readonly (string Command, string Description)[] CommandDescriptions = + [ + ("build", "Build targets"), + ("run", "Build and run one target"), + ("test", "Build and run tests"), + ("coverage", "Run tests with LLVM coverage"), + ("query", "Query the target graph"), + ("cquery", "Query targets for a platform and mode"), + ("aquery", "Print actions of targets"), + ("fetch", "Download and verify dependencies"), + ("vendor", "Copy dependencies into vendor/"), + ("clean", "Remove build outputs"), + ("package", "Create a module archive"), + ("custom", "Run a custom command from tazel_custom.txt"), + ("portal-modules", "Search or inspect Tazel Portal Modules"), + ("cache", "Manage remote cache keys and validate or repair caches"), + ("explain", "Explain an error code"), + ("version", "Print the Tazel version"), + ("help", "Print help"), + ("license", "Print Tazel and third-party licenses"), + ("shell-completion", "Print a shell completion script"), + ("dotnet", "Inspect .NET runtime settings and terms"), + ("limited-time", "Temporary migration helper"), + ("options", "Inspect or update tazel_options.txt"), + ("custom-cmds", "Validate tazel_custom.txt"), + ("envs", "Validate tazel_envs.txt"), + ("tool", "Launch or wrap external tazel tools"), + ("ignore", "Manage .tazelignore"), + ]; + + /// <summary>Parses a shell name, case-sensitively.</summary> + public static bool TryParse(string value, out ShellKind shell) + { + switch (value) + { + case "bash": + shell = ShellKind.Bash; + return true; + case "zsh": + shell = ShellKind.Zsh; + return true; + case "fish": + shell = ShellKind.Fish; + return true; + case "powershell": + shell = ShellKind.PowerShell; + return true; + default: + shell = default; + return false; + } + } + + /// <summary>Returns the completion script for <paramref name="shell"/>.</summary> + public static string Generate(ShellKind shell) => shell switch + { + ShellKind.Bash => Bash(), + ShellKind.Zsh => Zsh(), + ShellKind.Fish => Fish(), + ShellKind.PowerShell => PowerShell(), + _ => throw new ArgumentOutOfRangeException(nameof(shell), shell, "Unknown shell."), + }; + + private static string Bash() + { + var commands = string.Join(' ', CommandLine.Commands); + var globals = string.Join(' ', GlobalFlags); + var buildFlags = string.Join(' ', BuildFlags); + var shells = string.Join(' ', Names); + return $$""" + # Tazel shell completion for Bash. + # Load in the current shell: source <(tazel shell-completion bash) + + _tazel_completions() { + local cur prev cmd + cur="${COMP_WORDS[COMP_CWORD]}" + prev="" + if (( COMP_CWORD > 0 )); then + prev="${COMP_WORDS[COMP_CWORD-1]}" + fi + + case "$prev" in + --color|--progress) + COMPREPLY=( $(compgen -W "always auto never" -- "$cur") ) + return 0 + ;; + --message-format) + COMPREPLY=( $(compgen -W "rich-stdio script-friendly-stdio jsonl xml" -- "$cur") ) + return 0 + ;; + --mode) + COMPREPLY=( $(compgen -W "debug release" -- "$cur") ) + return 0 + ;; + --algorithm) + COMPREPLY=( $(compgen -W "ed25519 rsa-4096 ml-dsa" -- "$cur") ) + return 0 + ;; + --output|-o) + if [[ "${COMP_WORDS[1]}" == "license" ]]; then + COMPREPLY=( $(compgen -W "text md markdown rst" -- "$cur") ) + return 0 + elif [[ "${COMP_WORDS[1]}" == "query" || "${COMP_WORDS[1]}" == "cquery" || "${COMP_WORDS[1]}" == "aquery" ]]; then + COMPREPLY=( $(compgen -W "label label_kind" -- "$cur") ) + return 0 + fi + ;; + esac + + cmd="" + local i + for (( i = 1; i < COMP_CWORD; i++ )); do + case "${COMP_WORDS[i]}" in + -*) ;; + *) + cmd="${COMP_WORDS[i]}" + break + ;; + esac + done + + if [[ -z "$cmd" ]]; then + COMPREPLY=( $(compgen -W "{{commands}} {{globals}}" -- "$cur") ) + return 0 + fi + + local words="{{globals}}" + case "$cmd" in + build|run|test|coverage) + words="$words {{buildFlags}}" + ;; + query) + words="$words --output" + ;; + cquery|aquery) + words="$words --output {{buildFlags}}" + ;; + clean) + words="$words --expunge" + ;; + help) + words="$words --short --long {{commands}}" + ;; + explain) + words="$words --short --long" + ;; + license) + words="$words --output -o" + ;; + shell-completion) + words="$words {{shells}}" + ;; + cache) + words="$words keygen validate repair --algorithm --remote" + ;; + dotnet) + words="$words get what-is start-daemon restart-daemon stop-daemon" + ;; + options) + words="$words validate get what-is update --user --project --local --create" + ;; + custom-cmds|envs) + words="$words validate --user --project --local" + ;; + tool) + words="$words launch create-wrapper --output-dir -o" + ;; + ignore) + words="$words create-from validate add delete del" + ;; + portal-modules) + words="$words search info --exact -e" + ;; + limited-time) + words="$words C#" + ;; + esac + + COMPREPLY=( $(compgen -W "$words" -- "$cur") ) + return 0 + } + + complete -F _tazel_completions tazel + """; + } + + private static string Zsh() + { + var sb = new StringBuilder(); + sb.AppendLine("#compdef tazel"); + sb.AppendLine("# Tazel shell completion for Zsh."); + sb.AppendLine("# Load in the current shell: source <(tazel shell-completion zsh)"); + sb.AppendLine(); + sb.AppendLine("_tazel() {"); + sb.AppendLine(" local -a commands"); + sb.AppendLine(" commands=("); + foreach (var (cmd, desc) in CommandDescriptions) + { + sb.Append(" '").Append(cmd).Append(':').Append(desc.Replace("'", "'\\''", StringComparison.Ordinal)).AppendLine("'"); + } + + sb.AppendLine(" )"); + sb.AppendLine(); + sb.AppendLine(" local -a global_opts"); + sb.AppendLine(" global_opts=("); + sb.AppendLine(" '--color[Color output]:when:(always auto never)'"); + sb.AppendLine(" '--progress[Progress output]:when:(always auto never)'"); + sb.AppendLine(" '--quiet[Suppress status output]'"); + sb.AppendLine(" '--dotnet-settings[Set .NET runtime settings]:settings:'"); + sb.AppendLine(" '--message-format[Message output format]:format:(rich-stdio script-friendly-stdio jsonl xml)'"); + sb.AppendLine(" '(-h --help)'{-h,--help}'[Show help]'"); + sb.AppendLine(" )"); + sb.AppendLine(); + sb.AppendLine(" _arguments -C \\"); + sb.AppendLine(" $global_opts \\"); + sb.AppendLine(" '1:command:->command' \\"); + sb.AppendLine(" '*::arg:->args'"); + sb.AppendLine(); + sb.AppendLine(" case \"$state\" in"); + sb.AppendLine(" command)"); + sb.AppendLine(" _describe -t commands 'tazel command' commands"); + sb.AppendLine(" ;;"); + sb.AppendLine(" args)"); + sb.AppendLine(" case \"$words[1]\" in"); + sb.AppendLine(" build|run|test|coverage)"); + sb.AppendLine(" _arguments $global_opts \\"); + sb.AppendLine(" '--mode[Build mode]:mode:(debug release)' \\"); + sb.AppendLine(" '--platform[Target platform]:platform:' \\"); + sb.AppendLine(" '--jobs[Parallel jobs]:jobs:' \\"); + sb.AppendLine(" '--keep-going[Continue after failures]' \\"); + sb.AppendLine(" '--recompile[Recompile all sources]' \\"); + sb.AppendLine(" '--no-cache[Bypass cache reads and writes]' \\"); + sb.AppendLine(" '*--feature[Enable toolchain feature]:feature:' \\"); + sb.AppendLine(" '*--no-feature[Disable toolchain feature]:feature:' \\"); + sb.AppendLine(" '*--compiler-options[C-family compiler options]:options:' \\"); + sb.AppendLine(" '*--c-compiler-options[C/ObjC compiler options]:options:' \\"); + sb.AppendLine(" '*--cpp-compiler-options[C++/ObjC++ compiler options]:options:' \\"); + sb.AppendLine(" '*--linker-options[Linker options]:options:' \\"); + sb.AppendLine(" '*--zig-compiler-options[Zig compiler options]:options:'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" query|cquery|aquery)"); + sb.AppendLine(" _arguments $global_opts '--output[Output format]:format:(label label_kind)'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" clean)"); + sb.AppendLine(" _arguments $global_opts '--expunge[Remove all of .tazel]'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" help)"); + sb.AppendLine(" _arguments $global_opts '--short[Short help]' '--long[Detailed help]' '1:command:->subcmd'"); + sb.AppendLine(" if [[ \"$state\" == \"subcmd\" ]]; then _describe -t commands 'tazel command' commands; fi"); + sb.AppendLine(" ;;"); + sb.AppendLine(" explain)"); + sb.AppendLine(" _arguments $global_opts '--short[Short explanation]' '--long[Detailed explanation]' '1:code:'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" license)"); + sb.AppendLine(" _arguments $global_opts '(-o --output)'{-o,--output}'[Output format]:format:(text md markdown rst)'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" shell-completion)"); + sb.AppendLine(" _arguments $global_opts '1:shell:(bash zsh fish powershell)'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" cache)"); + sb.AppendLine(" _arguments $global_opts '1:action:(keygen validate repair)' '--algorithm[Signing algorithm]:algorithm:(ed25519 rsa-4096 ml-dsa)' '--remote[Include remote cache]'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" dotnet)"); + sb.AppendLine(" _arguments $global_opts '1:action:(get what-is start-daemon restart-daemon stop-daemon)'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" options)"); + sb.AppendLine(" _arguments $global_opts '1:action:(validate get what-is update)' '--user' '--project' '--local' '--create'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" custom-cmds|envs)"); + sb.AppendLine(" _arguments $global_opts '1:action:(validate)' '--user' '--project' '--local'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" tool)"); + sb.AppendLine(" _arguments $global_opts '1:action:(launch create-wrapper)' '(-o --output-dir)'{-o,--output-dir}'[Output directory]:dir:_files -/'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" ignore)"); + sb.AppendLine(" _arguments $global_opts '1:action:(create-from validate add delete del)'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" portal-modules)"); + sb.AppendLine(" _arguments $global_opts '1:action:(search info)' '(-e --exact)'{-e,--exact}'[Exact match]'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" limited-time)"); + sb.AppendLine(" _arguments $global_opts '1:migration:(C#)'"); + sb.AppendLine(" ;;"); + sb.AppendLine(" esac"); + sb.AppendLine(" ;;"); + sb.AppendLine(" esac"); + sb.AppendLine("}"); + sb.AppendLine(); + sb.AppendLine("if (( $+functions[compdef] )); then"); + sb.AppendLine(" compdef _tazel tazel"); + sb.AppendLine("fi"); + return sb.ToString().TrimEnd(); + } + + private static string Fish() + { + var sb = new StringBuilder(); + sb.AppendLine("# Tazel shell completion for Fish."); + sb.AppendLine("# Load in the current shell: tazel shell-completion fish | source"); + sb.AppendLine(); + sb.AppendLine("complete -c tazel -f"); + sb.AppendLine(); + sb.AppendLine("# Global options"); + sb.AppendLine("complete -c tazel -l color -x -a 'always auto never' -d 'Color output'"); + sb.AppendLine("complete -c tazel -l progress -x -a 'always auto never' -d 'Progress output'"); + sb.AppendLine("complete -c tazel -l quiet -d 'Suppress status output'"); + sb.AppendLine("complete -c tazel -l dotnet-settings -x -d 'Set .NET runtime settings'"); + sb.AppendLine("complete -c tazel -l message-format -x -a 'rich-stdio script-friendly-stdio jsonl xml' -d 'Message output format'"); + sb.AppendLine("complete -c tazel -s h -l help -d 'Show help'"); + sb.AppendLine(); + sb.AppendLine("# Commands"); + foreach (var (cmd, desc) in CommandDescriptions) + { + sb.Append("complete -c tazel -n '__fish_use_subcommand' -a '").Append(cmd) + .Append("' -d '").Append(desc.Replace("'", "\\'", StringComparison.Ordinal)).AppendLine("'"); + } + + sb.AppendLine(); + sb.AppendLine("# Command-specific completions"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from build run test coverage cquery aquery' -l mode -x -a 'debug release' -d 'Build mode'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from build run test coverage cquery aquery' -l platform -x -d 'Target platform'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from build run test coverage cquery aquery' -l jobs -x -d 'Parallel jobs'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from build run test coverage cquery aquery' -l keep-going -d 'Continue after failures'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from build run test coverage' -l recompile -d 'Recompile all sources'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from build run test coverage' -l no-cache -d 'Bypass cache'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from query cquery aquery' -l output -x -a 'label label_kind' -d 'Output format'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from clean' -l expunge -d 'Remove all of .tazel'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from help' -l short -d 'Short help'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from help' -l long -d 'Detailed help'"); + sb.AppendLine($"complete -c tazel -n '__fish_seen_subcommand_from help' -a '{string.Join(' ', CommandLine.Commands)}'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from explain' -l short -d 'Short explanation'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from explain' -l long -d 'Detailed explanation'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from license' -s o -l output -x -a 'text md markdown rst' -d 'License format'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from shell-completion' -a 'bash zsh fish powershell'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from cache' -a 'keygen validate repair'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from cache' -l algorithm -x -a 'ed25519 rsa-4096 ml-dsa' -d 'Signing algorithm'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from cache' -l remote -d 'Include remote cache'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from dotnet' -a 'get what-is start-daemon restart-daemon stop-daemon'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from options' -a 'validate get what-is update'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from options custom-cmds envs' -l user -d 'User layer'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from options custom-cmds envs' -l project -d 'Project layer'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from options custom-cmds envs' -l local -d 'Local layer'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from options' -l create -d 'Create file if missing'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from custom-cmds envs' -a 'validate'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from tool' -a 'launch create-wrapper'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from tool' -s o -l output-dir -r -d 'Output directory'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from ignore' -a 'create-from validate add delete del'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from portal-modules' -a 'search info'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from portal-modules' -s e -l exact -d 'Exact match'"); + sb.AppendLine("complete -c tazel -n '__fish_seen_subcommand_from limited-time' -a 'C#'"); + return sb.ToString().TrimEnd(); + } + + private static string PowerShell() + { + // Strictly compatible with Windows PowerShell 5.1 and later (no PowerShell 7-only syntax). + var commandList = string.Join(", ", CommandLine.Commands.Select(c => $"'{c}'")); + var globalList = string.Join(", ", GlobalFlags.Select(f => $"'{f}'")); + var buildList = string.Join(", ", BuildFlags.Select(f => $"'{f}'")); + return $$""" + # Tazel shell completion for PowerShell (requires PowerShell 5.1 or later). + # Load in the current shell: tazel shell-completion powershell | Out-String | Invoke-Expression + + Register-ArgumentCompleter -Native -CommandName 'tazel' -ScriptBlock { + param($wordToComplete, $commandAst, $cursorPosition) + + $commands = @({{commandList}}) + $globalOptions = @({{globalList}}) + $buildOptions = @({{buildList}}) + + $elements = @() + foreach ($el in $commandAst.CommandElements) { + $elements += $el.Extent.Text + } + + $cmd = $null + for ($i = 1; $i -lt $elements.Count; $i++) { + $token = $elements[$i] + if ($token -eq $wordToComplete -and $i -eq ($elements.Count - 1)) { + continue + } + if (-not $token.StartsWith('-')) { + $cmd = $token + break + } + } + + $prev = '' + if ($elements.Count -ge 2) { + if ([string]::IsNullOrEmpty($wordToComplete)) { + $prev = $elements[$elements.Count - 1] + } elseif ($elements.Count -ge 3) { + $prev = $elements[$elements.Count - 2] + } + } + + $candidates = @() + if ($prev -eq '--color' -or $prev -eq '--progress') { + $candidates = @('always', 'auto', 'never') + } elseif ($prev -eq '--message-format') { + $candidates = @('rich-stdio', 'script-friendly-stdio', 'jsonl', 'xml') + } elseif ($prev -eq '--mode') { + $candidates = @('debug', 'release') + } elseif ($prev -eq '--algorithm') { + $candidates = @('ed25519', 'rsa-4096', 'ml-dsa') + } elseif (($prev -eq '--output' -or $prev -eq '-o') -and $cmd -eq 'license') { + $candidates = @('text', 'md', 'markdown', 'rst') + } elseif ($prev -eq '--output' -and ($cmd -eq 'query' -or $cmd -eq 'cquery' -or $cmd -eq 'aquery')) { + $candidates = @('label', 'label_kind') + } elseif ($null -eq $cmd) { + $candidates = $commands + $globalOptions + } else { + $candidates = $globalOptions + switch ($cmd) { + 'build' { $candidates += $buildOptions } + 'run' { $candidates += $buildOptions } + 'test' { $candidates += $buildOptions } + 'coverage' { $candidates += $buildOptions } + 'query' { $candidates += @('--output') } + 'cquery' { $candidates += @('--output') + $buildOptions } + 'aquery' { $candidates += @('--output') + $buildOptions } + 'clean' { $candidates += @('--expunge') } + 'help' { $candidates += @('--short', '--long') + $commands } + 'explain' { $candidates += @('--short', '--long') } + 'license' { $candidates += @('--output', '-o') } + 'shell-completion' { $candidates += @('bash', 'zsh', 'fish', 'powershell') } + 'cache' { $candidates += @('keygen', 'validate', 'repair', '--algorithm', '--remote') } + 'dotnet' { $candidates += @('get', 'what-is', 'start-daemon', 'restart-daemon', 'stop-daemon') } + 'options' { $candidates += @('validate', 'get', 'what-is', 'update', '--user', '--project', '--local', '--create') } + 'custom-cmds' { $candidates += @('validate', '--user', '--project', '--local') } + 'envs' { $candidates += @('validate', '--user', '--project', '--local') } + 'tool' { $candidates += @('launch', 'create-wrapper', '--output-dir', '-o') } + 'ignore' { $candidates += @('create-from', 'validate', 'add', 'delete', 'del') } + 'portal-modules' { $candidates += @('search', 'info', '--exact', '-e') } + 'limited-time' { $candidates += @('C#') } + } + } + + $candidates | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { + [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) + } + } + """; + } +} diff --git a/src/Progmasoft.Tazel/Output/Reporter.cs b/src/Progmasoft.Tazel/Output/Reporter.cs index 8279749..724e7b7 100644 --- a/src/Progmasoft.Tazel/Output/Reporter.cs +++ b/src/Progmasoft.Tazel/Output/Reporter.cs @@ -405,18 +405,25 @@ internal sealed class Reporter : IDisposable } /// <summary> - /// What an error code means, for the formats other than rich-stdio (which <c>tazel explain</c> draws itself): the - /// first sentence and the right text, or with <paramref name="full"/> all of it and the other codes of its file. + /// What an error code means, for the formats other than rich-stdio (which <c>tazel explain</c> draws itself): + /// short is code, title and where; medium adds the first sentence and right text; long adds everything and related codes. /// </summary> - public void Explanation(ErrorCode entry, bool full, IReadOnlyList<string> related) + public void Explanation(ErrorCode entry, Cli.HelpLength length, IReadOnlyList<string> related) { ArgumentNullException.ThrowIfNull(entry); var first = entry.Explanation.IndexOf(". ", StringComparison.Ordinal); + var text = length switch + { + Cli.HelpLength.Short => null, + Cli.HelpLength.Long => entry.Explanation, + _ => first < 0 ? entry.Explanation : entry.Explanation[..(first + 1)], + }; Send(new Message("explanation", new Field("code", entry.Code), new Field("title", entry.Title), new Field("where", entry.Where), - new Field("text", full || first < 0 ? entry.Explanation : entry.Explanation[..(first + 1)]), - new Field("wrong", full ? entry.Wrong : null), new Field("right", entry.Right), - new Field("related", full && related.Count > 0 ? related : null))); + new Field("text", text), + new Field("wrong", length == Cli.HelpLength.Long ? entry.Wrong : null), + new Field("right", length == Cli.HelpLength.Short ? null : entry.Right), + new Field("related", length == Cli.HelpLength.Long && related.Count > 0 ? related : null))); } private static string StatusName(TestStatus status) => status switch diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index 36208da..2fedcf6 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -126,7 +126,7 @@ internal static class Program /// </summary> private static void ApplyDotnetSettings(Command command, string directory) { - if (command is HelpCommand or ExplainCommand or VersionCommand or LicenseCommand or DotnetWhatIsCommand) + if (command is HelpCommand or ExplainCommand or VersionCommand or LicenseCommand or ShellCompletionCommand or DotnetWhatIsCommand) { return; } diff --git a/tests/Progmasoft.Tazel.Tests/ShellCompletionAndExplainTests.cs b/tests/Progmasoft.Tazel.Tests/ShellCompletionAndExplainTests.cs new file mode 100644 index 0000000..e9e92d3 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/ShellCompletionAndExplainTests.cs @@ -0,0 +1,166 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Text.Json; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class ShellCompletionAndExplainTests +{ + [Fact] + public void ExplainSupportsShortMediumLongAndRejectsConflict() + { + var medium = Assert.IsType<ExplainCommand>(CommandLine.Parse(["explain", "E0406"])); + Assert.Equal("E0406", medium.Code); + Assert.Equal(HelpLength.Medium, medium.Length); + Assert.False(medium.Long); + + var @short = Assert.IsType<ExplainCommand>(CommandLine.Parse(["explain", "e0406", "--short"])); + Assert.Equal("E0406", @short.Code); + Assert.Equal(HelpLength.Short, @short.Length); + Assert.False(@short.Long); + + var @long = Assert.IsType<ExplainCommand>(CommandLine.Parse(["explain", "E0406", "--long"])); + Assert.Equal(HelpLength.Long, @long.Length); + Assert.True(@long.Long); + + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["explain", "E0406", "--short", "--long"])); + } + + [Fact] + public async Task ExplainShortMediumLongRenderDistinctLengthsInRichAndJsonl() + { + var dir = Path.Combine(Path.GetTempPath(), "tazel-explain-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + var shortRich = await RunAsync(["--color", "never", "explain", "E0406", "--short"], dir); + var mediumRich = await RunAsync(["--color", "never", "explain", "E0406"], dir); + var longRich = await RunAsync(["--color", "never", "explain", "E0406", "--long"], dir); + + Assert.Contains("E0406", shortRich, StringComparison.Ordinal); + Assert.DoesNotContain("More: tazel explain E0406 --long", shortRich, StringComparison.Ordinal); + Assert.True(shortRich.Length < mediumRich.Length); + Assert.True(mediumRich.Length < longRich.Length); + + var shortJsonl = await RunAsync(["--message-format", "jsonl", "explain", "E0406", "--short"], dir); + using var shortDoc = JsonDocument.Parse(shortJsonl.Trim()); + Assert.Equal("E0406", shortDoc.RootElement.GetProperty("code").GetString()); + Assert.True(shortDoc.RootElement.TryGetProperty("title", out _)); + Assert.False(shortDoc.RootElement.TryGetProperty("text", out _)); + Assert.False(shortDoc.RootElement.TryGetProperty("right", out _)); + Assert.False(shortDoc.RootElement.TryGetProperty("wrong", out _)); + + var mediumJsonl = await RunAsync(["--message-format", "jsonl", "explain", "E0406"], dir); + using var mediumDoc = JsonDocument.Parse(mediumJsonl.Trim()); + Assert.True(mediumDoc.RootElement.TryGetProperty("text", out _)); + Assert.False(mediumDoc.RootElement.TryGetProperty("wrong", out _)); + + var longJsonl = await RunAsync(["--message-format", "jsonl", "explain", "E0406", "--long"], dir); + using var longDoc = JsonDocument.Parse(longJsonl.Trim()); + Assert.True(longDoc.RootElement.TryGetProperty("wrong", out _)); + Assert.True(longDoc.RootElement.TryGetProperty("related", out _)); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Theory] + [InlineData("bash", "Bash")] + [InlineData("zsh", "Zsh")] + [InlineData("fish", "Fish")] + [InlineData("powershell", "PowerShell")] + public void ShellCompletionParsesSupportedShells(string arg, string expectedName) + { + var command = Assert.IsType<ShellCompletionCommand>(CommandLine.Parse(["shell-completion", arg])); + Assert.Equal(Enum.Parse<ShellKind>(expectedName), command.Shell); + } + + [Fact] + public void ShellCompletionRejectsMissingExtraAndUnknownShellsWithHints() + { + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["shell-completion"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["shell-completion", "zsh", "bash"])); + + var pwshError = Assert.Throws<CommandLineException>(() => CommandLine.Parse(["shell-completion", "pwsh"])); + Assert.Contains("did you mean powershell?", pwshError.Message, StringComparison.Ordinal); + + var typoError = Assert.Throws<CommandLineException>(() => CommandLine.Parse(["shell-completion", "zhs"])); + Assert.Contains("did you mean zsh?", typoError.Message, StringComparison.Ordinal); + + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["shell-completion", "ZSH"])); + } + + [Theory] + [InlineData("Bash")] + [InlineData("Zsh")] + [InlineData("Fish")] + [InlineData("PowerShell")] + public void EveryShellScriptIncludesAllCommands(string shellName) + { + var script = ShellCompletion.Generate(Enum.Parse<ShellKind>(shellName)); + foreach (var cmd in CommandLine.Commands) + { + Assert.Contains(cmd, script, StringComparison.Ordinal); + } + } + + [Fact] + public void ZshScriptSupportsDirectSourceAndCompdef() + { + var script = ShellCompletion.Generate(ShellKind.Zsh); + Assert.StartsWith("#compdef tazel", script, StringComparison.Ordinal); + Assert.Contains("source <(tazel shell-completion zsh)", script, StringComparison.Ordinal); + Assert.Contains("compdef _tazel tazel", script, StringComparison.Ordinal); + } + + [Fact] + public void PowerShellScriptIsCompatibleWithPowerShell51() + { + var script = ShellCompletion.Generate(ShellKind.PowerShell); + Assert.Contains("PowerShell 5.1", script, StringComparison.Ordinal); + Assert.Contains("Register-ArgumentCompleter -Native -CommandName 'tazel'", script, StringComparison.Ordinal); + Assert.Contains("[System.Management.Automation.CompletionResult]::new", script, StringComparison.Ordinal); + + // Guard against PowerShell 7-only operators/parameters. + Assert.DoesNotContain("??", script, StringComparison.Ordinal); + Assert.DoesNotContain("&&", script, StringComparison.Ordinal); + Assert.DoesNotContain("||", script, StringComparison.Ordinal); + Assert.DoesNotContain("-AsHashtable", script, StringComparison.Ordinal); + } + + [Fact] + public async Task ShellCompletionRunsWithoutWorkspace() + { + var dir = Path.Combine(Path.GetTempPath(), "tazel-completion-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + var zsh = await RunAsync(["--color", "never", "shell-completion", "zsh"], dir); + Assert.Contains("#compdef tazel", zsh, StringComparison.Ordinal); + Assert.Contains("compdef _tazel tazel", zsh, StringComparison.Ordinal); + + var ps = await RunAsync(["--color", "never", "shell-completion", "powershell"], dir); + Assert.Contains("Register-ArgumentCompleter", ps, StringComparison.Ordinal); + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + private static async Task<string> RunAsync(string[] args, string directory) + { + using var output = new StringWriter(); + var status = await Program.RunAsync(args, directory, output, TestContext.Current.CancellationToken); + Assert.Equal(0, status); + return output.ToString(); + } +}