diff --git a/src/System.CommandLine.ApiCompatibility.Tests/ApiCompatibilityApprovalTests.System_CommandLine_api_is_not_changed.approved.txt b/src/System.CommandLine.ApiCompatibility.Tests/ApiCompatibilityApprovalTests.System_CommandLine_api_is_not_changed.approved.txt index 46238e35f8..26cf6ad038 100644 --- a/src/System.CommandLine.ApiCompatibility.Tests/ApiCompatibilityApprovalTests.System_CommandLine_api_is_not_changed.approved.txt +++ b/src/System.CommandLine.ApiCompatibility.Tests/ApiCompatibilityApprovalTests.System_CommandLine_api_is_not_changed.approved.txt @@ -83,8 +83,8 @@ System.CommandLine public static CommandLineBuilder UseHelp(this CommandLineBuilder builder, System.Action customize, System.Nullable maxWidth = null) public static TBuilder UseHelpBuilder(this TBuilder builder, System.Func getHelpBuilder) public static CommandLineBuilder UseLocalizationResources(this CommandLineBuilder builder, LocalizationResources validationMessages) - public static CommandLineBuilder UseParseDirective(this CommandLineBuilder builder, System.Nullable errorExitCode = null) - public static CommandLineBuilder UseParseErrorReporting(this CommandLineBuilder builder, System.Nullable errorExitCode = null) + public static CommandLineBuilder UseParseDirective(this CommandLineBuilder builder, System.Int32 errorExitCode = 1) + public static CommandLineBuilder UseParseErrorReporting(this CommandLineBuilder builder, System.Int32 errorExitCode = 1) public static CommandLineBuilder UseSuggestDirective(this CommandLineBuilder builder) public static CommandLineBuilder UseTokenReplacer(this CommandLineBuilder builder, System.CommandLine.Parsing.TryReplaceToken replaceToken) public static CommandLineBuilder UseTypoCorrections(this CommandLineBuilder builder, System.Int32 maxLevenshteinDistance = 3) diff --git a/src/System.CommandLine.Hosting.Tests/HostingHandlerTest.cs b/src/System.CommandLine.Hosting.Tests/HostingHandlerTest.cs index c874ff5fb7..efe928533c 100644 --- a/src/System.CommandLine.Hosting.Tests/HostingHandlerTest.cs +++ b/src/System.CommandLine.Hosting.Tests/HostingHandlerTest.cs @@ -55,7 +55,7 @@ public static async Task Parameter_is_available_in_property() } [Fact] - public static async Task Can_have_diferent_handlers_based_on_command() + public static async Task Can_have_different_handlers_based_on_command() { var root = new RootCommand(); diff --git a/src/System.CommandLine.Tests/ParseDirectiveTests.cs b/src/System.CommandLine.Tests/ParseDirectiveTests.cs index 666d9bc468..d66b879cb0 100644 --- a/src/System.CommandLine.Tests/ParseDirectiveTests.cs +++ b/src/System.CommandLine.Tests/ParseDirectiveTests.cs @@ -46,6 +46,56 @@ public async Task Parse_directive_writes_parse_diagram() .Be($"![ {RootCommand.ExecutableName} [ subcommand [ -c <34> ] ] ] ???--> --nonexistent wat" + Environment.NewLine); } + [Fact] + public async Task When_parse_directive_is_used_the_help_is_not_displayed() + { + var rootCommand = new RootCommand(); + + var parser = new CommandLineBuilder(rootCommand) + .UseParseDirective() + .UseVersionOption() + .UseHelp() + .Build(); + + var result = parser.Parse("[parse] --help"); + + output.WriteLine(result.Diagram()); + + var console = new TestConsole(); + + await result.InvokeAsync(console); + + console.Out + .ToString() + .Should() + .Be($"[ {RootCommand.ExecutableName} [ --help ] ]" + Environment.NewLine); + } + + [Fact] + public async Task When_parse_directive_is_used_the_version_is_not_displayed() + { + var rootCommand = new RootCommand(); + + var parser = new CommandLineBuilder(rootCommand) + .UseParseDirective() + .UseVersionOption() + .UseHelp() + .Build(); + + var result = parser.Parse("[parse] --version"); + + output.WriteLine(result.Diagram()); + + var console = new TestConsole(); + + await result.InvokeAsync(console); + + console.Out + .ToString() + .Should() + .Be($"[ {RootCommand.ExecutableName} [ --version ] ]" + Environment.NewLine); + } + [Fact] public async Task When_there_are_no_errors_then_parse_directive_sets_exit_code_0() { diff --git a/src/System.CommandLine/Builder/CommandLineBuilder.cs b/src/System.CommandLine/Builder/CommandLineBuilder.cs index 547419f88d..956663acc4 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilder.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilder.cs @@ -14,6 +14,33 @@ namespace System.CommandLine /// public class CommandLineBuilder { + /// + internal bool EnablePosixBundling = true; + + /// + internal bool EnableTokenReplacement = true; + + /// + internal int? ParseErrorReportingExitCode; + + /// + internal bool EnableDirectives = true; + + /// + internal bool EnableEnvironmentVariableDirective; + + /// + internal int? ParseDirectiveExitCode; + + /// + internal bool EnableSuggestDirective; + + /// + internal int MaxLevenshteinDistance; + + /// + internal Action? ExceptionHandler; + // for every generic type with type argument being struct JIT needs to compile a dedicated version // (because each struct is of a different size) // that is why we don't use List for middleware @@ -33,19 +60,6 @@ public CommandLineBuilder(Command? rootCommand = null) /// public Command Command { get; } - /// - /// Determines whether the parser recognizes command line directives. - /// - /// - internal bool EnableDirectives { get; set; } = true; - - /// - /// Determines whether the parser recognize and expands POSIX-style bundled options. - /// - internal bool EnablePosixBundling { get; set; } = true; - - internal bool EnableTokenReplacement { get; set; } = true; - internal void CustomizeHelpLayout(Action customize) => _customizeHelpBuilder = customize; @@ -68,11 +82,11 @@ HelpBuilder CreateHelpBuilder(BindingContext bindingContext) } } - internal HelpOption? HelpOption { get; set; } + internal HelpOption? HelpOption; - internal VersionOption? VersionOption { get; set; } + internal VersionOption? VersionOption; - internal int? MaxHelpWidth { get; set; } + internal int? MaxHelpWidth; internal LocalizationResources LocalizationResources { @@ -80,7 +94,7 @@ internal LocalizationResources LocalizationResources set => _localizationResources = value; } - internal TryReplaceToken? TokenReplacer { get; set; } + internal TryReplaceToken? TokenReplacer; /// /// Creates a parser based on the configuration of the command line builder. @@ -92,6 +106,12 @@ public Parser Build() => enablePosixBundling: EnablePosixBundling, enableDirectives: EnableDirectives, enableTokenReplacement: EnableTokenReplacement, + enableEnvironmentVariableDirective: EnableEnvironmentVariableDirective, + parseDirectiveExitCode: ParseDirectiveExitCode, + enableSuggestDirective: EnableSuggestDirective, + parseErrorReportingExitCode: ParseErrorReportingExitCode, + maxLevenshteinDistance: MaxLevenshteinDistance, + exceptionHandler: ExceptionHandler, resources: LocalizationResources, middlewarePipeline: _middlewareList is null ? Array.Empty() diff --git a/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs b/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs index fe49e34d0d..3ee71b811d 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs @@ -8,7 +8,6 @@ using System.CommandLine.IO; using System.CommandLine.Parsing; using System.IO; -using System.Linq; using System.Threading; using System.Threading.Tasks; using static System.Environment; @@ -230,27 +229,7 @@ await feature.EnsureRegistered(async () => public static CommandLineBuilder UseEnvironmentVariableDirective( this CommandLineBuilder builder) { - builder.AddMiddleware((context, next) => - { - if (context.ParseResult.Directives.TryGetValue("env", out var keyValuePairs)) - { - for (var i = 0; i < keyValuePairs.Count; i++) - { - var envDirective = keyValuePairs[i]; - var components = envDirective.Split(new[] { '=' }, count: 2); - var variable = components.Length > 0 ? components[0].Trim() : string.Empty; - if (string.IsNullOrEmpty(variable) || components.Length < 2) - { - continue; - } - - var value = components[1].Trim(); - SetEnvironmentVariable(variable, value); - } - } - - return next(context); - }, MiddlewareOrderInternal.EnvironmentVariableDirective); + builder.EnableEnvironmentVariableDirective = true; return builder; } @@ -302,17 +281,7 @@ public static CommandLineBuilder UseExceptionHandler( Action? onException = null, int? errorExitCode = null) { - builder.AddMiddleware(async (context, next) => - { - try - { - await next(context); - } - catch (Exception exception) - { - (onException ?? Default)(exception, context); - } - }, MiddlewareOrderInternal.ExceptionHandler); + builder.ExceptionHandler = onException ?? Default; return builder; @@ -397,14 +366,6 @@ internal static CommandLineBuilder UseHelp( builder.HelpOption = helpOption; builder.Command.AddGlobalOption(helpOption); builder.MaxHelpWidth = maxWidth; - - builder.AddMiddleware(async (context, next) => - { - if (!ShowHelp(context, builder.HelpOption)) - { - await next(context); - } - }, MiddlewareOrderInternal.HelpOption); } return builder; } @@ -475,19 +436,9 @@ public static CommandLineBuilder AddMiddleware( /// The same instance of . public static CommandLineBuilder UseParseDirective( this CommandLineBuilder builder, - int? errorExitCode = null) + int errorExitCode = 1) { - builder.AddMiddleware(async (context, next) => - { - if (context.ParseResult.Directives.ContainsKey("parse")) - { - context.InvocationResult = ctx => ParseDirectiveResult.Apply(ctx, errorExitCode); - } - else - { - await next(context); - } - }, MiddlewareOrderInternal.ParseDirective); + builder.ParseDirectiveExitCode = errorExitCode; return builder; } @@ -500,19 +451,9 @@ public static CommandLineBuilder UseParseDirective( /// The same instance of . public static CommandLineBuilder UseParseErrorReporting( this CommandLineBuilder builder, - int? errorExitCode = null) + int errorExitCode = 1) { - builder.AddMiddleware(async (context, next) => - { - if (context.ParseResult.Errors.Count > 0) - { - context.InvocationResult = ctx => ParseErrorResult.Apply(ctx, errorExitCode); - } - else - { - await next(context); - } - }, MiddlewareOrderInternal.ParseErrorReporting); + builder.ParseErrorReportingExitCode = errorExitCode; return builder; } @@ -526,28 +467,7 @@ public static CommandLineBuilder UseParseErrorReporting( public static CommandLineBuilder UseSuggestDirective( this CommandLineBuilder builder) { - builder.AddMiddleware(async (context, next) => - { - if (context.ParseResult.Directives.TryGetValue("suggest", out var values)) - { - int position; - - if (values.FirstOrDefault() is { } positionString) - { - position = int.Parse(positionString); - } - else - { - position = context.ParseResult.CommandLineText?.Length ?? 0; - } - - context.InvocationResult = ctx => SuggestDirectiveResult.Apply(ctx, position); - } - else - { - await next(context); - } - }, MiddlewareOrderInternal.SuggestDirective); + builder.EnableSuggestDirective = true; return builder; } @@ -562,17 +482,12 @@ public static CommandLineBuilder UseTypoCorrections( this CommandLineBuilder builder, int maxLevenshteinDistance = 3) { - builder.AddMiddleware(async (context, next) => + if (maxLevenshteinDistance <= 0) { - if (context.ParseResult.CommandResult.Command.TreatUnmatchedTokensAsErrors && - context.ParseResult.UnmatchedTokens.Count > 0) - { - var typoCorrection = new TypoCorrection(maxLevenshteinDistance); + throw new ArgumentOutOfRangeException(nameof(maxLevenshteinDistance)); + } - typoCorrection.ProvideSuggestions(context.ParseResult, context.Console); - } - await next(context); - }, MiddlewareOrderInternal.TypoCorrection); + builder.MaxLevenshteinDistance = maxLevenshteinDistance; return builder; } @@ -619,10 +534,8 @@ public static CommandLineBuilder UseVersionOption( return builder; } - var versionOption = new VersionOption(builder); - - builder.VersionOption = versionOption; - builder.Command.Options.Add(versionOption); + builder.VersionOption = new (builder); + builder.Command.Options.Add(builder.VersionOption); return builder; } @@ -634,32 +547,15 @@ public static CommandLineBuilder UseVersionOption( this CommandLineBuilder builder, params string[] aliases) { - var command = builder.Command; - if (builder.VersionOption is not null) { return builder; } - var versionOption = new VersionOption(aliases, builder); - - builder.VersionOption = versionOption; - command.Options.Add(versionOption); + builder.VersionOption = new (aliases, builder); + builder.Command.Options.Add(builder.VersionOption); return builder; } - - private static bool ShowHelp( - InvocationContext context, - Option helpOption) - { - if (context.ParseResult.FindResultFor(helpOption) is { }) - { - context.InvocationResult = HelpResult.Apply; - return true; - } - - return false; - } } } diff --git a/src/System.CommandLine/CommandLineConfiguration.cs b/src/System.CommandLine/CommandLineConfiguration.cs index 44672ea41b..da668dee3c 100644 --- a/src/System.CommandLine/CommandLineConfiguration.cs +++ b/src/System.CommandLine/CommandLineConfiguration.cs @@ -16,6 +16,39 @@ namespace System.CommandLine /// public class CommandLineConfiguration { + /// + /// A delegate that will be called when an exception is thrown by a command handler. + /// + internal readonly Action? ExceptionHandler; + + /// + /// Enables the use of the [env:key=value] directive, allowing environment variables to be set from the command line during invocation. + /// + internal readonly bool EnableEnvironmentVariableDirective; + + /// + /// If the parse result contains errors, this exit code will be used when the process exits. + /// + internal readonly int? ParseDirectiveExitCode; + + /// + /// Enables the use of the [suggest] directive which when specified in command line input short circuits normal command handling and writes a newline-delimited list of suggestions suitable for use by most shells to provide command line completions. + /// + /// The dotnet-suggest tool requires the suggest directive to be enabled for an application to provide completions. + internal readonly bool EnableSuggestDirective; + + /// + /// The exit code to use when parser errors occur. + /// + internal readonly int? ParseErrorReportingExitCode; + + /// + /// The maximum Levenshtein distance for suggestions based on detected typos in command line input. + /// + internal readonly int MaxLevenshteinDistance; + + internal readonly IReadOnlyList Middleware; + private Func? _helpBuilderFactory; private TryReplaceToken? _tokenReplacer; @@ -39,17 +72,42 @@ public CommandLineConfiguration( IReadOnlyList? middlewarePipeline = null, Func? helpBuilderFactory = null, TryReplaceToken? tokenReplacer = null) + : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, null, false, null, 0, + resources, middlewarePipeline, helpBuilderFactory, tokenReplacer, null) + { + } + + internal CommandLineConfiguration( + Command command, + bool enablePosixBundling, + bool enableDirectives, + bool enableTokenReplacement, + bool enableEnvironmentVariableDirective, + int? parseDirectiveExitCode, + bool enableSuggestDirective, + int? parseErrorReportingExitCode, + int maxLevenshteinDistance, + LocalizationResources? resources, + IReadOnlyList? middlewarePipeline, + Func? helpBuilderFactory, + TryReplaceToken? tokenReplacer, + Action? exceptionHandler) { RootCommand = command ?? throw new ArgumentNullException(nameof(command)); EnableTokenReplacement = enableTokenReplacement; EnablePosixBundling = enablePosixBundling; - EnableDirectives = enableDirectives; - + EnableDirectives = enableDirectives || enableEnvironmentVariableDirective || parseDirectiveExitCode.HasValue || enableSuggestDirective; + EnableEnvironmentVariableDirective = enableEnvironmentVariableDirective; + ParseDirectiveExitCode = parseDirectiveExitCode; + EnableSuggestDirective = enableSuggestDirective; + ParseErrorReportingExitCode = parseErrorReportingExitCode; + MaxLevenshteinDistance = maxLevenshteinDistance; LocalizationResources = resources ?? LocalizationResources.Instance; Middleware = middlewarePipeline ?? Array.Empty(); _helpBuilderFactory = helpBuilderFactory; _tokenReplacer = tokenReplacer; + ExceptionHandler = exceptionHandler; } internal static HelpBuilder DefaultHelpBuilderFactory(BindingContext context, int? requestedMaxWidth = null) @@ -91,8 +149,6 @@ internal static HelpBuilder DefaultHelpBuilderFactory(BindingContext context, in internal Func HelpBuilderFactory => _helpBuilderFactory ??= context => DefaultHelpBuilderFactory(context); - internal IReadOnlyList Middleware { get; } - internal TryReplaceToken? TokenReplacer => EnableTokenReplacement ? _tokenReplacer ??= DefaultTokenReplacer diff --git a/src/System.CommandLine/Help/HelpOption.cs b/src/System.CommandLine/Help/HelpOption.cs index 616156cff1..654afd5647 100644 --- a/src/System.CommandLine/Help/HelpOption.cs +++ b/src/System.CommandLine/Help/HelpOption.cs @@ -1,6 +1,9 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.CommandLine.Invocation; +using System.CommandLine.IO; + namespace System.CommandLine.Help { internal class HelpOption : Option @@ -33,14 +36,22 @@ public override string? Description internal override bool IsGreedy => false; - public override bool Equals(object? obj) - { - return obj is HelpOption; - } + public override bool Equals(object? obj) => obj is HelpOption; - public override int GetHashCode() + public override int GetHashCode() => typeof(HelpOption).GetHashCode(); + + internal static void Handler(InvocationContext context) { - return typeof(HelpOption).GetHashCode(); + var output = context.Console.Out.CreateTextWriter(); + + var helpContext = new HelpContext(context.BindingContext.HelpBuilder, + context.ParseResult.CommandResult.Command, + output, + context.ParseResult); + + context.BindingContext + .HelpBuilder + .Write(helpContext); } } } \ No newline at end of file diff --git a/src/System.CommandLine/Help/HelpResult.cs b/src/System.CommandLine/Help/HelpResult.cs deleted file mode 100644 index 9055aec93e..0000000000 --- a/src/System.CommandLine/Help/HelpResult.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) .NET Foundation and contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.CommandLine.Invocation; -using System.CommandLine.IO; - -namespace System.CommandLine.Help -{ - internal static class HelpResult - { - internal static void Apply(InvocationContext context) - { - var output = context.Console.Out.CreateTextWriter(); - - var helpContext = new HelpContext(context.BindingContext.HelpBuilder, - context.ParseResult.CommandResult.Command, - output, - context.ParseResult); - - context.BindingContext - .HelpBuilder - .Write(helpContext); - } - } -} \ No newline at end of file diff --git a/src/System.CommandLine/Help/VersionOption.cs b/src/System.CommandLine/Help/VersionOption.cs index 8e65328ee8..04514a9b15 100644 --- a/src/System.CommandLine/Help/VersionOption.cs +++ b/src/System.CommandLine/Help/VersionOption.cs @@ -1,6 +1,8 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.CommandLine.Invocation; +using System.CommandLine.IO; using System.CommandLine.Parsing; using System.Linq; @@ -56,14 +58,11 @@ public override string? Description internal override bool IsGreedy => false; - public override bool Equals(object? obj) - { - return obj is VersionOption; - } + public override bool Equals(object? obj) => obj is VersionOption; - public override int GetHashCode() - { - return typeof(VersionOption).GetHashCode(); - } + public override int GetHashCode() => typeof(VersionOption).GetHashCode(); + + internal static void Handler(InvocationContext context) + => context.Console.Out.WriteLine(RootCommand.ExecutableVersion); } } \ No newline at end of file diff --git a/src/System.CommandLine/Invocation/InvocationPipeline.cs b/src/System.CommandLine/Invocation/InvocationPipeline.cs index a16b8a2832..0251cbb30b 100644 --- a/src/System.CommandLine/Invocation/InvocationPipeline.cs +++ b/src/System.CommandLine/Invocation/InvocationPipeline.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; -using System.CommandLine.Parsing; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -13,22 +12,27 @@ internal class InvocationPipeline { private readonly ParseResult _parseResult; - public InvocationPipeline(ParseResult parseResult) - { - _parseResult = parseResult ?? throw new ArgumentNullException(nameof(parseResult)); - } + internal InvocationPipeline(ParseResult parseResult) + => _parseResult = parseResult ?? throw new ArgumentNullException(nameof(parseResult)); - public Task InvokeAsync(IConsole? console = null, CancellationToken cancellationToken = default) + public async Task InvokeAsync(IConsole? console = null, CancellationToken cancellationToken = default) { var context = new InvocationContext(_parseResult, console, cancellationToken); - if (context.Parser.Configuration.Middleware.Count == 0 && - _parseResult.Handler is not null) + try { - return _parseResult.Handler.InvokeAsync(context); - } + if (context.Parser.Configuration.Middleware.Count == 0 && _parseResult.Handler is not null) + { + return await _parseResult.Handler.InvokeAsync(context); + } - return InvokeHandlerWithMiddleware(context); + return await InvokeHandlerWithMiddleware(context); + } + catch (Exception ex) when (context.Parser.Configuration.ExceptionHandler is not null) + { + context.Parser.Configuration.ExceptionHandler(ex, context); + return context.ExitCode; + } static async Task InvokeHandlerWithMiddleware(InvocationContext context) { @@ -44,13 +48,20 @@ public int Invoke(IConsole? console = null) { var context = new InvocationContext(_parseResult, console); - if (context.Parser.Configuration.Middleware.Count == 0 - && context.ParseResult.CommandResult.Command.Handler is ICommandHandler handler) + try { - return handler.Invoke(context); - } + if (context.Parser.Configuration.Middleware.Count == 0 && _parseResult.Handler is not null) + { + return _parseResult.Handler.Invoke(context); + } - return InvokeHandlerWithMiddleware(context); // kept in a separate method to avoid JITting + return InvokeHandlerWithMiddleware(context); // kept in a separate method to avoid JITting + } + catch (Exception ex) when (context.Parser.Configuration.ExceptionHandler is not null) + { + context.Parser.Configuration.ExceptionHandler(ex, context); + return context.ExitCode; + } static int InvokeHandlerWithMiddleware(InvocationContext context) { diff --git a/src/System.CommandLine/Invocation/MiddlewareOrder.cs b/src/System.CommandLine/Invocation/MiddlewareOrder.cs index 411d887ae7..419196a2b5 100644 --- a/src/System.CommandLine/Invocation/MiddlewareOrder.cs +++ b/src/System.CommandLine/Invocation/MiddlewareOrder.cs @@ -32,16 +32,6 @@ public enum MiddlewareOrder internal enum MiddlewareOrderInternal { Startup = -4000, - ExceptionHandler = -3000, - EnvironmentVariableDirective = -2600, - ConfigureConsole = -2500, RegisterWithDotnetSuggest = -2400, - DebugDirective = -2300, - ParseDirective = -2200, - SuggestDirective = -2000, - TypoCorrection = -1900, - VersionOption = -1200, - HelpOption = -1100, - ParseErrorReporting = 1000, } } \ No newline at end of file diff --git a/src/System.CommandLine/Invocation/ParseDirectiveResult.cs b/src/System.CommandLine/Invocation/ParseDirectiveResult.cs index 3d80dda706..0f212d6812 100644 --- a/src/System.CommandLine/Invocation/ParseDirectiveResult.cs +++ b/src/System.CommandLine/Invocation/ParseDirectiveResult.cs @@ -8,13 +8,13 @@ namespace System.CommandLine.Invocation { internal static class ParseDirectiveResult { - internal static void Apply(InvocationContext context, int? errorExitCode) + internal static void Apply(InvocationContext context) { var parseResult = context.ParseResult; context.Console.Out.WriteLine(parseResult.Diagram()); context.ExitCode = parseResult.Errors.Count == 0 ? 0 - : errorExitCode ?? 1; + : context.Parser.Configuration.ParseDirectiveExitCode!.Value; } } } diff --git a/src/System.CommandLine/Invocation/ParseErrorResult.cs b/src/System.CommandLine/Invocation/ParseErrorResult.cs index e67d70ee67..30432ddaad 100644 --- a/src/System.CommandLine/Invocation/ParseErrorResult.cs +++ b/src/System.CommandLine/Invocation/ParseErrorResult.cs @@ -8,7 +8,7 @@ namespace System.CommandLine.Invocation { internal static class ParseErrorResult { - internal static void Apply(InvocationContext context, int? errorExitCode) + internal static void Apply(InvocationContext context) { context.Console.ResetTerminalForegroundColor(); context.Console.SetTerminalForegroundRed(); @@ -20,11 +20,11 @@ internal static void Apply(InvocationContext context, int? errorExitCode) context.Console.Error.WriteLine(); - context.ExitCode = errorExitCode ?? 1; + context.ExitCode = context.Parser.Configuration.ParseErrorReportingExitCode!.Value; context.Console.ResetTerminalForegroundColor(); - HelpResult.Apply(context); + HelpOption.Handler(context); } } } \ No newline at end of file diff --git a/src/System.CommandLine/Invocation/TypoCorrection.cs b/src/System.CommandLine/Invocation/TypoCorrection.cs index 3dead941da..bdc0937d92 100644 --- a/src/System.CommandLine/Invocation/TypoCorrection.cs +++ b/src/System.CommandLine/Invocation/TypoCorrection.cs @@ -7,29 +7,21 @@ namespace System.CommandLine.Invocation { - internal class TypoCorrection + internal static class TypoCorrection { - private readonly int _maxLevenshteinDistance; - - public TypoCorrection(int maxLevenshteinDistance) + internal static void ProvideSuggestions(InvocationContext context) { - if (maxLevenshteinDistance <= 0) - { - throw new ArgumentOutOfRangeException(nameof(maxLevenshteinDistance)); - } + ParseResult result = context.ParseResult; + IConsole console = context.Console; + int maxLevenshteinDistance = context.Parser.Configuration.MaxLevenshteinDistance; - _maxLevenshteinDistance = maxLevenshteinDistance; - } - - public void ProvideSuggestions(ParseResult result, IConsole console) - { var unmatchedTokens = result.UnmatchedTokens; for (var i = 0; i < unmatchedTokens.Count; i++) { var token = unmatchedTokens[i]; bool first = true; - foreach (string suggestion in GetPossibleTokens(result.CommandResult.Command, token)) + foreach (string suggestion in GetPossibleTokens(result.CommandResult.Command, token, maxLevenshteinDistance)) { if (first) { @@ -42,7 +34,7 @@ public void ProvideSuggestions(ParseResult result, IConsole console) } } - private IEnumerable GetPossibleTokens(Command targetSymbol, string token) + private static IEnumerable GetPossibleTokens(Command targetSymbol, string token, int maxLevenshteinDistance) { if (!targetSymbol.HasOptions && !targetSymbol.HasSubcommands) { @@ -64,7 +56,7 @@ private IEnumerable GetPossibleTokens(Command targetSymbol, string token int? bestDistance = null; return possibleMatches .Select(possibleMatch => (possibleMatch, distance:GetDistance(token, possibleMatch))) - .Where(tuple => tuple.distance <= _maxLevenshteinDistance) + .Where(tuple => tuple.distance <= maxLevenshteinDistance) .OrderBy(tuple => tuple.distance) .ThenByDescending(tuple => GetStartsWithDistance(token, tuple.possibleMatch)) .TakeWhile(tuple => @@ -153,7 +145,6 @@ private static int GetDistance(string first, string second) // Return the computed edit distance return rows[curRow][m]; - } } } diff --git a/src/System.CommandLine/ParseResult.cs b/src/System.CommandLine/ParseResult.cs index 08bd091071..9bab338295 100644 --- a/src/System.CommandLine/ParseResult.cs +++ b/src/System.CommandLine/ParseResult.cs @@ -29,12 +29,14 @@ internal ParseResult( List tokens, IReadOnlyList? unmatchedTokens, List? errors, - string? commandLineText = null) + string? commandLineText = null, + ICommandHandler? handler = null) { Parser = parser; _rootCommandResult = rootCommandResult; CommandResult = commandResult; _directives = directives; + _handler = handler; // skip the root command when populating Tokens property if (tokens.Count > 1) @@ -51,25 +53,7 @@ internal ParseResult( } CommandLineText = commandLineText; - - if (unmatchedTokens is null) - { - _unmatchedTokens = Array.Empty(); - } - else - { - _unmatchedTokens = unmatchedTokens; - - if (parser.Configuration.RootCommand.TreatUnmatchedTokensAsErrors) - { - for (var i = 0; i < _unmatchedTokens.Count; i++) - { - var token = _unmatchedTokens[i]; - (errors ??= new()).Add(new ParseError(parser.Configuration.LocalizationResources.UnrecognizedCommandOrArgument(token.Value), rootCommandResult)); - } - } - } - + _unmatchedTokens = unmatchedTokens is null ? Array.Empty() : unmatchedTokens; _errors = errors is not null ? errors : Array.Empty(); } diff --git a/src/System.CommandLine/Parsing/ArgumentResult.cs b/src/System.CommandLine/Parsing/ArgumentResult.cs index c77bacdecd..99e09e34f8 100644 --- a/src/System.CommandLine/Parsing/ArgumentResult.cs +++ b/src/System.CommandLine/Parsing/ArgumentResult.cs @@ -116,7 +116,7 @@ public void OnlyTake(int numberOfTokens) { Token unmatched = _tokens[numberOfTokens]; _tokens.RemoveAt(numberOfTokens); - SymbolResultTree.AddUnmatchedToken(unmatched); + SymbolResultTree.AddUnmatchedToken(unmatched, parent.Command.TreatUnmatchedTokensAsErrors ? parent : null); --tokensToPass; } } diff --git a/src/System.CommandLine/Parsing/ParseOperation.cs b/src/System.CommandLine/Parsing/ParseOperation.cs index caf62a54cf..00520d4a7e 100644 --- a/src/System.CommandLine/Parsing/ParseOperation.cs +++ b/src/System.CommandLine/Parsing/ParseOperation.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.CommandLine.Help; using System.CommandLine.Invocation; -using System.CommandLine.IO; namespace System.CommandLine.Parsing { @@ -19,8 +18,8 @@ internal sealed class ParseOperation private int _index; private Dictionary>? _directives; private CommandResult _innermostCommandResult; - private bool _isHelpRequested; - private bool _isVersionRequested; + private bool _isHelpRequested, _isParseRequested; + private ICommandHandler? _handler; public ParseOperation( List tokens, @@ -62,7 +61,20 @@ internal ParseResult Parse(Parser parser) Validate(); } - ParseResult parseResult = new ( + if (_handler is null) + { + if (_configuration.ParseErrorReportingExitCode.HasValue && _symbolResultTree.ErrorCount > 0) + { + _handler = new AnonymousCommandHandler(ParseErrorResult.Apply); + } + else if (_configuration.MaxLevenshteinDistance > 0 && _rootCommandResult.Command.TreatUnmatchedTokensAsErrors + && _symbolResultTree.UnmatchedTokens is not null) + { + _handler = new AnonymousCommandHandler(TypoCorrection.ProvideSuggestions); + } + } + + return new ( parser, _rootCommandResult, _innermostCommandResult, @@ -70,18 +82,8 @@ internal ParseResult Parse(Parser parser) _tokens, _symbolResultTree.UnmatchedTokens, _symbolResultTree.Errors, - _rawInput); - - if (_isVersionRequested) - { - // FIX: (GetResult) use the ActiveOption's handler - parseResult.Handler = new AnonymousCommandHandler(context => - { - context.Console.Out.WriteLine(RootCommand.ExecutableVersion); - }); - } - - return parseResult; + _rawInput, + _handler); } private void ParseSubcommand() @@ -187,13 +189,19 @@ private void ParseOption() if (!_symbolResultTree.TryGetValue(option, out SymbolResult? symbolResult)) { - if (option is HelpOption) + // parse directive has a precedence over --help and --version + if (!_isParseRequested) { - _isHelpRequested = true; - } - else if (option is VersionOption) - { - _isVersionRequested = true; + if (option is HelpOption) + { + _isHelpRequested = true; + + _handler = new AnonymousCommandHandler(HelpOption.Handler); + } + else if (option is VersionOption) + { + _handler = new AnonymousCommandHandler(VersionOption.Handler); + } } optionResult = new OptionResult( @@ -277,7 +285,12 @@ private void ParseDirectives() { while (More(out TokenType currentTokenType) && currentTokenType == TokenType.Directive) { - ParseDirective(); // kept in separate method to avoid JIT + if (_configuration.EnableDirectives) + { + ParseDirective(); // kept in separate method to avoid JIT + } + + Advance(); } void ParseDirective() @@ -304,7 +317,7 @@ void ParseDirective() ((List)values).Add(value); } - Advance(); + OnDirectiveParsed(key, value); } } @@ -315,7 +328,8 @@ private void AddCurrentTokenToUnmatched() return; } - _symbolResultTree.AddUnmatchedToken(CurrentToken); + _symbolResultTree.AddUnmatchedToken(CurrentToken, + _rootCommandResult.Command.TreatUnmatchedTokensAsErrors ? _rootCommandResult : null); } private void Validate() @@ -332,5 +346,35 @@ private void Validate() currentResult = currentResult.Parent as CommandResult; } } + + private void OnDirectiveParsed(string directiveKey, string? parsedValues) + { + if (_configuration.EnableEnvironmentVariableDirective && directiveKey == "env") + { + if (parsedValues is not null) + { + var components = parsedValues.Split(new[] { '=' }, count: 2); + var variable = components.Length > 0 ? components[0].Trim() : string.Empty; + if (string.IsNullOrEmpty(variable) || components.Length < 2) + { + return; + } + + var value = components[1].Trim(); + Environment.SetEnvironmentVariable(variable, value); + } + } + else if (_configuration.ParseDirectiveExitCode.HasValue && directiveKey == "parse") + { + _isParseRequested = true; + _handler = new AnonymousCommandHandler(ParseDirectiveResult.Apply); + } + else if (_configuration.EnableSuggestDirective && directiveKey == "suggest") + { + int position = parsedValues is not null ? int.Parse(parsedValues) : _rawInput?.Length ?? 0; + + _handler = new AnonymousCommandHandler(ctx => SuggestDirectiveResult.Apply(ctx, position)); + } + } } } \ No newline at end of file diff --git a/src/System.CommandLine/Parsing/SymbolResultTree.cs b/src/System.CommandLine/Parsing/SymbolResultTree.cs index d59935f020..9d152ec3e6 100644 --- a/src/System.CommandLine/Parsing/SymbolResultTree.cs +++ b/src/System.CommandLine/Parsing/SymbolResultTree.cs @@ -55,6 +55,14 @@ internal IEnumerable GetChildren(SymbolResult parent) internal void InsertFirstError(ParseError parseError) => (Errors ??= new()).Insert(0, parseError); - internal void AddUnmatchedToken(Token token) => (UnmatchedTokens ??= new()).Add(token); + internal void AddUnmatchedToken(Token token, CommandResult? commandResult) + { + (UnmatchedTokens ??= new()).Add(token); + + if (commandResult is not null) + { + AddError(new ParseError(LocalizationResources.UnrecognizedCommandOrArgument(token.Value), commandResult)); + } + } } }