自定义帮助输出

命令行应用通常提供一个选项来显示可用命令、选项和参数的简要说明。 System.CommandLine 提供的 System.CommandLine.Help.HelpOption 默认情况下被包含在 RootCommand 选项中。 System.CommandLine.Help.HelpOption 通过使用由 System.CommandLine.Symbol.NameSystem.CommandLine.Symbol.HelpNameSystem.CommandLine.Symbol.Description 以及默认值或完成源等其他属性公开的信息,为定义的符号生成帮助输出。

Option<FileInfo> fileOption = new("--file")
{
    Description = "The file to print out.",
};
Option<bool> lightModeOption = new("--light-mode")
{
    Description = "Determines whether the background color will be black or white"
};
Option<ConsoleColor> foregroundColorOption = new("--color")
{
    Description = "Specifies the foreground color of console output",
    DefaultValueFactory = _ => ConsoleColor.White
};

RootCommand rootCommand = new("Read a file")
{
    fileOption,
    lightModeOption,
    foregroundColorOption
};
rootCommand.Parse("-h").Invoke();
Description:
  Read a file

Usage:
  scl [options]

Options:
  -?, -h, --help                                            Show help and usage information
  --version                                                 Show version information
  --file                                                    The file to print out.
  --light-mode                                              Determines whether the background color will be black
                                                            or white
  --color                                                   Specifies the foreground color of console output
  <Black|Blue|Cyan|DarkBlue|DarkCyan|DarkGray|DarkGreen|Da  [default: White]
  rkMagenta|DarkRed|DarkYellow|Gray|Green|Magenta|Red|Whit
  e|Yellow>

应用用户可能会习惯于在不同平台上以不同方式请求帮助,因此基于System.CommandLine构建的应用可以以多种方式响应请求帮助。 以下命令都是等效的:

dotnet --help
dotnet -h
dotnet /h
dotnet -?
dotnet /?

帮助输出不一定显示所有可用的命令、参数和选项。 其中一些可能通过属性System.CommandLine.Symbol.Hidden,这意味着它们不会显示在帮助输出(和完成)中,但可以在命令行上指定。

帮助自定义

你可以通过为每个符号定义特定的帮助文本来自定义命令的帮助输出,从而为用户进一步说明其用法。

若要自定义选项参数的名称,请使用选项 System.CommandLine.Option.HelpName 的属性。

在示例应用中,--light-mode 可以得到充分说明,但对 --file--color 选项说明的更改将很有用。 对于 --file,可以将参数标识为 <FILEPATH>。 对于该 --color 选项,可以缩短可用颜色的列表。

若要进行这些更改,请使用以下代码扩展前面的代码:

fileOption.HelpName = "FILEPATH";
foregroundColorOption.AcceptOnlyFromAmong(
    ConsoleColor.Black.ToString(),
    ConsoleColor.White.ToString(),
    ConsoleColor.Red.ToString(),
    ConsoleColor.Yellow.ToString()
);

应用现在生成以下帮助输出:

Description:
  Read a file

Usage:
  scl [options]

Options:
  -?, -h, --help                    Show help and usage information
  --version                         Show version information
  --file <FILEPATH>                 The file to print out.
  --light-mode                      Determines whether the background color will be black or white
  --color <Black|Red|White|Yellow>  Specifies the foreground color of console output [default: White]

添加章节以改善输出

可以向帮助输出添加第一节或最后一节。 例如,假设你想要使用 Spectre.Console NuGet 包将一些 ASCII 艺术添加到说明部分。

定义一个自定义动作,以便在调用默认 HelpAction 之前和之后执行一些额外的逻辑。

internal class CustomHelpAction : SynchronousCommandLineAction
{
    private readonly HelpAction _defaultHelp;

    public CustomHelpAction(HelpAction action) => _defaultHelp = action;

    public override int Invoke(ParseResult parseResult)
    {
        Spectre.Console.AnsiConsole.Write(new FigletText(parseResult.RootCommandResult.Command.Description!));

        int result = _defaultHelp.Invoke(parseResult);

        Spectre.Console.AnsiConsole.WriteLine("Sample usage: --file input.txt");

        return result;

    }
}

更新由 HelpAction 定义的 RootCommand 以使用自定义操作:

for (int i = 0; i < rootCommand.Options.Count; i++)
{
    // RootCommand has a default HelpOption, we need to update its Action.
    if (rootCommand.Options[i] is HelpOption defaultHelpOption)
    {
        defaultHelpOption.Action = new CustomHelpAction((HelpAction)defaultHelpOption.Action!);
        break;
    }
}

帮助输出现在如下所示:

  ____                       _                __   _   _
 |  _ \    ___    __ _    __| |     __ _     / _| (_) | |   ___
 | |_) |  / _ \  / _` |  / _` |    / _` |   | |_  | | | |  / _ \
 |  _ <  |  __/ | (_| | | (_| |   | (_| |   |  _| | | | | |  __/
 |_| \_\  \___|  \__,_|  \__,_|    \__,_|   |_|   |_| |_|  \___|

Description:
  Read a file

Usage:
  scl [options]

Options:
  -?, -h, --help                    Show help and usage information
  --version                         Show version information
  --file <FILEPATH>                 The file to print out.
  --light-mode                      Determines whether the background color will be black or white
  --color <Black|Red|White|Yellow>  Specifies the foreground color of console output [default: White]

Sample usage: --file input.txt

另请参阅

System.CommandLine 概述