.NET 8 C# Console 程序命令行解析

文章目录

    由于平时要写大量的增删改查代码,包括 golang gin 的和 C# asp.net 的等等。
    VIM Snippet 可以解决单文件的问题,但是解决不了要同时新建多个文件的情况。
    所以,想用 .NET 8 Console 来实现一个自动生成代码的工具。

    首先呢,就需要能方便的解析命令行参数,来区分不同的框架。

    依赖库:System.CommandLine

    官方介绍

    https://learn.microsoft.com/en-us/dotnet/standard/commandline/get-started-tutorial

    GitHub 项目:

    https://github.com/dotnet/command-line-api

    在 github 项目首页,介绍里说内置了 Shell Completion 的支持。

    Command line parser, model binding, invocation, shell completions

    奇怪的版本号

    两年了,版本号还停留在 2022 年的 2.0.0-beta4。

    虽然从 git 提交历史看,一直有代码的更新,但是版本号不变化了。

    果然在 github issue 中找到了有同样疑问的老哥:

    https://github.com/dotnet/command-line-api/issues/2445

    We are in the process of a major restructuring to change some code ownership. The Powderhouse effort has been delayed by some unforeseen circumstances, but we anticipate the pace improving soon.

    其实,只要这个项目一直在维护就行。

    安装依赖

    dotnet add package System.CommandLine --prerelease
    

    prerelease 参数,表示安装依旧在 beta 版本的依赖。。。恰好这个库就是 beta 版本。

    通过 git diff 命令,会看到 xxx.csproj 文件增加了一段配置:

    +  <ItemGroup>
    +    <PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
    +  </ItemGroup>
    

    Argument 与 Option 的区别

    讲概念,不如直接上示例:

    some_command new name --color
    some_command new name --color black
    
    • new 是 command
    • name 是 argument
    • color 是 option. black 是 color option 的值,当然不设置可以有默认值

    用 argument 的好处是,省去了 option 名字的输入。

    示例代码

    using System.CommandLine;
    
    Console.WriteLine("Hello, World!");
    
    PrintArgs(args);
    
    var rootCommand = new RootCommand("DotNet Snippet Tool for generating code.");
    
    var nameArgument = new Argument<string>(
        name: "name",
        description: "Name");
    
    // asp_mvc command
    var aspMvcCommand = new Command("asp_mvc", "Add ASP MVC Controller, View and I18N Resources.") {
        nameArgument
    };
    aspMvcCommand.SetHandler(async (name) =>
        {
            await NewAspMvc(name);
        },
        nameArgument);
    rootCommand.AddCommand(aspMvcCommand);
    // end of asp_mvc command
    
    await rootCommand.InvokeAsync(args);
    
    void PrintArgs(string[] args) {
        Console.WriteLine($"parameter count = {args.Length}");
    
        for (int i = 0; i < args.Length; i++)
        {
            Console.WriteLine($"Arg[{i}] = [{args[i]}]");
        }
    }
    
    async Task NewAspMvc(string name) {
        Console.WriteLine($"name: {name}");
    }
    

    运行结果

    正确的输入:

    > dotnet.exe run asp_mvc hello
    parameter count = 2
    Arg[0] = [asp_mvc]
    Arg[1] = [hello]
    name: hello
    

    错误的输入:

    > dotnet.exe run test
    Hello, World!
    parameter count = 1
    Arg[0] = [test]
    Required command was not provided.
    Unrecognized command or argument 'test'.
    
    Description:
      DotNet Snippet Tool for generating code.
    
    Usage:
      dotnet_snippet [command] [options]
    
    Options:
      --version       Show version information
      -?, -h, --help  Show help and usage information
    
    Commands:
      asp_mvc <name>  Add ASP MVC Controller, View and I18N Resources.
    

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式