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;
}
}
System.CommandLine 사용
프로그래밍
2022/03/14 22:18
덧글을 달아 주세요