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

1 つのオプションまたは引数のヘルプをカスタマイズする

重要

System.CommandLine は現在プレビュー段階であり、このドキュメントはバージョン 2.0 beta 4 を対象としています。 一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。

オプションの引数名をカスタマイズするには、オプションの ArgumentHelpName プロパティを使います。 また、HelpBuilder.CustomizeSymbol を使うと、コマンド、オプション、引数のヘルプ出力の一部をカスタマイズできます (Symbol は、3 つの型すべての基底クラスです)。 CustomizeSymbol を使うと、以下を指定できます。

  • 最初の列のテキスト。
  • 2 列目のテキスト。
  • 既定値の記述方法。

このサンプル アプリでは、--light-mode については十分に説明されていますが、--file--color のオプションの説明を変更すると便利です。 --file の場合、引数を <file> ではなく <FILEPATH> として識別できます。 --color オプションについては、1 列目で使用できる色の一覧を短縮し、2 列目で一部の色が一部の背景で機能しないという警告を追加できます。

これらの変更を行うには、前のコードに示されている 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

この出力は、firstColumnTextsecondColumnText のパラメーターがその列内での単語の折り返しに対応していることを示しています。

ヘルプ セクションの追加または置換

ヘルプ出力のセクション全体を追加または置換できます。 たとえば、Spectre.Console NuGet パッケージを使って説明セクションに ASCII アートを追加するとします。

UseHelp メソッドに渡されるラムダに HelpBuilder.CustomizeLayout への呼び出しを追加して、レイアウトを変更します。

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 の概要