Поделиться через


Настройка справки в приложениях, созданных с помощью библиотеки System.Commandline

Вы можете настроить справку для определенной команды, параметра или аргумента, а также добавить или заменить все разделы справки.

Примеры в этой статье работают со следующим приложением командной строки:

Для этого кода требуется директива using :

using System.CommandLine;
var fileOption = new Option<FileInfo>(
    "--file",
    description: "The file to print out.",
    getDefaultValue: () => new FileInfo("scl.runtimeconfig.json"));
var lightModeOption = new Option<bool> (
    "--light-mode",
    description: "Determines whether the background color will be black or white");
var foregroundColorOption = new Option<ConsoleColor>(
    "--color",
    description: "Specifies the foreground color of console output",
    getDefaultValue: () => ConsoleColor.White);

var rootCommand = new RootCommand("Read a file")
{
    fileOption,
    lightModeOption,
    foregroundColorOption
};

rootCommand.SetHandler((file, lightMode, color) =>
    {
        Console.BackgroundColor = lightMode ? ConsoleColor.White: ConsoleColor.Black;
        Console.ForegroundColor = color;
        Console.WriteLine($"--file = {file?.FullName}");
        Console.WriteLine($"File contents:\n{file?.OpenText().ReadToEnd()}");
    },
    fileOption,
    lightModeOption,
    foregroundColorOption);

await rootCommand.InvokeAsync(args);

Без настройки выходные данные справки создаются:

Description:
  Read a file

Usage:
  scl [options]

Options:
  --file <file>                                               The file to print out. [default: scl.runtimeconfig.json]
  --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|Dark  [default: White]
  Magenta|DarkRed|DarkYellow|Gray|Green|Magenta|Red|White|Ye
  llow>
  --version                                                   Show version information
  -?, -h, --help                                              Show help and usage information

Настройка справки для одного варианта или аргумента

Внимание

System.CommandLine в настоящее время находится в предварительной версии, и эта документация предназначена для версии 2.0 бета-версии 4. Некоторые сведения относятся к предварительному выпуску продукта, который может быть существенно изменен до его выпуска. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.

Чтобы настроить имя аргумента параметра, используйте свойство параметра ArgumentHelpName . И HelpBuilder.CustomizeSymbol позволяет настроить несколько частей выходных данных справки для команды, параметра или аргумента (Symbol это базовый класс для всех трех типов). С CustomizeSymbolпомощью этого параметра можно указать следующее:

  • Первый текст столбца.
  • Второй текст столбца.
  • Способ описания значения по умолчанию.

В примере приложения объясняется достаточно, --light-mode но изменения --file в описаниях вариантов --color будут полезны. Для --fileэтого аргумент можно определить как не <file>так<FILEPATH>. --color Для параметра можно сократить список доступных цветов в столбце один, а в столбце два можно добавить предупреждение о том, что некоторые цвета не будут работать с некоторыми фонами.

Чтобы внести эти изменения, удалите строку, показанную await rootCommand.InvokeAsync(args); в предыдущем коде, и добавьте в его место следующий код:

fileOption.ArgumentHelpName = "FILEPATH";

var parser = new CommandLineBuilder(rootCommand)
        .UseDefaults()
        .UseHelp(ctx =>
        {
            ctx.HelpBuilder.CustomizeSymbol(foregroundColorOption,
                firstColumnText: "--color <Black, White, Red, or Yellow>",
                secondColumnText: "Specifies the foreground color. " +
                    "Choose a color that provides enough contrast " +
                    "with the background color. " + 
                    "For example, a yellow foreground can't be read " +
                    "against a light mode background.");
        })
        .Build();

parser.Invoke(args);

Для обновленного кода требуются дополнительные using директивы:

using System.CommandLine.Builder;
using System.CommandLine.Help;
using System.CommandLine.Parsing;

Теперь приложение создает следующие выходные данные справки:

Description:
  Read a file

Usage:
  scl [options]

Options:
  --file <FILEPATH>                       The file to print out. [default: CustomHelp.runtimeconfig.json]
  --light-mode                            Determines whether the background color will be black or white
  --color <Black, White, Red, or Yellow>  Specifies the foreground color. Choose a color that provides enough contrast
                                          with the background color. For example, a yellow foreground can't be read
                                          against a light mode background.
  --version                               Show version information
  -?, -h, --help                          Show help and usage information

В этом выходных данных показано, что firstColumnText параметры secondColumnText поддерживают оболочку слов в столбцах.

Добавление или замена разделов справки

Вы можете добавить или заменить весь раздел выходных данных справки. Например, предположим, что вы хотите добавить некоторое искусство ASCII в раздел описания с помощью пакета NuGet Spectre.Console .

Измените макет, добавив вызов HelpBuilder.CustomizeLayout в лямбда-код, переданный методу UseHelp :

fileOption.ArgumentHelpName = "FILEPATH";

var parser = new CommandLineBuilder(rootCommand)
        .UseDefaults()
        .UseHelp(ctx =>
        {
            ctx.HelpBuilder.CustomizeSymbol(foregroundColorOption,
                firstColumnText: "--color <Black, White, Red, or Yellow>",
                secondColumnText: "Specifies the foreground color. " +
                    "Choose a color that provides enough contrast " +
                    "with the background color. " +
                    "For example, a yellow foreground can't be read " +
                    "against a light mode background.");
            ctx.HelpBuilder.CustomizeLayout(
                _ =>
                    HelpBuilder.Default
                        .GetLayout()
                        .Skip(1) // Skip the default command description section.
                        .Prepend(
                            _ => Spectre.Console.AnsiConsole.Write(
                                new FigletText(rootCommand.Description!))
                ));
        })
        .Build();

await parser.InvokeAsync(args);

Для предыдущего кода требуется дополнительная using директива:

using Spectre.Console;

Класс System.CommandLine.Help.HelpBuilder.Default позволяет повторно использовать существующие вспомогательные функции форматирования и создавать их в настраиваемую справку.

Выходные данные справки теперь выглядят следующим образом:

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


Usage:
  scl [options]

Options:
  --file <FILEPATH>                       The file to print out. [default: CustomHelp.runtimeconfig.json]
  --light-mode                            Determines whether the background color will be black or white
  --color <Black, White, Red, or Yellow>  Specifies the foreground color. Choose a color that provides enough contrast
                                          with the background color. For example, a yellow foreground can't be read
                                          against a light mode background.
  --version                               Show version information
  -?, -h, --help                          Show help and usage information

Если вы хотите просто использовать строку в качестве текста раздела замены вместо форматирования Spectre.Console, замените Prepend код в предыдущем примере следующим кодом:

.Prepend(
    _ => _.Output.WriteLine("**New command description section**")

См. также

Обзор System.CommandLine