Bagikan melalui


Cara menyesuaikan bantuan di dalam aplikasi yang dibuat dengan pustaka System.Commandline

Anda dapat menyesuaikan bantuan untuk perintah, opsi, atau argumen tertentu, dan Anda dapat menambahkan atau mengganti seluruh bagian bantuan.

Contoh di dalam artikel ini berfungsi dengan aplikasi baris-perintah berikut:

Kode ini memerlukan arahan 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);

Tanpa penyesuaian, output bantuan berikut yang diproduksi:

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

Menyesuaikan bantuan untuk satu opsi, atau argumen

Penting

System.CommandLine saat ini dalam PRATINJAU, dan dokumentasi ini untuk versi 2.0 beta 4. Beberapa informasi terkait produk prarilis yang dapat diubah secara signifikan sebelum dirilis. Microsoft tidak memberikan jaminan, tersirat maupun tersurat, sehubungan dengan informasi yang diberikan di sini.

Untuk menyesuaikan nama argumen opsi, gunakan properti milik opsi ArgumentHelpName. Dan HelpBuilder.CustomizeSymbol memungkinkan Anda menyesuaikan beberapa bagian output bantuan untuk perintah, opsi, atau argumen (Symbol adalah kelas dasar untuk ketiga jenis). Dengan CustomizeSymbol, Anda dapat menentukan:

  • Teks kolom pertama.
  • Teks kolom kedua.
  • Cara sebuah nilai default dijelaskan.

Di dalam aplikasi sampel, --light-mode dijelaskan secara memadai, tetapi perubahan pada deskripsi opsi --file dan --color akan membantu. Untuk --file, argumen dapat diidentifikasi sebagai <FILEPATH> alih-alih <file>. Untuk opsi --color, Anda dapat mempersingkat daftar warna yang tersedia di dalam kolom satu, dan di kolom dua Anda bisa menambahkan peringatan bahwa beberapa warna tidak akan berfungsi dengan beberapa latar belakang.

Untuk membuat perubahan ini, hapus baris yang await rootCommand.InvokeAsync(args); diperlihatkan dalam kode sebelumnya dan tambahkan di tempatnya kode berikut:

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);

Kode yang diperbarui memerlukan arahan tambahan using :

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

Aplikasi ini sekarang menghasilkan output bantuan berikut:

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

Output ini menunjukkan bahwa parameter firstColumnText dan secondColumnText mendukung pembungkusan kata di dalam kolomnya.

Menambahkan atau mengganti bagian bantuan

Anda dapat menambahkan atau mengganti seluruh bagian output bantuan. Misalnya, Anda ingin menambahkan beberapa seni ASCII ke bagian deskripsi dengan menggunakan paket NuGet Spectre.Console.

Ubah tata letak dengan menambahkan panggilan ke HelpBuilder.CustomizeLayout di lambda yang diteruskan ke metode 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);

Kode sebelumnya memerlukan arahan tambahan using :

using Spectre.Console;

Kelas System.CommandLine.Help.HelpBuilder.Default ini memungkinkan Anda menggunakan kembali potongan fungsionalitas pemformatan bantuan yang ada, dan menyusunnya ke dalam bantuan kustom Anda.

Output bantuan sekarang terlihat seperti ini:

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


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

Jika Anda hanya ingin menggunakan string sebagai teks bagian pengganti alih-alih memformatnya dengan Spectre.Console, ganti Prepend kode dalam contoh sebelumnya dengan kode berikut:

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

Lihat juga

System.CommandLine ringkasan