Skip to content

Commit bf313ca

Browse files
authored
Respect custom help builder during parse error reporting (#2211)
1 parent 8238c79 commit bf313ca

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

src/System.CommandLine.Tests/UseParseErrorReportingTests.cs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,5 +60,46 @@ public void User_can_customize_parse_error_result_code()
6060

6161
result.Should().Be(42);
6262
}
63+
64+
[Fact]
65+
public void User_can_customize_help_printed_on_parse_error()
66+
{
67+
CustomHelpBuilder customHelpBuilder = new();
68+
69+
CliRootCommand root = new ();
70+
root.Options.Clear();
71+
root.Options.Add(new HelpOption()
72+
{
73+
Action = new HelpAction()
74+
{
75+
Builder = customHelpBuilder
76+
}
77+
});
78+
79+
CliConfiguration config = new(root)
80+
{
81+
EnableParseErrorReporting = true
82+
};
83+
84+
customHelpBuilder.WasUsed.Should().BeFalse();
85+
86+
ParseResult parseResult = root.Parse("-bla", config);
87+
88+
int result = parseResult.Invoke();
89+
result.Should().Be(1);
90+
customHelpBuilder.WasUsed.Should().BeTrue();
91+
}
92+
93+
private sealed class CustomHelpBuilder : HelpBuilder
94+
{
95+
internal bool WasUsed = false;
96+
97+
public override void Write(HelpContext context)
98+
{
99+
WasUsed = true;
100+
101+
base.Write(context);
102+
}
103+
}
63104
}
64105
}

src/System.CommandLine/Invocation/ParseErrorAction.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

44
using System.CommandLine.Help;
5+
using System.Linq;
56
using System.Threading;
67
using System.Threading.Tasks;
78

@@ -23,7 +24,9 @@ public override int Invoke(ParseResult parseResult)
2324

2425
ConsoleHelpers.ResetTerminalForegroundColor();
2526

26-
new HelpOption().Action!.Invoke(parseResult);
27+
HelpOption helpOption = parseResult.RootCommandResult.Command.Options.FirstOrDefault(option => option is HelpOption) as HelpOption ?? new HelpOption();
28+
29+
helpOption.Action!.Invoke(parseResult);
2730

2831
return 1;
2932
}

0 commit comments

Comments
 (0)