dotnet / dotnet/command-line-api

Help text after failure should go to standard error

Open
#2,840 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
3.7k
Forks
428
PR merge metrics
No merged PRs in 30d

Description

When emitting help text because a command's options weren't specified correctly, the help text should be printed to the standard error stream. This avoids mixing diagnostic messages with program output.

The error message is correctly written to stderr, but the help text is not and I think it should match the error message's behavior.

If help was explicitly asked for with `-h`, then it's probably okay to send that to standard output.

```command
$ dotnet --version
10.0.301

$ cat ok.cs
#!/usr/bin/env dotnet
#:package System.CommandLine@2.0.10
using System.CommandLine;
var okOption = new Option("--ok")
{
Description = "Required flag. When passed, the app prints \"ok\".",
Required = true,
};
var rootCommand = new RootCommand("Prints \"ok\" when --ok is passed.")
{
okOption,
};
rootCommand.Validators.Add(result =>
{
if (result.GetResult(okOption) is null)
{
result.AddError($"Option '{okOption.Name}' is required.");
}
});
rootCommand.SetAction(parseResult =>
{
Console.WriteLine("ok");
return 0;
});
return rootCommand.Parse(args).Invoke();

$ dotnet run ok.cs
Option '--ok' is required.

Description:
Prints "ok" when --ok is passed.

Usage:
ok [options]

Options:
--ok (REQUIRED) Required flag. When passed, the app prints "ok".
-?, -h, --help Show help and usage information
--version Show version information
```

But redirecting stderr to /dev/null shows that the help text (but not the error message) is printed to stdout:

```command
$ dotnet run ok.cs 2> /dev/null
Description:
Prints "ok" when --ok is passed.

Usage:
ok [options]

Options:
--ok (REQUIRED) Required flag. When passed, the app prints "ok".
-?, -h, --help Show help and usage information
--version Show version information
```

Contributor guide

Open the contributing guide

Research direction

Reproduce the command shown in the issue and compare stdout and stderr when the required --ok option is omitted, including with 2>/dev/null. Done means validation-triggered help follows the error to stderr, while help explicitly requested with -h remains on stdout.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
cli
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
68/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.