From 98311ec88267b79d76941abb6093d1f69033a6dd Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Fri, 3 Feb 2023 08:06:38 +0100 Subject: [PATCH 01/10] move HelpOption out of middleware --- .../Builder/CommandLineBuilderExtensions.cs | 21 ------------------- .../Parsing/ParseOperation.cs | 6 +++++- 2 files changed, 5 insertions(+), 22 deletions(-) diff --git a/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs b/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs index fe49e34d0d..904c35773b 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs @@ -397,14 +397,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; } @@ -648,18 +640,5 @@ public static CommandLineBuilder UseVersionOption( 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/Parsing/ParseOperation.cs b/src/System.CommandLine/Parsing/ParseOperation.cs index caf62a54cf..edfd8125ee 100644 --- a/src/System.CommandLine/Parsing/ParseOperation.cs +++ b/src/System.CommandLine/Parsing/ParseOperation.cs @@ -75,11 +75,15 @@ internal ParseResult Parse(Parser parser) if (_isVersionRequested) { // FIX: (GetResult) use the ActiveOption's handler - parseResult.Handler = new AnonymousCommandHandler(context => + parseResult.Handler = new AnonymousCommandHandler(static context => { context.Console.Out.WriteLine(RootCommand.ExecutableVersion); }); } + else if (_isHelpRequested) + { + parseResult.Handler = new AnonymousCommandHandler(HelpResult.Apply); + } return parseResult; } From 4023a3158d7baa04c2ba880f80a4f4b71ccff38b Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Fri, 3 Feb 2023 08:23:47 +0100 Subject: [PATCH 02/10] move environment variable directive out of middleware --- .../Builder/CommandLineBuilder.cs | 6 +++++ .../Builder/CommandLineBuilderExtensions.cs | 22 +----------------- .../CommandLineConfiguration.cs | 20 ++++++++++++++++ .../Invocation/MiddlewareOrder.cs | 3 --- .../Parsing/ParseOperation.cs | 23 +++++++++++++++++++ 5 files changed, 50 insertions(+), 24 deletions(-) diff --git a/src/System.CommandLine/Builder/CommandLineBuilder.cs b/src/System.CommandLine/Builder/CommandLineBuilder.cs index 547419f88d..467d6947e3 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilder.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilder.cs @@ -39,6 +39,11 @@ public CommandLineBuilder(Command? rootCommand = null) /// internal bool EnableDirectives { get; set; } = true; + /// + /// Enables the use of the [env:key=value] directive, allowing environment variables to be set from the command line during invocation. + /// + internal bool EnableEnvironmentVariableDirective { get; set; } + /// /// Determines whether the parser recognize and expands POSIX-style bundled options. /// @@ -92,6 +97,7 @@ public Parser Build() => enablePosixBundling: EnablePosixBundling, enableDirectives: EnableDirectives, enableTokenReplacement: EnableTokenReplacement, + enableEnvironmentVariableDirective: EnableEnvironmentVariableDirective, 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 904c35773b..2bdbb92380 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs @@ -230,27 +230,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; } diff --git a/src/System.CommandLine/CommandLineConfiguration.cs b/src/System.CommandLine/CommandLineConfiguration.cs index 44672ea41b..64bf27c4d0 100644 --- a/src/System.CommandLine/CommandLineConfiguration.cs +++ b/src/System.CommandLine/CommandLineConfiguration.cs @@ -39,11 +39,26 @@ public CommandLineConfiguration( IReadOnlyList? middlewarePipeline = null, Func? helpBuilderFactory = null, TryReplaceToken? tokenReplacer = null) + : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, resources, middlewarePipeline, helpBuilderFactory, tokenReplacer) + { + } + + internal CommandLineConfiguration( + Command command, + bool enablePosixBundling, + bool enableDirectives, + bool enableTokenReplacement, + bool enableEnvironmentVariableDirective, + LocalizationResources? resources, + IReadOnlyList? middlewarePipeline, + Func? helpBuilderFactory, + TryReplaceToken? tokenReplacer) { RootCommand = command ?? throw new ArgumentNullException(nameof(command)); EnableTokenReplacement = enableTokenReplacement; EnablePosixBundling = enablePosixBundling; EnableDirectives = enableDirectives; + EnableEnvironmentVariableDirective = enableEnvironmentVariableDirective; LocalizationResources = resources ?? LocalizationResources.Instance; Middleware = middlewarePipeline ?? Array.Empty(); @@ -84,6 +99,11 @@ internal static HelpBuilder DefaultHelpBuilderFactory(BindingContext context, in /// public bool EnableTokenReplacement { get; } + /// + /// Enables the use of the [env:key=value] directive, allowing environment variables to be set from the command line during invocation. + /// + internal bool EnableEnvironmentVariableDirective { get; set; } + /// /// Gets the localizable resources. /// diff --git a/src/System.CommandLine/Invocation/MiddlewareOrder.cs b/src/System.CommandLine/Invocation/MiddlewareOrder.cs index 411d887ae7..58a33b5469 100644 --- a/src/System.CommandLine/Invocation/MiddlewareOrder.cs +++ b/src/System.CommandLine/Invocation/MiddlewareOrder.cs @@ -33,15 +33,12 @@ 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/Parsing/ParseOperation.cs b/src/System.CommandLine/Parsing/ParseOperation.cs index edfd8125ee..fa2e168511 100644 --- a/src/System.CommandLine/Parsing/ParseOperation.cs +++ b/src/System.CommandLine/Parsing/ParseOperation.cs @@ -306,6 +306,8 @@ void ParseDirective() if (value is not null) { ((List)values).Add(value); + + OnDirectiveParsed(key, value); } Advance(); @@ -336,5 +338,26 @@ private void Validate() currentResult = currentResult.Parent as CommandResult; } } + + private void OnDirectiveParsed(string directiveKey, string parsedValues) + { + if (!_configuration.EnableDirectives) + { + return; + } + + if (_configuration.EnableEnvironmentVariableDirective && directiveKey == "env") + { + 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); + } + } } } \ No newline at end of file From 24d2d334c0a660feec2816e5cdac6c6384943dbe Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Fri, 3 Feb 2023 08:38:10 +0100 Subject: [PATCH 03/10] move parse directive out of middleware --- .../Builder/CommandLineBuilder.cs | 8 ++++ .../Builder/CommandLineBuilderExtensions.cs | 13 +----- .../CommandLineConfiguration.cs | 20 +++++++-- .../Invocation/MiddlewareOrder.cs | 1 - .../Parsing/ParseOperation.cs | 44 ++++++++++++------- 5 files changed, 54 insertions(+), 32 deletions(-) diff --git a/src/System.CommandLine/Builder/CommandLineBuilder.cs b/src/System.CommandLine/Builder/CommandLineBuilder.cs index 467d6947e3..f74114f30b 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilder.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilder.cs @@ -44,6 +44,12 @@ public CommandLineBuilder(Command? rootCommand = null) /// internal bool EnableEnvironmentVariableDirective { get; set; } + /// + /// Enables the use of the [env:key=value] directive, allowing environment variables to be set from the command line during invocation. + /// + internal bool EnableParseDirective { get; set; } + internal int? ParseDirectiveExitCode { get; set; } + /// /// Determines whether the parser recognize and expands POSIX-style bundled options. /// @@ -98,6 +104,8 @@ public Parser Build() => enableDirectives: EnableDirectives, enableTokenReplacement: EnableTokenReplacement, enableEnvironmentVariableDirective: EnableEnvironmentVariableDirective, + enableParseDirective: EnableParseDirective, + parseDirectiveExitCode: ParseDirectiveExitCode, 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 2bdbb92380..6afb57cbb8 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs @@ -449,17 +449,8 @@ public static CommandLineBuilder UseParseDirective( this CommandLineBuilder builder, int? errorExitCode = null) { - 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.EnableParseDirective = true; + builder.ParseDirectiveExitCode = errorExitCode; return builder; } diff --git a/src/System.CommandLine/CommandLineConfiguration.cs b/src/System.CommandLine/CommandLineConfiguration.cs index 64bf27c4d0..5f6cfc70c1 100644 --- a/src/System.CommandLine/CommandLineConfiguration.cs +++ b/src/System.CommandLine/CommandLineConfiguration.cs @@ -39,7 +39,8 @@ public CommandLineConfiguration( IReadOnlyList? middlewarePipeline = null, Func? helpBuilderFactory = null, TryReplaceToken? tokenReplacer = null) - : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, resources, middlewarePipeline, helpBuilderFactory, tokenReplacer) + : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, false, null, + resources, middlewarePipeline, helpBuilderFactory, tokenReplacer) { } @@ -49,6 +50,8 @@ internal CommandLineConfiguration( bool enableDirectives, bool enableTokenReplacement, bool enableEnvironmentVariableDirective, + bool enableParseDirective, + int? parseDirectiveExitCode, LocalizationResources? resources, IReadOnlyList? middlewarePipeline, Func? helpBuilderFactory, @@ -57,9 +60,10 @@ internal CommandLineConfiguration( RootCommand = command ?? throw new ArgumentNullException(nameof(command)); EnableTokenReplacement = enableTokenReplacement; EnablePosixBundling = enablePosixBundling; - EnableDirectives = enableDirectives; + EnableDirectives = enableDirectives || enableEnvironmentVariableDirective || enableParseDirective; EnableEnvironmentVariableDirective = enableEnvironmentVariableDirective; - + EnableParseDirective = enableParseDirective; + ParseDirectiveExitCode = parseDirectiveExitCode; LocalizationResources = resources ?? LocalizationResources.Instance; Middleware = middlewarePipeline ?? Array.Empty(); @@ -104,6 +108,16 @@ internal static HelpBuilder DefaultHelpBuilderFactory(BindingContext context, in /// internal bool EnableEnvironmentVariableDirective { get; set; } + /// + /// Enables the use of the [parse] directive, which when specified on the command line will short circuit normal command handling and display a diagram explaining the parse result for the command line input. + /// + internal bool EnableParseDirective { get; } + + /// + /// If the parse result contains errors, this exit code will be used when the process exits. + /// + internal int? ParseDirectiveExitCode { get; } + /// /// Gets the localizable resources. /// diff --git a/src/System.CommandLine/Invocation/MiddlewareOrder.cs b/src/System.CommandLine/Invocation/MiddlewareOrder.cs index 58a33b5469..7176dcf0c7 100644 --- a/src/System.CommandLine/Invocation/MiddlewareOrder.cs +++ b/src/System.CommandLine/Invocation/MiddlewareOrder.cs @@ -36,7 +36,6 @@ internal enum MiddlewareOrderInternal ConfigureConsole = -2500, RegisterWithDotnetSuggest = -2400, DebugDirective = -2300, - ParseDirective = -2200, SuggestDirective = -2000, TypoCorrection = -1900, ParseErrorReporting = 1000, diff --git a/src/System.CommandLine/Parsing/ParseOperation.cs b/src/System.CommandLine/Parsing/ParseOperation.cs index fa2e168511..1e08ec17c8 100644 --- a/src/System.CommandLine/Parsing/ParseOperation.cs +++ b/src/System.CommandLine/Parsing/ParseOperation.cs @@ -21,6 +21,7 @@ internal sealed class ParseOperation private CommandResult _innermostCommandResult; private bool _isHelpRequested; private bool _isVersionRequested; + private ICommandHandler? _commandHandler; public ParseOperation( List tokens, @@ -84,6 +85,10 @@ internal ParseResult Parse(Parser parser) { parseResult.Handler = new AnonymousCommandHandler(HelpResult.Apply); } + else if (_commandHandler is not null) + { + parseResult.Handler = _commandHandler; + } return parseResult; } @@ -281,7 +286,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() @@ -306,11 +316,9 @@ void ParseDirective() if (value is not null) { ((List)values).Add(value); - - OnDirectiveParsed(key, value); } - Advance(); + OnDirectiveParsed(key, value); } } @@ -339,24 +347,26 @@ private void Validate() } } - private void OnDirectiveParsed(string directiveKey, string parsedValues) + private void OnDirectiveParsed(string directiveKey, string? parsedValues) { - if (!_configuration.EnableDirectives) - { - return; - } - if (_configuration.EnableEnvironmentVariableDirective && directiveKey == "env") { - var components = parsedValues.Split(new[] { '=' }, count: 2); - var variable = components.Length > 0 ? components[0].Trim() : string.Empty; - if (string.IsNullOrEmpty(variable) || components.Length < 2) + if (parsedValues is not null) { - return; - } + 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); + var value = components[1].Trim(); + Environment.SetEnvironmentVariable(variable, value); + } + } + else if (_configuration.EnableParseDirective && directiveKey == "parse") + { + _commandHandler = new AnonymousCommandHandler(ctx => ParseDirectiveResult.Apply(ctx, _configuration.ParseDirectiveExitCode)); } } } From bea86a22819c45fb6d4ed9f18e2255b96e14ca56 Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Fri, 3 Feb 2023 09:27:44 +0100 Subject: [PATCH 04/10] add a tests for combinding [perse] with --help and --version --- .../ParseDirectiveTests.cs | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) 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() { From e54d965b3bcbf7cfc4bfcc7f56c932e3224748a5 Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Fri, 3 Feb 2023 09:33:38 +0100 Subject: [PATCH 05/10] refactor --- .../Builder/CommandLineBuilder.cs | 14 ++--- src/System.CommandLine/Help/HelpOption.cs | 23 ++++++--- src/System.CommandLine/Help/HelpResult.cs | 25 --------- src/System.CommandLine/Help/VersionOption.cs | 15 +++--- .../Invocation/ParseErrorResult.cs | 2 +- src/System.CommandLine/ParseResult.cs | 4 +- .../Parsing/ParseOperation.cs | 51 +++++++------------ 7 files changed, 51 insertions(+), 83 deletions(-) delete mode 100644 src/System.CommandLine/Help/HelpResult.cs diff --git a/src/System.CommandLine/Builder/CommandLineBuilder.cs b/src/System.CommandLine/Builder/CommandLineBuilder.cs index f74114f30b..be77192c0b 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilder.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilder.cs @@ -33,26 +33,20 @@ public CommandLineBuilder(Command? rootCommand = null) /// public Command Command { get; } - /// - /// Determines whether the parser recognizes command line directives. - /// - /// + /// internal bool EnableDirectives { get; set; } = true; - /// - /// Enables the use of the [env:key=value] directive, allowing environment variables to be set from the command line during invocation. - /// + /// internal bool EnableEnvironmentVariableDirective { get; set; } - /// - /// Enables the use of the [env:key=value] directive, allowing environment variables to be set from the command line during invocation. - /// + /// internal bool EnableParseDirective { get; set; } internal int? ParseDirectiveExitCode { get; set; } /// /// Determines whether the parser recognize and expands POSIX-style bundled options. /// + /// internal bool EnablePosixBundling { get; set; } = true; internal bool EnableTokenReplacement { get; set; } = true; 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/ParseErrorResult.cs b/src/System.CommandLine/Invocation/ParseErrorResult.cs index e67d70ee67..b7d3163622 100644 --- a/src/System.CommandLine/Invocation/ParseErrorResult.cs +++ b/src/System.CommandLine/Invocation/ParseErrorResult.cs @@ -24,7 +24,7 @@ internal static void Apply(InvocationContext context, int? errorExitCode) context.Console.ResetTerminalForegroundColor(); - HelpResult.Apply(context); + HelpOption.Handler(context); } } } \ No newline at end of file diff --git a/src/System.CommandLine/ParseResult.cs b/src/System.CommandLine/ParseResult.cs index 08bd091071..48d047e809 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) diff --git a/src/System.CommandLine/Parsing/ParseOperation.cs b/src/System.CommandLine/Parsing/ParseOperation.cs index 1e08ec17c8..a135ba6c69 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,9 +18,8 @@ internal sealed class ParseOperation private int _index; private Dictionary>? _directives; private CommandResult _innermostCommandResult; - private bool _isHelpRequested; - private bool _isVersionRequested; - private ICommandHandler? _commandHandler; + private bool _isHelpRequested, _isParseRequested; + private ICommandHandler? _handler; public ParseOperation( List tokens, @@ -63,7 +61,7 @@ internal ParseResult Parse(Parser parser) Validate(); } - ParseResult parseResult = new ( + return new ( parser, _rootCommandResult, _innermostCommandResult, @@ -71,26 +69,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(static context => - { - context.Console.Out.WriteLine(RootCommand.ExecutableVersion); - }); - } - else if (_isHelpRequested) - { - parseResult.Handler = new AnonymousCommandHandler(HelpResult.Apply); - } - else if (_commandHandler is not null) - { - parseResult.Handler = _commandHandler; - } - - return parseResult; + _rawInput, + _handler); } private void ParseSubcommand() @@ -196,13 +176,19 @@ private void ParseOption() if (!_symbolResultTree.TryGetValue(option, out SymbolResult? symbolResult)) { - if (option is HelpOption) - { - _isHelpRequested = true; - } - else if (option is VersionOption) + // parse directive has a precedence over --help and --version + if (!_isParseRequested) { - _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( @@ -366,7 +352,8 @@ private void OnDirectiveParsed(string directiveKey, string? parsedValues) } else if (_configuration.EnableParseDirective && directiveKey == "parse") { - _commandHandler = new AnonymousCommandHandler(ctx => ParseDirectiveResult.Apply(ctx, _configuration.ParseDirectiveExitCode)); + _isParseRequested = true; + _handler = new AnonymousCommandHandler(ctx => ParseDirectiveResult.Apply(ctx, _configuration.ParseDirectiveExitCode)); } } } From 19be15bd690dfbd8729ce4d195510fad0c8fd6d8 Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Fri, 3 Feb 2023 09:50:19 +0100 Subject: [PATCH 06/10] move suggest directive out of middleware --- .../Builder/CommandLineBuilder.cs | 7 +++--- .../Builder/CommandLineBuilderExtensions.cs | 23 +------------------ .../CommandLineConfiguration.cs | 12 ++++++++-- .../Invocation/MiddlewareOrder.cs | 1 - .../Parsing/ParseOperation.cs | 6 +++++ 5 files changed, 21 insertions(+), 28 deletions(-) diff --git a/src/System.CommandLine/Builder/CommandLineBuilder.cs b/src/System.CommandLine/Builder/CommandLineBuilder.cs index be77192c0b..d640cac540 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilder.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilder.cs @@ -43,9 +43,9 @@ public CommandLineBuilder(Command? rootCommand = null) internal bool EnableParseDirective { get; set; } internal int? ParseDirectiveExitCode { get; set; } - /// - /// Determines whether the parser recognize and expands POSIX-style bundled options. - /// + /// + internal bool EnableSuggestDirective { get; set; } + /// internal bool EnablePosixBundling { get; set; } = true; @@ -100,6 +100,7 @@ public Parser Build() => enableEnvironmentVariableDirective: EnableEnvironmentVariableDirective, enableParseDirective: EnableParseDirective, parseDirectiveExitCode: ParseDirectiveExitCode, + enableSuggestDirective: EnableSuggestDirective, 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 6afb57cbb8..8b35761ee9 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs @@ -489,28 +489,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; } diff --git a/src/System.CommandLine/CommandLineConfiguration.cs b/src/System.CommandLine/CommandLineConfiguration.cs index 5f6cfc70c1..0df25367f0 100644 --- a/src/System.CommandLine/CommandLineConfiguration.cs +++ b/src/System.CommandLine/CommandLineConfiguration.cs @@ -39,7 +39,7 @@ public CommandLineConfiguration( IReadOnlyList? middlewarePipeline = null, Func? helpBuilderFactory = null, TryReplaceToken? tokenReplacer = null) - : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, false, null, + : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, false, null, false, resources, middlewarePipeline, helpBuilderFactory, tokenReplacer) { } @@ -52,6 +52,7 @@ internal CommandLineConfiguration( bool enableEnvironmentVariableDirective, bool enableParseDirective, int? parseDirectiveExitCode, + bool enableSuggestDirective, LocalizationResources? resources, IReadOnlyList? middlewarePipeline, Func? helpBuilderFactory, @@ -60,10 +61,11 @@ internal CommandLineConfiguration( RootCommand = command ?? throw new ArgumentNullException(nameof(command)); EnableTokenReplacement = enableTokenReplacement; EnablePosixBundling = enablePosixBundling; - EnableDirectives = enableDirectives || enableEnvironmentVariableDirective || enableParseDirective; + EnableDirectives = enableDirectives || enableEnvironmentVariableDirective || enableParseDirective || enableSuggestDirective; EnableEnvironmentVariableDirective = enableEnvironmentVariableDirective; EnableParseDirective = enableParseDirective; ParseDirectiveExitCode = parseDirectiveExitCode; + EnableSuggestDirective = enableSuggestDirective; LocalizationResources = resources ?? LocalizationResources.Instance; Middleware = middlewarePipeline ?? Array.Empty(); @@ -118,6 +120,12 @@ internal static HelpBuilder DefaultHelpBuilderFactory(BindingContext context, in /// internal int? ParseDirectiveExitCode { get; } + /// + /// 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 bool EnableSuggestDirective { get; } + /// /// Gets the localizable resources. /// diff --git a/src/System.CommandLine/Invocation/MiddlewareOrder.cs b/src/System.CommandLine/Invocation/MiddlewareOrder.cs index 7176dcf0c7..c29f958855 100644 --- a/src/System.CommandLine/Invocation/MiddlewareOrder.cs +++ b/src/System.CommandLine/Invocation/MiddlewareOrder.cs @@ -36,7 +36,6 @@ internal enum MiddlewareOrderInternal ConfigureConsole = -2500, RegisterWithDotnetSuggest = -2400, DebugDirective = -2300, - SuggestDirective = -2000, TypoCorrection = -1900, ParseErrorReporting = 1000, } diff --git a/src/System.CommandLine/Parsing/ParseOperation.cs b/src/System.CommandLine/Parsing/ParseOperation.cs index a135ba6c69..19f40eeb68 100644 --- a/src/System.CommandLine/Parsing/ParseOperation.cs +++ b/src/System.CommandLine/Parsing/ParseOperation.cs @@ -355,6 +355,12 @@ private void OnDirectiveParsed(string directiveKey, string? parsedValues) _isParseRequested = true; _handler = new AnonymousCommandHandler(ctx => ParseDirectiveResult.Apply(ctx, _configuration.ParseDirectiveExitCode)); } + 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 From 4053a9e9efbaf48348ddd9fdbd895b2f83d8d9f0 Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Fri, 3 Feb 2023 10:18:00 +0100 Subject: [PATCH 07/10] move parse error reporting out of middleware report parsing errors as soon as unmatched token is found --- .../HostingHandlerTest.cs | 2 +- .../Builder/CommandLineBuilder.cs | 7 +++++++ .../Builder/CommandLineBuilderExtensions.cs | 13 ++---------- .../CommandLineConfiguration.cs | 15 +++++++++++++- .../Invocation/MiddlewareOrder.cs | 1 - .../Invocation/ParseDirectiveResult.cs | 4 ++-- .../Invocation/ParseErrorResult.cs | 4 ++-- src/System.CommandLine/ParseResult.cs | 20 +------------------ .../Parsing/ArgumentResult.cs | 2 +- .../Parsing/ParseOperation.cs | 10 ++++++++-- .../Parsing/SymbolResultTree.cs | 10 +++++++++- 11 files changed, 47 insertions(+), 41 deletions(-) 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/Builder/CommandLineBuilder.cs b/src/System.CommandLine/Builder/CommandLineBuilder.cs index d640cac540..494e967259 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilder.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilder.cs @@ -46,6 +46,11 @@ public CommandLineBuilder(Command? rootCommand = null) /// internal bool EnableSuggestDirective { get; set; } + /// + internal bool EnableParseErrorReporting { get; set; } + /// + internal int? ParseErrorReportingExitCode { get; set; } + /// internal bool EnablePosixBundling { get; set; } = true; @@ -101,6 +106,8 @@ public Parser Build() => enableParseDirective: EnableParseDirective, parseDirectiveExitCode: ParseDirectiveExitCode, enableSuggestDirective: EnableSuggestDirective, + enableParseErrorReporting: EnableParseErrorReporting, + parseErrorReportingExitCode: ParseErrorReportingExitCode, 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 8b35761ee9..779f9f0bb5 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs @@ -465,17 +465,8 @@ public static CommandLineBuilder UseParseErrorReporting( this CommandLineBuilder builder, int? errorExitCode = null) { - 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.EnableParseErrorReporting = true; + builder.ParseErrorReportingExitCode = errorExitCode; return builder; } diff --git a/src/System.CommandLine/CommandLineConfiguration.cs b/src/System.CommandLine/CommandLineConfiguration.cs index 0df25367f0..cf47b98b41 100644 --- a/src/System.CommandLine/CommandLineConfiguration.cs +++ b/src/System.CommandLine/CommandLineConfiguration.cs @@ -39,7 +39,7 @@ public CommandLineConfiguration( IReadOnlyList? middlewarePipeline = null, Func? helpBuilderFactory = null, TryReplaceToken? tokenReplacer = null) - : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, false, null, false, + : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, false, null, false, false, null, resources, middlewarePipeline, helpBuilderFactory, tokenReplacer) { } @@ -53,6 +53,8 @@ internal CommandLineConfiguration( bool enableParseDirective, int? parseDirectiveExitCode, bool enableSuggestDirective, + bool enableParseErrorReporting, + int? parseErrorReportingExitCode, LocalizationResources? resources, IReadOnlyList? middlewarePipeline, Func? helpBuilderFactory, @@ -66,6 +68,8 @@ internal CommandLineConfiguration( EnableParseDirective = enableParseDirective; ParseDirectiveExitCode = parseDirectiveExitCode; EnableSuggestDirective = enableSuggestDirective; + EnableParseErrorReporting = enableParseErrorReporting; + ParseErrorReportingExitCode = parseErrorReportingExitCode; LocalizationResources = resources ?? LocalizationResources.Instance; Middleware = middlewarePipeline ?? Array.Empty(); @@ -126,6 +130,15 @@ internal static HelpBuilder DefaultHelpBuilderFactory(BindingContext context, in /// The dotnet-suggest tool requires the suggest directive to be enabled for an application to provide completions. internal bool EnableSuggestDirective { get; } + /// + /// Configures the command line to write error information to standard error when there are errors parsing command line input. + /// + internal bool EnableParseErrorReporting { get; } + /// + /// The exit code to use when parser errors occur. + /// + internal int? ParseErrorReportingExitCode { get; } + /// /// Gets the localizable resources. /// diff --git a/src/System.CommandLine/Invocation/MiddlewareOrder.cs b/src/System.CommandLine/Invocation/MiddlewareOrder.cs index c29f958855..7a5bf91967 100644 --- a/src/System.CommandLine/Invocation/MiddlewareOrder.cs +++ b/src/System.CommandLine/Invocation/MiddlewareOrder.cs @@ -37,6 +37,5 @@ internal enum MiddlewareOrderInternal RegisterWithDotnetSuggest = -2400, DebugDirective = -2300, TypoCorrection = -1900, - 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..020a012bec 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 ?? 1; } } } diff --git a/src/System.CommandLine/Invocation/ParseErrorResult.cs b/src/System.CommandLine/Invocation/ParseErrorResult.cs index b7d3163622..39bfc76413 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,7 +20,7 @@ internal static void Apply(InvocationContext context, int? errorExitCode) context.Console.Error.WriteLine(); - context.ExitCode = errorExitCode ?? 1; + context.ExitCode = context.Parser.Configuration.ParseErrorReportingExitCode ?? 1; context.Console.ResetTerminalForegroundColor(); diff --git a/src/System.CommandLine/ParseResult.cs b/src/System.CommandLine/ParseResult.cs index 48d047e809..9bab338295 100644 --- a/src/System.CommandLine/ParseResult.cs +++ b/src/System.CommandLine/ParseResult.cs @@ -53,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 19f40eeb68..af741c8105 100644 --- a/src/System.CommandLine/Parsing/ParseOperation.cs +++ b/src/System.CommandLine/Parsing/ParseOperation.cs @@ -61,6 +61,11 @@ internal ParseResult Parse(Parser parser) Validate(); } + if (_configuration.EnableParseErrorReporting && _handler is null && _symbolResultTree.ErrorCount > 0) + { + _handler = new AnonymousCommandHandler(ParseErrorResult.Apply); + } + return new ( parser, _rootCommandResult, @@ -315,7 +320,8 @@ private void AddCurrentTokenToUnmatched() return; } - _symbolResultTree.AddUnmatchedToken(CurrentToken); + _symbolResultTree.AddUnmatchedToken(CurrentToken, + _rootCommandResult.Command.TreatUnmatchedTokensAsErrors ? _rootCommandResult : null); } private void Validate() @@ -353,7 +359,7 @@ private void OnDirectiveParsed(string directiveKey, string? parsedValues) else if (_configuration.EnableParseDirective && directiveKey == "parse") { _isParseRequested = true; - _handler = new AnonymousCommandHandler(ctx => ParseDirectiveResult.Apply(ctx, _configuration.ParseDirectiveExitCode)); + _handler = new AnonymousCommandHandler(ParseDirectiveResult.Apply); } else if (_configuration.EnableSuggestDirective && directiveKey == "suggest") { 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)); + } + } } } From 846233d7ff91fe8a484a19f3f9d7496fa55c8d73 Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Fri, 3 Feb 2023 11:16:08 +0100 Subject: [PATCH 08/10] move typo corrections out of middleware make TypoCorrection a static class as all it needs is inside InvocationContext --- .../Builder/CommandLineBuilder.cs | 5 ++++ .../Builder/CommandLineBuilderExtensions.cs | 13 +++------- .../CommandLineConfiguration.cs | 10 +++++++- .../Invocation/MiddlewareOrder.cs | 1 - .../Invocation/TypoCorrection.cs | 25 ++++++------------- .../Parsing/ParseOperation.cs | 12 +++++++-- 6 files changed, 36 insertions(+), 30 deletions(-) diff --git a/src/System.CommandLine/Builder/CommandLineBuilder.cs b/src/System.CommandLine/Builder/CommandLineBuilder.cs index 494e967259..5658fabc02 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilder.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilder.cs @@ -48,9 +48,13 @@ public CommandLineBuilder(Command? rootCommand = null) /// internal bool EnableParseErrorReporting { get; set; } + /// internal int? ParseErrorReportingExitCode { get; set; } + /// + internal int MaxLevenshteinDistance { get; set; } + /// internal bool EnablePosixBundling { get; set; } = true; @@ -108,6 +112,7 @@ public Parser Build() => enableSuggestDirective: EnableSuggestDirective, enableParseErrorReporting: EnableParseErrorReporting, parseErrorReportingExitCode: ParseErrorReportingExitCode, + maxLevenshteinDistance: MaxLevenshteinDistance, 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 779f9f0bb5..6a57ddcb98 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs @@ -495,17 +495,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; } diff --git a/src/System.CommandLine/CommandLineConfiguration.cs b/src/System.CommandLine/CommandLineConfiguration.cs index cf47b98b41..67d97e87ed 100644 --- a/src/System.CommandLine/CommandLineConfiguration.cs +++ b/src/System.CommandLine/CommandLineConfiguration.cs @@ -39,7 +39,7 @@ public CommandLineConfiguration( IReadOnlyList? middlewarePipeline = null, Func? helpBuilderFactory = null, TryReplaceToken? tokenReplacer = null) - : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, false, null, false, false, null, + : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, false, null, false, false, null, 0, resources, middlewarePipeline, helpBuilderFactory, tokenReplacer) { } @@ -55,6 +55,7 @@ internal CommandLineConfiguration( bool enableSuggestDirective, bool enableParseErrorReporting, int? parseErrorReportingExitCode, + int maxLevenshteinDistance, LocalizationResources? resources, IReadOnlyList? middlewarePipeline, Func? helpBuilderFactory, @@ -70,6 +71,7 @@ internal CommandLineConfiguration( EnableSuggestDirective = enableSuggestDirective; EnableParseErrorReporting = enableParseErrorReporting; ParseErrorReportingExitCode = parseErrorReportingExitCode; + MaxLevenshteinDistance = maxLevenshteinDistance; LocalizationResources = resources ?? LocalizationResources.Instance; Middleware = middlewarePipeline ?? Array.Empty(); @@ -134,11 +136,17 @@ internal static HelpBuilder DefaultHelpBuilderFactory(BindingContext context, in /// Configures the command line to write error information to standard error when there are errors parsing command line input. /// internal bool EnableParseErrorReporting { get; } + /// /// The exit code to use when parser errors occur. /// internal int? ParseErrorReportingExitCode { get; } + /// + /// The maximum Levenshtein distance for suggestions based on detected typos in command line input. + /// + internal int MaxLevenshteinDistance { get; set; } + /// /// Gets the localizable resources. /// diff --git a/src/System.CommandLine/Invocation/MiddlewareOrder.cs b/src/System.CommandLine/Invocation/MiddlewareOrder.cs index 7a5bf91967..eedceda178 100644 --- a/src/System.CommandLine/Invocation/MiddlewareOrder.cs +++ b/src/System.CommandLine/Invocation/MiddlewareOrder.cs @@ -36,6 +36,5 @@ internal enum MiddlewareOrderInternal ConfigureConsole = -2500, RegisterWithDotnetSuggest = -2400, DebugDirective = -2300, - TypoCorrection = -1900, } } \ 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/Parsing/ParseOperation.cs b/src/System.CommandLine/Parsing/ParseOperation.cs index af741c8105..fcd3fa6098 100644 --- a/src/System.CommandLine/Parsing/ParseOperation.cs +++ b/src/System.CommandLine/Parsing/ParseOperation.cs @@ -61,9 +61,17 @@ internal ParseResult Parse(Parser parser) Validate(); } - if (_configuration.EnableParseErrorReporting && _handler is null && _symbolResultTree.ErrorCount > 0) + if (_handler is null) { - _handler = new AnonymousCommandHandler(ParseErrorResult.Apply); + if (_configuration.EnableParseErrorReporting && _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 ( From cbadeca1bf3e652e198023282ec5abf7a53ad2f7 Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Fri, 3 Feb 2023 11:46:43 +0100 Subject: [PATCH 09/10] move exception handling out of middleware --- .../Builder/CommandLineBuilder.cs | 4 ++ .../Builder/CommandLineBuilderExtensions.cs | 12 +----- .../CommandLineConfiguration.cs | 11 ++++- .../Invocation/InvocationPipeline.cs | 43 ++++++++++++------- .../Invocation/MiddlewareOrder.cs | 3 -- 5 files changed, 41 insertions(+), 32 deletions(-) diff --git a/src/System.CommandLine/Builder/CommandLineBuilder.cs b/src/System.CommandLine/Builder/CommandLineBuilder.cs index 5658fabc02..0a7d99a029 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilder.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilder.cs @@ -14,6 +14,9 @@ namespace System.CommandLine /// public class CommandLineBuilder { + /// + 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 @@ -113,6 +116,7 @@ public Parser Build() => enableParseErrorReporting: EnableParseErrorReporting, 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 6a57ddcb98..7d9b57e04a 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs @@ -282,17 +282,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; diff --git a/src/System.CommandLine/CommandLineConfiguration.cs b/src/System.CommandLine/CommandLineConfiguration.cs index 67d97e87ed..8d013c14dc 100644 --- a/src/System.CommandLine/CommandLineConfiguration.cs +++ b/src/System.CommandLine/CommandLineConfiguration.cs @@ -16,6 +16,11 @@ 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; + private Func? _helpBuilderFactory; private TryReplaceToken? _tokenReplacer; @@ -40,7 +45,7 @@ public CommandLineConfiguration( Func? helpBuilderFactory = null, TryReplaceToken? tokenReplacer = null) : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, false, null, false, false, null, 0, - resources, middlewarePipeline, helpBuilderFactory, tokenReplacer) + resources, middlewarePipeline, helpBuilderFactory, tokenReplacer, null) { } @@ -59,7 +64,8 @@ internal CommandLineConfiguration( LocalizationResources? resources, IReadOnlyList? middlewarePipeline, Func? helpBuilderFactory, - TryReplaceToken? tokenReplacer) + TryReplaceToken? tokenReplacer, + Action? exceptionHandler) { RootCommand = command ?? throw new ArgumentNullException(nameof(command)); EnableTokenReplacement = enableTokenReplacement; @@ -77,6 +83,7 @@ internal CommandLineConfiguration( _helpBuilderFactory = helpBuilderFactory; _tokenReplacer = tokenReplacer; + ExceptionHandler = exceptionHandler; } internal static HelpBuilder DefaultHelpBuilderFactory(BindingContext context, int? requestedMaxWidth = null) 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 eedceda178..419196a2b5 100644 --- a/src/System.CommandLine/Invocation/MiddlewareOrder.cs +++ b/src/System.CommandLine/Invocation/MiddlewareOrder.cs @@ -32,9 +32,6 @@ public enum MiddlewareOrder internal enum MiddlewareOrderInternal { Startup = -4000, - ExceptionHandler = -3000, - ConfigureConsole = -2500, RegisterWithDotnetSuggest = -2400, - DebugDirective = -2300, } } \ No newline at end of file From aadf6c9ee8e0acbcabaceb5d2a91fb357cbe1627 Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Fri, 3 Feb 2023 12:02:32 +0100 Subject: [PATCH 10/10] refactoring: * make internal properties fields to avoid method JITting * reduce the number of fields * provide defautl exit codes in explicit way --- ...ommandLine_api_is_not_changed.approved.txt | 4 +- .../Builder/CommandLineBuilder.cs | 61 +++++++-------- .../Builder/CommandLineBuilderExtensions.cs | 21 ++---- .../CommandLineConfiguration.cs | 74 ++++++++----------- .../Invocation/ParseDirectiveResult.cs | 2 +- .../Invocation/ParseErrorResult.cs | 2 +- .../Parsing/ParseOperation.cs | 4 +- 7 files changed, 70 insertions(+), 98 deletions(-) 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/Builder/CommandLineBuilder.cs b/src/System.CommandLine/Builder/CommandLineBuilder.cs index 0a7d99a029..956663acc4 100644 --- a/src/System.CommandLine/Builder/CommandLineBuilder.cs +++ b/src/System.CommandLine/Builder/CommandLineBuilder.cs @@ -14,6 +14,30 @@ 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; @@ -36,33 +60,6 @@ public CommandLineBuilder(Command? rootCommand = null) /// public Command Command { get; } - /// - internal bool EnableDirectives { get; set; } = true; - - /// - internal bool EnableEnvironmentVariableDirective { get; set; } - - /// - internal bool EnableParseDirective { get; set; } - internal int? ParseDirectiveExitCode { get; set; } - - /// - internal bool EnableSuggestDirective { get; set; } - - /// - internal bool EnableParseErrorReporting { get; set; } - - /// - internal int? ParseErrorReportingExitCode { get; set; } - - /// - internal int MaxLevenshteinDistance { get; set; } - - /// - internal bool EnablePosixBundling { get; set; } = true; - - internal bool EnableTokenReplacement { get; set; } = true; - internal void CustomizeHelpLayout(Action customize) => _customizeHelpBuilder = customize; @@ -85,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 { @@ -97,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. @@ -110,10 +107,8 @@ public Parser Build() => enableDirectives: EnableDirectives, enableTokenReplacement: EnableTokenReplacement, enableEnvironmentVariableDirective: EnableEnvironmentVariableDirective, - enableParseDirective: EnableParseDirective, parseDirectiveExitCode: ParseDirectiveExitCode, enableSuggestDirective: EnableSuggestDirective, - enableParseErrorReporting: EnableParseErrorReporting, parseErrorReportingExitCode: ParseErrorReportingExitCode, maxLevenshteinDistance: MaxLevenshteinDistance, exceptionHandler: ExceptionHandler, diff --git a/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs b/src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs index 7d9b57e04a..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; @@ -437,9 +436,8 @@ public static CommandLineBuilder AddMiddleware( /// The same instance of . public static CommandLineBuilder UseParseDirective( this CommandLineBuilder builder, - int? errorExitCode = null) + int errorExitCode = 1) { - builder.EnableParseDirective = true; builder.ParseDirectiveExitCode = errorExitCode; return builder; @@ -453,9 +451,8 @@ public static CommandLineBuilder UseParseDirective( /// The same instance of . public static CommandLineBuilder UseParseErrorReporting( this CommandLineBuilder builder, - int? errorExitCode = null) + int errorExitCode = 1) { - builder.EnableParseErrorReporting = true; builder.ParseErrorReportingExitCode = errorExitCode; return builder; @@ -537,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; } @@ -552,17 +547,13 @@ 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; } diff --git a/src/System.CommandLine/CommandLineConfiguration.cs b/src/System.CommandLine/CommandLineConfiguration.cs index 8d013c14dc..da668dee3c 100644 --- a/src/System.CommandLine/CommandLineConfiguration.cs +++ b/src/System.CommandLine/CommandLineConfiguration.cs @@ -21,6 +21,34 @@ public class CommandLineConfiguration /// 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; @@ -44,7 +72,7 @@ public CommandLineConfiguration( IReadOnlyList? middlewarePipeline = null, Func? helpBuilderFactory = null, TryReplaceToken? tokenReplacer = null) - : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, false, null, false, false, null, 0, + : this(command, enablePosixBundling, enableDirectives, enableTokenReplacement, false, null, false, null, 0, resources, middlewarePipeline, helpBuilderFactory, tokenReplacer, null) { } @@ -55,10 +83,8 @@ internal CommandLineConfiguration( bool enableDirectives, bool enableTokenReplacement, bool enableEnvironmentVariableDirective, - bool enableParseDirective, int? parseDirectiveExitCode, bool enableSuggestDirective, - bool enableParseErrorReporting, int? parseErrorReportingExitCode, int maxLevenshteinDistance, LocalizationResources? resources, @@ -70,12 +96,10 @@ internal CommandLineConfiguration( RootCommand = command ?? throw new ArgumentNullException(nameof(command)); EnableTokenReplacement = enableTokenReplacement; EnablePosixBundling = enablePosixBundling; - EnableDirectives = enableDirectives || enableEnvironmentVariableDirective || enableParseDirective || enableSuggestDirective; + EnableDirectives = enableDirectives || enableEnvironmentVariableDirective || parseDirectiveExitCode.HasValue || enableSuggestDirective; EnableEnvironmentVariableDirective = enableEnvironmentVariableDirective; - EnableParseDirective = enableParseDirective; ParseDirectiveExitCode = parseDirectiveExitCode; EnableSuggestDirective = enableSuggestDirective; - EnableParseErrorReporting = enableParseErrorReporting; ParseErrorReportingExitCode = parseErrorReportingExitCode; MaxLevenshteinDistance = maxLevenshteinDistance; LocalizationResources = resources ?? LocalizationResources.Instance; @@ -118,42 +142,6 @@ internal static HelpBuilder DefaultHelpBuilderFactory(BindingContext context, in /// public bool EnableTokenReplacement { get; } - /// - /// Enables the use of the [env:key=value] directive, allowing environment variables to be set from the command line during invocation. - /// - internal bool EnableEnvironmentVariableDirective { get; set; } - - /// - /// Enables the use of the [parse] directive, which when specified on the command line will short circuit normal command handling and display a diagram explaining the parse result for the command line input. - /// - internal bool EnableParseDirective { get; } - - /// - /// If the parse result contains errors, this exit code will be used when the process exits. - /// - internal int? ParseDirectiveExitCode { get; } - - /// - /// 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 bool EnableSuggestDirective { get; } - - /// - /// Configures the command line to write error information to standard error when there are errors parsing command line input. - /// - internal bool EnableParseErrorReporting { get; } - - /// - /// The exit code to use when parser errors occur. - /// - internal int? ParseErrorReportingExitCode { get; } - - /// - /// The maximum Levenshtein distance for suggestions based on detected typos in command line input. - /// - internal int MaxLevenshteinDistance { get; set; } - /// /// Gets the localizable resources. /// @@ -161,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/Invocation/ParseDirectiveResult.cs b/src/System.CommandLine/Invocation/ParseDirectiveResult.cs index 020a012bec..0f212d6812 100644 --- a/src/System.CommandLine/Invocation/ParseDirectiveResult.cs +++ b/src/System.CommandLine/Invocation/ParseDirectiveResult.cs @@ -14,7 +14,7 @@ internal static void Apply(InvocationContext context) context.Console.Out.WriteLine(parseResult.Diagram()); context.ExitCode = parseResult.Errors.Count == 0 ? 0 - : context.Parser.Configuration.ParseDirectiveExitCode ?? 1; + : context.Parser.Configuration.ParseDirectiveExitCode!.Value; } } } diff --git a/src/System.CommandLine/Invocation/ParseErrorResult.cs b/src/System.CommandLine/Invocation/ParseErrorResult.cs index 39bfc76413..30432ddaad 100644 --- a/src/System.CommandLine/Invocation/ParseErrorResult.cs +++ b/src/System.CommandLine/Invocation/ParseErrorResult.cs @@ -20,7 +20,7 @@ internal static void Apply(InvocationContext context) context.Console.Error.WriteLine(); - context.ExitCode = context.Parser.Configuration.ParseErrorReportingExitCode ?? 1; + context.ExitCode = context.Parser.Configuration.ParseErrorReportingExitCode!.Value; context.Console.ResetTerminalForegroundColor(); diff --git a/src/System.CommandLine/Parsing/ParseOperation.cs b/src/System.CommandLine/Parsing/ParseOperation.cs index fcd3fa6098..00520d4a7e 100644 --- a/src/System.CommandLine/Parsing/ParseOperation.cs +++ b/src/System.CommandLine/Parsing/ParseOperation.cs @@ -63,7 +63,7 @@ internal ParseResult Parse(Parser parser) if (_handler is null) { - if (_configuration.EnableParseErrorReporting && _symbolResultTree.ErrorCount > 0) + if (_configuration.ParseErrorReportingExitCode.HasValue && _symbolResultTree.ErrorCount > 0) { _handler = new AnonymousCommandHandler(ParseErrorResult.Apply); } @@ -364,7 +364,7 @@ private void OnDirectiveParsed(string directiveKey, string? parsedValues) Environment.SetEnvironmentVariable(variable, value); } } - else if (_configuration.EnableParseDirective && directiveKey == "parse") + else if (_configuration.ParseDirectiveExitCode.HasValue && directiveKey == "parse") { _isParseRequested = true; _handler = new AnonymousCommandHandler(ParseDirectiveResult.Apply);