System.CommandLine 사용

using System.CommandLine;
using System.CommandLine.NamingConventionBinder;
using System.CommandLine.Invocation;
using System.CommandLine.IO;
using System.Reflection;

namespace Project;

public static class Program
{
    public static async Task<Int32> Main(string[] args)
    {
        RootCommand rootCommand = new()
        {
#if DEBUG
            new Command("debug", "debugging").WithHandler(nameof(HandleDebugAsync)),
#endif // DEBUG

            new Command("run", "running")
            {
                new Option<string>(new[] { "--config", "-c" },
                    description: "config file path.",
                    getDefaultValue: () => "config.json")
                {
                    IsRequired = true,
                },
                new Option<bool>(new[] { "--verbose", "-v" },
                    description: "Show the details.",
                    getDefaultValue: () => false)
                {
                    IsRequired = false,
                },
            }.WithHandler(nameof(HandleRunAsync)),
        };

        return await rootCommand.InvokeAsync(args);
    }

#if DEBUG
    private static async Task<Int32> HandleDebugAsync(IConsole console, CancellationToken cancellationToken)
    {
        string configFilePath = "config.json";
        bool verbose = true;

        return await HandleRunAsync(configFilePath, verbose, console, cancellationToken);
    }
#endif // DEBUG

    private static async Task<Int32> HandleRunAsync(string configFilePath, bool verbose,
        IConsole console, CancellationToken cancellationToken)
    {
        if (verbose)
        {
            console.WriteLine($"current directory '{Environment.CurrentDirectory}'");
            console.WriteLine($"--config '{configFilePath}'");
            console.WriteLine($"--verbose '{verbose}'");
        }

        await Task.CompletedTask;
        return 0;
    }

    private static Command WithHandler(this Command command, string methodName)
    {
        MethodInfo? method =
            typeof(Program).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static);
        ICommandHandler handler = CommandHandler.Create(method!);
        command.Handler = handler;
        return command;
    }
}
2022/03/14 22:18 2022/03/14 22:18

글 걸기 주소 : 이 글에는 트랙백을 보낼 수 없습니다

덧글을 달아 주세요