设为首页收藏本站
网站公告 | 这是第一条公告
     

 找回密码
 立即注册
缓存时间08 现在时间08 缓存数据 世界上没有永恒的懦弱,也没有永恒的坚强,万事靠自己,但是一定要放下懦弱,活的有尊严,活出你的坚强,才真正的体现你的自信和力量,你的活才更有价值!

世界上没有永恒的懦弱,也没有永恒的坚强,万事靠自己,但是一定要放下懦弱,活的有尊严,活出你的坚强,才真正的体现你的自信和力量,你的活才更有价值!

查看: 401|回复: 1

dotnet 命令行工具解决方案 PomeloCli详解

[复制链接]

  离线 

TA的专栏

  • 打卡等级:热心大叔
  • 打卡总天数:220
  • 打卡月天数:0
  • 打卡总奖励:3528
  • 最近打卡:2025-04-11 01:42:35
等级头衔

等級:晓枫资讯-上等兵

在线时间
0 小时

积分成就
威望
0
贡献
395
主题
349
精华
0
金钱
4653
积分
788
注册时间
2023-1-21
最后登录
2025-4-11

发表于 2024-5-29 20:15:06 来自手机 | 显示全部楼层 |阅读模式
目录
  • PomeloCli 是什么
  • 为什么实现
    • 太多的工具太少的规范
    • 基于二进制拷贝分发难以为继
  • 快速开始
    • 1. 引用 PomeloCli 开发命令行应用
    • 2. 引用 PomeloCli 开发命令行插件
      • 开发命令行插件
      • 搭建私有 nuget 服务
      • 发布命令行插件
    • 3. 使用 PomeloCli 集成已发布插件
      • 安装命令行宿主
      • 集成命令行插件
      • 卸载命令行插件
      • 卸载命令行宿主
    • 4. 引用 PomeloCli 开发命令行宿主
      • 其他:异常 NU1102 的处理
      • 其他事项
        • 已知问题
          • 路线图

          PomeloCli 是什么

          • 中文版
          • English version

          我们已经有相当多的命令行工具实现或解析类库,PomeloCli 并不是替代版本,它基于 Nate McMaster 的杰出工作 CommandLineUtils、DotNetCorePlugins 实现了一整套的命令行开发、管理、维护方案,在此特别鸣谢 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 后,既可以通过 

          1. dotnet run -- --help
          复制代码
           查看包含的 
          1. echo
          复制代码
           和 
          1. head
          复制代码
           命令及使用说明。

          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 制品;

          插件加载示意

          1.png

          命令行参数传递示意

          2.png

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

          • 开发人员
            • 开发插件
            • 使用 
              1. dotnet nuget push
              复制代码
               发布插件
          • 运维/使用人员
            • 使用 
              1. dotnet tool
              复制代码
              安装、更新、卸载宿主
            • 使用 
              1. 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
          复制代码

          我们使用 

          1. 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.
          复制代码

          我们用 

          1. 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
          复制代码

          修改 Program.cs 替换为以下内容

          1. using System;
          2. using System.Threading.Tasks;
          3. using Microsoft.Extensions.DependencyInjection;
          4. using PomeloCli;
          5. using PomeloCli.Plugins;
          6. class Program
          7. {
          8. static async Task<int> Main(string[] args)
          9. {
          10. var services = new ServiceCollection()
          11. .AddPluginSupport()
          12. .BuildServiceProvider();
          13. var applicationFactory = new ApplicationFactory(services);
          14. var application = applicationFactory.ConstructRootApp();
          15. return await application.ExecuteAsync(args);
          16. }
          17. }
          复制代码

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

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

          其他:异常 NU1102 的处理

          当安装插件失败且错误码是NU1102 时,表示未找到对应版本,可以执行命令 

          1. $ 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 支持存在问题

          路线图

          • 业务插件配置

          到此这篇关于dotnet 命令行工具解决方案 PomeloCli的文章就介绍到这了,更多相关dotnet 命令行工具解决方案 PomeloCli内容请搜索晓枫资讯以前的文章或继续浏览下面的相关文章希望大家以后多多支持晓枫资讯!


          免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
          晓枫资讯-科技资讯社区-免责声明
          免责声明:以上内容为本网站转自其它媒体,相关信息仅为传递更多信息之目的,不代表本网观点,亦不代表本网站赞同其观点或证实其内容的真实性。
                1、注册用户在本社区发表、转载的任何作品仅代表其个人观点,不代表本社区认同其观点。
                2、管理员及版主有权在不事先通知或不经作者准许的情况下删除其在本社区所发表的文章。
                3、本社区的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,举报反馈:点击这里给我发消息进行删除处理。
                4、本社区一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
                5、以上声明内容的最终解释权归《晓枫资讯-科技资讯社区》所有。
          http://bbs.yzwlo.com 晓枫资讯--游戏IT新闻资讯~~~

            离线 

          TA的专栏

          等级头衔

          等級:晓枫资讯-列兵

          在线时间
          0 小时

          积分成就
          威望
          0
          贡献
          0
          主题
          0
          精华
          0
          金钱
          16
          积分
          12
          注册时间
          2022-12-26
          最后登录
          2022-12-26

          发表于 2025-3-26 20:22:37 | 显示全部楼层
          感谢楼主分享。
          http://bbs.yzwlo.com 晓枫资讯--游戏IT新闻资讯~~~
          严禁发布广告,淫秽、色情、赌博、暴力、凶杀、恐怖、间谍及其他违反国家法律法规的内容。!晓枫资讯-社区
          您需要登录后才可以回帖 登录 | 立即注册

          本版积分规则

          1楼
          2楼

          手机版|晓枫资讯--科技资讯社区 本站已运行

          CopyRight © 2022-2025 晓枫资讯--科技资讯社区 ( BBS.yzwlo.com ) . All Rights Reserved .

          晓枫资讯--科技资讯社区

          本站内容由用户自主分享和转载自互联网,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。

          如有侵权、违反国家法律政策行为,请联系我们,我们会第一时间及时清除和处理! 举报反馈邮箱:点击这里给我发消息

          Powered by Discuz! X3.5

          快速回复 返回顶部 返回列表