Skip to content

Help text after failure should go to standard error #2840

Description

@jennings

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.

$ 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<bool>("--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:

$ 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions