经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » ASP.net » 查看文章
dotnet 命令行工具解决方案 PomeloCli
来源:cnblogs  作者:leoninew  时间:2024/5/21 8:52:12  对本文有异议

PomeloCli 是什么

我们已经有相当多的命令行工具实现或解析类库,PomeloCli 并不是替代版本,它基于 Nate McMaster 的杰出工作 CommandLineUtilsDotNetCorePlugins 实现了一整套的命令行开发、管理、维护方案,在此特别鸣谢 Nate。

为什么实现

作者述职于 devOps 部门,编写、维护 CLI 工具并将其部署到各个服务器节点上是很常规的需求,但是又常常面临一系列问题。

太多的工具太少的规范

命令行工具开发自由度过高,随之而来的是迥异的开发和使用体验:

  • 依赖和配置管理混乱;
  • 没有一致的参数、选项标准,缺失帮助命令;
  • 永远找不到版本对号的说明文档;

基于二进制拷贝分发难以为继

工具开发完了还需要部署到计算节点上,但是对运维人员极其不友好:

  • 永远不知道哪些机器有没有安装,安装了什么版本;
  • 需要进入工具目录配置运行参数;

快速开始

你可以直接开始,但是在此之前理解命令、参数和选项仍然有很大的帮助。相关内容可以参考 Introduction.

1. 引用 PomeloCli 开发命令行应用

引用 PomeloCli 来快速创建自己的命令行应用

  1. $ dotnet new console -n SampleApp
  2. $ cd SampleApp
  3. $ dotnet add package PomeloCli -v 1.3.0

在入口程序添加必要的处理逻辑,文件内容见于 docs/sample/3-sample-app/Program.cs。这里使用了依赖注入管理命令,相关参考见 .NET 依赖项注入

  1. using System;
  2. using System.Threading.Tasks;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using PomeloCli;
  5. class Program
  6. {
  7. static async Task<int> Main(string[] avg)
  8. {
  9. var services = new ServiceCollection()
  10. .AddTransient<ICommand, EchoCommand>()
  11. .AddTransient<ICommand, HeadCommand>()
  12. .BuildServiceProvider();
  13. var application = ApplicationFactory.ConstructFrom(services);
  14. return await application.ExecuteAsync(args);
  15. }
  16. }

这里有两个命令:EchoCommand,是对 echo 命令的模拟,文件内容见于 docs/sample/3-sample-app/EchoCommand.cs

  1. #nullable disable
  2. using System;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using McMaster.Extensions.CommandLineUtils;
  6. using PomeloCli;
  7. [Command("echo", Description = "display a line of text")]
  8. class EchoCommand : Command
  9. {
  10. [Argument(0, "input")]
  11. public String Input { get; set; }
  12. [Option("-n|--newline", CommandOptionType.NoValue, Description = "do not output the trailing newline")]
  13. public Boolean? Newline { get; set; }
  14. protected override Task<int> OnExecuteAsync(CancellationToken cancellationToken)
  15. {
  16. if (Newline.HasValue)
  17. {
  18. Console.WriteLine(Input);
  19. }
  20. else
  21. {
  22. Console.Write(Input);
  23. }
  24. return Task.FromResult(0);
  25. }
  26. }

HeadCommand是对 head 命令的模拟,文件内容见于 docs/sample/3-sample-app/HeadCommand.cs

  1. #nullable disable
  2. using System;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using McMaster.Extensions.CommandLineUtils;
  9. using PomeloCli;
  10. [Command("head", Description = "Print the first 10 lines of each FILE to standard output")]
  11. class HeadCommand : Command
  12. {
  13. [Required]
  14. [Argument(0)]
  15. public String Path { get; set; }
  16. [Option("-n|--line", CommandOptionType.SingleValue, Description = "print the first NUM lines instead of the first 10")]
  17. public Int32 Line { get; set; } = 10;
  18. protected override Task<int> OnExecuteAsync(CancellationToken cancellationToken)
  19. {
  20. if (!File.Exists(Path))
  21. {
  22. throw new FileNotFoundException($"file '{Path}' not found");
  23. }
  24. var lines = File.ReadLines(Path).Take(Line);
  25. foreach (var line in lines)
  26. {
  27. Console.WriteLine(line);
  28. }
  29. return Task.FromResult(0);
  30. }
  31. }

进入目录 SampleApp 后,既可以通过 dotnet run -- --help 查看包含的 echohead 命令及使用说明。

  1. $ dotnet run -- --help
  2. Usage: SampleApp [command] [options]
  3. Options:
  4. -?|-h|--help Show help information.
  5. Commands:
  6. echo display a line of text
  7. head Print the first 10 lines of each FILE to standard output
  8. Run 'SampleApp [command] -?|-h|--help' for more information about a command.
  9. $ dotnet run -- echo --help
  10. display a line of text
  11. Usage: SampleApp echo [options] <input>
  12. Arguments:
  13. input
  14. Options:
  15. -n|--newline do not output the trailing newline
  16. -?|-h|--help Show help information.

