Skip to content

1491184849/Cracker.CommandLine

Repository files navigation

Cracker.CommandLine

  • 不依赖第三方包
  • 解析命令行参数
  • 支持选项、子命令
  • 核心使用反射

NuGet Version NuGet Downloads Forks Stargazers Issues MIT License

使用步骤
  1. 安装.NET SDK8.x
  2. 添加nuget包

dotnet add package Cracker.CommandLine

or

Install-Package Cracker.CommandLine -Version 1.0.3

  1. 示例Program.cs
var app = new CommandApp();
app.Add<ConvertCommand>("convert")
    .Child(() => new CommandConfiguration("ts", new TimeToTimestampCommand()).WithDescription("时间戳转时间"))
    .Child(() => new CommandConfiguration("time", new TimestampToTimeCommand()).WithDescription("时间转时间戳"))
    .WithDescription("格式转换");
await app.StartAsync(args);
  1. 示例ConvertCommand.cs
public class ConvertCommand : CommandBase
{
    public override Task ExecuteAsync(CommandContext context)
    {
        return Task.CompletedTask;
    }
}

public class TimeParameter
{
    [CliArgument(0, "要转换的时间|时间戳", true)]
    public string? Value { get; set; }

    [CliOption("-f", "指定时间戳的格式,可选值:<s|ms>,s:秒,ms:毫秒", "s")]
    public string? Format { get; set; }
}

public class TimeToTimestampCommand : CommandBase<TimeParameter>
{
    public override Task ExecuteAsync(CommandContext context)
    {
        if (DateTime.TryParse(Receive.Value, out var time))
        {
            if (Receive.Format == "s")
            {
                Console.WriteLine(TimeUtils.DateTimeToTimestamp(time, true));
            }
            else
            {
                Console.WriteLine(TimeUtils.DateTimeToTimestamp(time, false));
            }
        }
        else
        {
            Console.WriteLine("时间格式错误");
        }
        return Task.CompletedTask;
    }
}

public class TimestampToTimeCommand : CommandBase<TimeParameter>
{
    public override Task ExecuteAsync(CommandContext context)
    {
        if (long.TryParse(Receive.Value, out var ts))
        {
            Console.WriteLine(TimeUtils.TimestampToDateTime(ts).ToString("yyyy-MM-dd HH:mm:ss"));
        }
        else
        {
            Console.WriteLine("时间戳格式错误");
        }
        return Task.CompletedTask;
    }
}

作者

crackerwork@outlook.com

QQ: 1491184849

MySite: https://crackerwork.cn

您也可以在贡献者名单中参看所有参与该项目的开发者。

版权说明

该项目签署了MIT 授权许可,详情请参阅 LICENSE.txt

About

纯手写命令行

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages