From cf33856bed1ce663861fe0f97d5e073d1ba485c7 Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Tue, 6 Jun 2023 16:47:10 +0200 Subject: [PATCH 1/2] add a failing test --- .../UseParseErrorReportingTests.cs | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/System.CommandLine.Tests/UseParseErrorReportingTests.cs b/src/System.CommandLine.Tests/UseParseErrorReportingTests.cs index 77e6886e92..b75081609a 100644 --- a/src/System.CommandLine.Tests/UseParseErrorReportingTests.cs +++ b/src/System.CommandLine.Tests/UseParseErrorReportingTests.cs @@ -60,5 +60,46 @@ public void User_can_customize_parse_error_result_code() result.Should().Be(42); } + + [Fact] + public void User_can_customize_help_printed_on_parse_error() + { + CustomHelpBuilder customHelpBuilder = new(); + + CliRootCommand root = new (); + root.Options.Clear(); + root.Options.Add(new HelpOption() + { + Action = new HelpAction() + { + Builder = customHelpBuilder + } + }); + + CliConfiguration config = new(root) + { + EnableParseErrorReporting = true + }; + + customHelpBuilder.WasUsed.Should().BeFalse(); + + ParseResult parseResult = root.Parse("-bla", config); + + int result = parseResult.Invoke(); + result.Should().Be(1); + customHelpBuilder.WasUsed.Should().BeTrue(); + } + + private sealed class CustomHelpBuilder : HelpBuilder + { + internal bool WasUsed = false; + + public override void Write(HelpContext context) + { + WasUsed = true; + + base.Write(context); + } + } } } \ No newline at end of file From 4d3bc7b6fa2fdf40973507d9018b6df9afc6729e Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Tue, 6 Jun 2023 16:49:10 +0200 Subject: [PATCH 2/2] fix: use existing HelpOption when it's available --- src/System.CommandLine/Invocation/ParseErrorAction.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/System.CommandLine/Invocation/ParseErrorAction.cs b/src/System.CommandLine/Invocation/ParseErrorAction.cs index 04845a29da..8a13a09958 100644 --- a/src/System.CommandLine/Invocation/ParseErrorAction.cs +++ b/src/System.CommandLine/Invocation/ParseErrorAction.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.CommandLine.Help; +using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -23,7 +24,9 @@ public override int Invoke(ParseResult parseResult) ConsoleHelpers.ResetTerminalForegroundColor(); - new HelpOption().Action!.Invoke(parseResult); + HelpOption helpOption = parseResult.RootCommandResult.Command.Options.FirstOrDefault(option => option is HelpOption) as HelpOption ?? new HelpOption(); + + helpOption.Action!.Invoke(parseResult); return 1; }