也可以编译使用可执行的 SampleApp.exe 。

  1. $ ./bin/Debug/net8.0/SampleApp.exe --help
  2. Usage: SampleApp [command] [options]
  3. Options:
  4. -?|-h|--help Show help information.
  5. Commands:
  6. echo display a line of text
  7. head Print the first 10 lines of each FILE to standard output
  8. Run 'SampleApp [command] -?|-h|--help' for more information about a command.
  9. $ ./bin/Debug/net8.0/SampleApp.exe echo --help
  10. display a line of text
  11. Usage: SampleApp echo [options] <input>
  12. Arguments:
  13. input
  14. Options:
  15. -n|--newline do not output the trailing newline
  16. -?|-h|--help Show help information.

BRAVO 很简单对吧。

2. 引用 PomeloCli 开发命令行插件

如果只是提供命令行应用的创建能力,作者大可不必发布这样一个项目,因为 McMaster.Extensions.CommandLineUtils 本身已经做得足够好了。如上文"为什么实现章节"所说,作者还希望解决命令行工具的分发维护问题。

为了实现这一目标,PomeloCli 继续基于 McMaster.NETCore.Plugins 实现了一套插件系统或者说架构:

  • 将命令行工具拆分成宿主插件两部分功能;
  • 宿主负责安装、卸载、加载插件,作为命令行入口将参数转交给对应的插件
  • 插件负责具体的业务功能的实现;
  • 宿主插件均打包成标准的 nuget 制品;

插件加载示意

image-20240519212639103

命令行参数传递示意

image-20240519212733969

通过将宿主的维护交由 dotnet tool 处理、将插件的维护交由宿主处理,我们希望解决命令行工具的分发维护问题:

  • 开发人员
    • 开发插件
    • 使用 dotnet nuget push 发布插件
  • 运维/使用人员
    • 使用 dotnet tool安装、更新、卸载宿主
    • 使用 pomelo-cli install/uninstall 安装、更新、卸载插件

现在现在我们来开发一个插件应用。

开发命令行插件

引用 PomeloCli 来创建自己的命令行插件

  1. $ dotnet new classlib -n SamplePlugin
  2. $ cd SamplePlugin
  3. $ dotnet add package PomeloCli -v 1.3.0

我们把上文提到的 EchoCommand 和 HeadCommand 复制到该项目,再添加依赖注入文件 ServiceCollectionExtensions.cs,文件内容见于 docs/sample/4-sample-plugin/ServiceCollectionExtensions.cs

  1. using System;
  2. using System.Threading.Tasks;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using PomeloCli;
  5. public static class ServiceCollectionExtensions
  6. {
  7. /// <summary>
  8. /// pomelo-cli load plugin by this method, see
  9. /// <see cref="PomeloCli.Plugins.Runtime.PluginResolver.Loading()" />
  10. /// </summary>
  11. /// <param name="services"></param>
  12. /// <returns></returns>
  13. public static IServiceCollection AddCommands(this IServiceCollection services)
  14. {
  15. return services
  16. .AddTransient<ICommand, EchoCommand>()
  17. .AddTransient<ICommand, HeadCommand>();
  18. }
  19. }

为了能够使得插件运行起来,我们还需要在打包时将依赖添加到 nupkg 文件中。为此需要修改 csproj 添加打包配置,参考 docs/sample/4-sample-plugin/SamplePlugin.csproj,相关原理见出处 How to include package reference files in your nuget

搭建私有 nuget 服务

为了托管我们的工具与插件,我们这里使用 BaGet 搭建轻量的 nuget 服务,docker-compose.yaml 已经提供见 baget。docker 等工具使用请自行查阅。

  1. version: "3.3"
  2. services:
  3. baget:
  4. image: loicsharma/baget
  5. container_name: baget
  6. ports:
  7. - "8000:80"
  8. volumes:
  9. - $PWD/data:/var/baget

我们使用 docker-compose up -d 将其运行起来,baget 将在地址 http://localhost:8000/ 上提供服务。

发布命令行插件

现我们在有了插件和 nuget 服务,可以发布插件了。

  1. $ cd SamplePlugin
  2. $ dotnet pack -o nupkgs -c Debug
  3. $ dotnet nuget push -s http://localhost:8000/v3/index.json nupkgs/SamplePlugin.1.0.0.nupkg

3. 使用 PomeloCli 集成已发布插件

pomelo-cli 是一个 dotnet tool 应用,可以看作命令行宿主,它包含了一组 plugin 命令用来管理我们的命令行插件。

