다음을 통해 공유


도움말 출력 사용자 지정

명령줄 앱은 일반적으로 사용 가능한 명령, 옵션 및 인수에 대한 간략한 설명을 표시하는 옵션을 제공합니다. System.CommandLineSystem.CommandLine.Help.HelpOption 옵션에 기본적으로 포함된 을 제공합니다. System.CommandLine.Help.HelpOption은 System.CommandLine.Symbol.Name, System.CommandLine.Symbol.HelpName, System.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 개요