安装命令行宿主

我们使用标准的 dotnet tool CLI 命令安装 PomeloCli,相关参考见 How to manage .NET tools

  1. $ dotnet tool install PomeloCli.Host --version 1.3.0 -g
  2. $ pomelo-cli --help
  3. Usage: PomeloCli.Host [command] [options]
  4. Options:
  5. -?|-h|--help Show help information.
  6. Commands:
  7. config
  8. plugin
  9. version
  10. Run 'PomeloCli.Host [command] -?|-h|--help' for more information about a command.

可以看到 pomelo-cli 内置了部分命令。

集成命令行插件

pomelo-cli 内置了一组插件,包含了其他插件的管理命令

  1. $ pomelo-cli plugin --help
  2. Usage: PomeloCli.Host plugin [command] [options]
  3. Options:
  4. -?|-h|--help Show help information.
  5. Commands:
  6. install
  7. list
  8. uninstall
  9. Run 'plugging [command] -?|-h|--help' for more information about a command.

我们用 plugin install 命令安装刚刚发布的插件 SamplePlugin

  1. $ pomelo-cli plugin install SamplePlugin -v 1.0.0 -s http://localhost:8000/v3/index.json
  2. $ pomelo-cli --help
  3. Usage: PomeloCli.Host [command] [options]
  4. Options:
  5. -?|-h|--help Show help information.
  6. Commands:
  7. config
  8. echo display a line of text
  9. head Print the first 10 lines of each FILE to standard output
  10. plugin
  11. version
  12. Run 'PomeloCli.Host [command] -?|-h|--help' for more information about a command.
  13. $ pomelo-cli echo --help
  14. display a line of text
  15. Usage: PomeloCli.Host echo [options] <input>
  16. Arguments:
  17. input
  18. Options:
  19. -n|--newline do not output the trailing newline
  20. -?|-h|--help Show help information.

可以看到 SamplePlugin 包含的 echo 和 head 命令已经被显示在子命令列表中。

卸载命令行插件

pomelo-cli 当然也可以卸载其他插件

  1. $ pomelo-cli plugin uninstall SamplePlugin

卸载命令行宿主

我们使用标准的 dotnet tool CLI 命令卸载 PomeloCli

  1. $ dotnet tool uninstall PomeloCli.Host -g

4. 引用 PomeloCli 开发命令行宿主

你可能需要自己的命令行宿主,这也很容易。

  1. $ dotnet new console -n SampleHost
  2. $ cd SampleHost/
  3. $ dotnet add package PomeloCli
  4. $ dotnet add package PomeloCli.Plugins
  5. $ dotnet build

现在你得到了一个命令宿主,你可以运行它,甚至用它安装插件

  1. $ ./bin/Debug/net8.0/SampleHost.exe --help
  2. Usage: SampleHost [command] [options]
  3. Options:
  4. -?|-h|--help Show help information.
  5. Commands:
  6. plugin
  7. Run 'SampleHost [command] -?|-h|--help' for more information about a command.
  8. $ ./bin/Debug/net8.0/SampleHost.exe plugin install SamplePlugin -v 1.0.0 -s http://localhost:8000/v3/index.json
  9. ...
  10. $ ./bin/Debug/net8.0/SampleHost.exe --help
  11. Usage: SampleHost [command] [options]
  12. Options:
  13. -?|-h|--help Show help information.
  14. Commands:
  15. echo display a line of text
  16. head Print the first 10 lines of each FILE to standard output
  17. plugin
  18. Run 'SampleHost [command] -?|-h|--help' for more information about a command.

其他:异常 NU1102 的处理

当安装插件失败且错误码是NU1102 时,表示未找到对应版本,可以执行命令 $ dotnet nuget locals http-cache --clear 以清理 HTTP 缓存。

  1. info : Restoring packages for C:\Users\leon\.PomeloCli.Host\Plugin.csproj...
  2. info : GET http://localhost:8000/v3/package/sampleplugin/index.json
  3. info : OK http://localhost:8000/v3/package/sampleplugin/index.json 2ms
  4. error: NU1102: Unable to find package Sample Plugin with version (>= 1.1.0)
  5. error: - Found 7 version(s) in http://localhost:8000/v3/index.json [ Nearest version: 1.0.0 ]
  6. error: Package 'SamplePlugin' is incompatible with 'user specified' frameworks in project 'C:\Users\leon\.PomeloCli.Host\Plugin.csproj'.

其他事项

已知问题

  • refit 支持存在问题

路线图

  • 业务插件配置

项目仍然在开发中,欢迎与我交流想法

原文链接:https://www.cnblogs.com/leoninew/p/18203243/pomelo_cli_intro

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号