dotnet 命令行工具解决方案 PomeloCli
PomeloCli 是什么
我们已经有相当多的命令行工具实现或解析类库,PomeloCli 并不是替代版本,它基于 Nate McMaster 的杰出工作 CommandLineUtils、DotNetCorePlugins 实现了一整套的命令行开发、管理、维护方案,在此特别鸣谢 Nate。
为什么实现
作者述职于 devOps 部门,编写、维护 CLI 工具并将其部署到各个服务器节点上是很常规的需求,但是又常常面临一系列问题。
太多的工具太少的规范
命令行工具开发自由度过高,随之而来的是迥异的开发和使用体验:
- 依赖和配置管理混乱;
- 没有一致的参数、选项标准,缺失帮助命令;
- 永远找不到版本对号的说明文档;
基于二进制拷贝分发难以为继
工具开发完了还需要部署到计算节点上,但是对运维人员极其不友好:
- 永远不知道哪些机器有没有安装,安装了什么版本;
- 需要进入工具目录配置运行参数;
快速开始
你可以直接开始,但是在此之前理解命令、参数和选项仍然有很大的帮助。相关内容可以参考 Introduction.
1. 引用 PomeloCli 开发命令行应用
引用 PomeloCli 来快速创建自己的命令行应用
$ dotnet new console -n SampleApp
$ cd SampleApp
$ dotnet add package PomeloCli -v 1.3.0
在入口程序添加必要的处理逻辑,文件内容见于 docs/sample/3-sample-app/Program.cs。这里使用了依赖注入管理命令,相关参考见 .NET 依赖项注入。
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using PomeloCli;
class Program
{
static async Task<int> Main(string[] avg)
{
var services = new ServiceCollection()
.AddTransient<ICommand, EchoCommand>()
.AddTransient<ICommand, HeadCommand>()
.BuildServiceProvider();
var application = ApplicationFactory.ConstructFrom(services);
return await application.ExecuteAsync(args);
}
}
这里有两个命令:EchoCommand,是对 echo 命令的模拟,文件内容见于 docs/sample/3-sample-app/EchoCommand.cs
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using McMaster.Extensions.CommandLineUtils;
using PomeloCli;
[Command("echo", Description = "display a line of text")]
class EchoCommand : Command
{
[Argument(0, "input")]
public String Input { get; set; }
[Option("-n|--newline", CommandOptionType.NoValue, Description = "do not output the trailing newline")]
public Boolean? Newline { get; set; }
protected override Task<int> OnExecuteAsync(CancellationToken cancellationToken)
{
if (Newline.HasValue)
{
Console.WriteLine(Input);
}
else
{
Console.Write(Input);
}
return Task.FromResult(0);
}
}
HeadCommand是对 head 命令的模拟,文件内容见于 docs/sample/3-sample-app/HeadCommand.cs。
#nullable disable
using System;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using McMaster.Extensions.CommandLineUtils;
using PomeloCli;
[Command("head", Description = "Print the first 10 lines of each FILE to standard output")]
class HeadCommand : Command
{
[Required]
[Argument(0)]
public String Path { get; set; }
[Option("-n|--line", CommandOptionType.SingleValue, Description = "print the first NUM lines instead of the first 10")]
public Int32 Line { get; set; } = 10;
protected override Task<int> OnExecuteAsync(CancellationToken cancellationToken)
{
if (!File.Exists(Path))
{
throw new FileNotFoundException($"file '{Path}' not found");
}
var lines = File.ReadLines(Path).Take(Line);
foreach (var line in lines)
{
Console.WriteLine(line);
}
return Task.FromResult(0);
}
}
进入目录 SampleApp 后,既可以通过 dotnet run -- --help 查看包含的 echo 和 head 命令及使用说明。
$ dotnet run -- --help
Usage: SampleApp [command] [options]
Options:
-?|-h|--help Show help information.
Commands:
echo display a line of text
head Print the first 10 lines of each FILE to standard output
Run 'SampleApp [command] -?|-h|--help' for more information about a command.
$ dotnet run -- echo --help
display a line of text
Usage: SampleApp echo [options] <input>
Arguments:
input
Options:
-n|--newline do not output the trailing newline
-?|-h|--help Show help information.
也可以编译使用可执行的 SampleApp.exe 。
$ ./bin/Debug/net8.0/SampleApp.exe --help
Usage: SampleApp [command] [options]
Options:
-?|-h|--help Show help information.
Commands:
echo display a line of text
head Print the first 10 lines of each FILE to standard output
Run 'SampleApp [command] -?|-h|--help' for more information about a command.
$ ./bin/Debug/net8.0/SampleApp.exe echo --help
display a line of text
Usage: SampleApp echo [options] <input>
Arguments:
input
Options:
-n|--newline do not output the trailing newline
-?|-h|--help Show help information.
BRAVO 很简单对吧。
2. 引用 PomeloCli 开发命令行插件
如果只是提供命令行应用的创建能力,作者大可不必发布这样一个项目,因为 McMaster.Extensions.CommandLineUtils 本身已经做得足够好了。如上文"为什么实现章节"所说,作者还希望解决命令行工具的分发维护问题。
为了实现这一目标,PomeloCli 继续基于 McMaster.NETCore.Plugins 实现了一套插件系统或者说架构:
- 将命令行工具拆分成宿主和插件两部分功能;
- 宿主负责安装、卸载、加载插件,作为命令行入口将参数转交给对应的插件;
- 插件负责具体的业务功能的实现;
- 宿主和插件均打包成标准的 nuget 制品;
插件加载示意

命令行参数传递示意

通过将宿主的维护交由 dotnet tool 处理、将插件的维护交由宿主处理,我们希望解决命令行工具的分发维护问题:
- 开发人员
- 开发插件
- 使用
dotnet nuget push发布插件
- 运维/使用人员
- 使用
dotnet tool安装、更新、卸载宿主 - 使用
pomelo-cli install/uninstall安装、更新、卸载插件
- 使用
现在现在我们来开发一个插件应用。
开发命令行插件
引用 PomeloCli 来创建自己的命令行插件
$ dotnet new classlib -n SamplePlugin
$ cd SamplePlugin
$ dotnet add package PomeloCli -v 1.3.0
我们把上文提到的 EchoCommand 和 HeadCommand 复制到该项目,再添加依赖注入文件 ServiceCollectionExtensions.cs,文件内容见于 docs/sample/4-sample-plugin/ServiceCollectionExtensions.cs
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using PomeloCli;
public static class ServiceCollectionExtensions
{
/// <summary>
/// pomelo-cli load plugin by this method, see
/// <see cref="PomeloCli.Plugins.Runtime.PluginResolver.Loading()" />
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddCommands(this IServiceCollection services)
{
return services
.AddTransient<ICommand, EchoCommand>()
.AddTransient<ICommand, HeadCommand>();
}
}
为了能够使得插件运行起来,我们还需要在打包时将依赖添加到 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 等工具使用请自行查阅。
version: "3.3"
services:
baget:
image: loicsharma/baget
container_name: baget
ports:
- "8000:80"
volumes:
- $PWD/data:/var/baget
我们使用 docker-compose up -d 将其运行起来,baget 将在地址 http://localhost:8000/ 上提供服务。
发布命令行插件
现我们在有了插件和 nuget 服务,可以发布插件了。
$ cd SamplePlugin
$ dotnet pack -o nupkgs -c Debug
$ 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
$ dotnet tool install PomeloCli.Host --version 1.3.0 -g
$ pomelo-cli --help
Usage: PomeloCli.Host [command] [options]
Options:
-?|-h|--help Show help information.
Commands:
config
plugin
version
Run 'PomeloCli.Host [command] -?|-h|--help' for more information about a command.
可以看到 pomelo-cli 内置了部分命令。
集成命令行插件
pomelo-cli 内置了一组插件,包含了其他插件的管理命令
$ pomelo-cli plugin --help
Usage: PomeloCli.Host plugin [command] [options]
Options:
-?|-h|--help Show help information.
Commands:
install
list
uninstall
Run 'plugging [command] -?|-h|--help' for more information about a command.
我们用 plugin install 命令安装刚刚发布的插件 SamplePlugin
$ pomelo-cli plugin install SamplePlugin -v 1.0.0 -s http://localhost:8000/v3/index.json
$ pomelo-cli --help
Usage: PomeloCli.Host [command] [options]
Options:
-?|-h|--help Show help information.
Commands:
config
echo display a line of text
head Print the first 10 lines of each FILE to standard output
plugin
version
Run 'PomeloCli.Host [command] -?|-h|--help' for more information about a command.
$ pomelo-cli echo --help
display a line of text
Usage: PomeloCli.Host echo [options] <input>
Arguments:
input
Options:
-n|--newline do not output the trailing newline
-?|-h|--help Show help information.
可以看到 SamplePlugin 包含的 echo 和 head 命令已经被显示在子命令列表中。
卸载命令行插件
pomelo-cli 当然也可以卸载其他插件
$ pomelo-cli plugin uninstall SamplePlugin
卸载命令行宿主
我们使用标准的 dotnet tool CLI 命令卸载 PomeloCli
$ dotnet tool uninstall PomeloCli.Host -g
4. 引用 PomeloCli 开发命令行宿主
你可能需要自己的命令行宿主,这也很容易。
$ dotnet new console -n SampleHost
$ cd SampleHost/
$ dotnet add package PomeloCli
$ dotnet add package PomeloCli.Plugins
$ dotnet build
现在你得到了一个命令宿主,你可以运行它,甚至用它安装插件
$ ./bin/Debug/net8.0/SampleHost.exe --help
Usage: SampleHost [command] [options]
Options:
-?|-h|--help Show help information.
Commands:
plugin
Run 'SampleHost [command] -?|-h|--help' for more information about a command.
$ ./bin/Debug/net8.0/SampleHost.exe plugin install SamplePlugin -v 1.0.0 -s http://localhost:8000/v3/index.json
...
$ ./bin/Debug/net8.0/SampleHost.exe --help
Usage: SampleHost [command] [options]
Options:
-?|-h|--help Show help information.
Commands:
echo display a line of text
head Print the first 10 lines of each FILE to standard output
plugin
Run 'SampleHost [command] -?|-h|--help' for more information about a command.
其他:异常 NU1102 的处理
当安装插件失败且错误码是NU1102 时,表示未找到对应版本,可以执行命令 $ dotnet nuget locals http-cache --clear 以清理 HTTP 缓存。
info : Restoring packages for C:\Users\leon\.PomeloCli.Host\Plugin.csproj...
info : GET http://localhost:8000/v3/package/sampleplugin/index.json
info : OK http://localhost:8000/v3/package/sampleplugin/index.json 2ms
error: NU1102: Unable to find package Sample Plugin with version (>= 1.1.0)
error: - Found 7 version(s) in http://localhost:8000/v3/index.json [ Nearest version: 1.0.0 ]
error: Package 'SamplePlugin' is incompatible with 'user specified' frameworks in project 'C:\Users\leon\.PomeloCli.Host\Plugin.csproj'.
其他事项
已知问题
- refit 支持存在问题
路线图
- 业务插件配置
项目仍然在开发中,欢迎与我交流想法
dotnet 命令行工具解决方案 PomeloCli的更多相关文章
- 如何创建一个基于命令行工具的跨平台的 NuGet 工具包
命令行可是跨进程通信的一种非常方便的手段呢,只需启动一个进程传入一些参数即可完成一些很复杂的任务.NuGet 为我们提供了一种自动导入 .props 和 .targets 的方法,同时还是一个 .NE ...
- 『.NET Core CLI工具文档』(一).NET Core 命令行工具(CLI)
说明:本文是个人翻译文章,由于个人水平有限,有不对的地方请大家帮忙更正. 原文:.NET Core Command Line Tools 翻译:.NET Core命令行工具 什么是 .NET Core ...
- [原创]使用命令行工具提升cocos2d-x开发效率(一)之TexturePacker篇
TexturePacker是一个常用的制作sprite sheet的工具,它提供了很多实用的功能. 一般我们制作sprite sheet都是使用他的gui版本,纯手工操作,就像下面这张图示的一样. 刚 ...
- 十分钟通过 NPM 创建一个命令行工具
大过年的,要不要写点代码压压惊?来花十分钟学一下怎么通过 NPM 构建一个命令行工具. 写了一个小 demo,用于代替 touch 的创建文件命令 touchme ,可以创建自带“佛祖保佑”注释的文件 ...
- 在Docker中安装.NET Core(使用命令行工具)
在Docker中安装.NET Core目前共有两种方法:1,使用命令行工具安装2,使用VS2017来安装 本文主要介绍使用命令行工具来安装: 1,安装Docker(如果本机已经有Docker环境,可以 ...
- vs for Mac中的启用Entity Framework Core .NET命令行工具
在vs for Mac的工具菜单中已没有了Package Manager Console. 我们可以通过以下方法使用Entity Framework Core .NET命令行工具: 1.添加Nuget ...
- node命令行工具之实现项目工程自动初始化的标准流程
一.目的 传统的前端项目初始流程一般是这样: 可以看出,传统的初始化步骤,花费的时间并不少.而且,人工操作的情况下,总有改漏的情况出现.这个缺点有时很致命. 甚至有马大哈,没有更新项目仓库地址,导致提 ...
- -Shell 命令行工具 Cmder Babun Zsh MD
目录 目录 Cmder:window 下增强型的 cmd + bash 简介 配置 解决中文乱码问题 添加到右键菜单 添加至环境变量 修改命令提示符号 自定义aliases Readme.md 设置c ...
- 2019-8-31-HttpRepl-互操作的-RESTful-HTTP-服务调试命令行工具
title author date CreateTime categories HttpRepl 互操作的 RESTful HTTP 服务调试命令行工具 lindexi 2019-08-31 16:5 ...
- HttpRepl 互操作的 RESTful HTTP 服务调试命令行工具
今天早上曽根セイラ告诉我一个好用的工具 HttpRepl 这是一个可以在命令行里面对 RESTful 的 HTTP 服务进行路由跳转和访问的命令行工具.可以使用 cd 这个命令和像文件跳转已经跳转到下 ...
随机推荐
- OpenHarmony 3.1 Release版本关键特性解析——HDI硬件设备接口介绍
HDF 驱动框架是 OpenAtom OpenHarmony(简称"OpenHarmony")系统硬件生态开放的基础,为驱动开发者提供了驱动加载.驱动服务管理和驱动消息机制等驱动框 ...
- 【直播回顾】OpenHarmony知识赋能第八期:手把手教你实现涂鸦小游戏
OpenHarmony第八期知识赋能直播已经在9月29日圆满落幕!从9月15日起,资深OS框架开发工程师巴延兴老师于每周四进行分享,通过实现涂鸦小游戏来帮助大家全面了解ArkUI框架的应用,拓宽知识 ...
- OpenHarmony有氧拳击之设备端开发
一.简介 在一个风和日丽,阳光明媚的下午,码农们都像往常一样正在专注地码代码.突然前面的小哥哥站起来,手握开发板,来回出拳.这是怎么回事? 原来这是一款拳击互动游戏,本文将带你一同解开其中的奥秘.开发 ...
- RabbitMQ 04 直连模式-Java操作
使用Java原生的方式使用RabbitMQ现在已经较少,但这是基础,还是有必要了解的. 引入依赖. <dependency> <groupId>com.rabbitmq< ...
- MogDB 2.1.1 初始化参数概要说明
MogDB 2.1.1 初始化参数概要说明 本文出处:https://www.modb.pro/db/394787 MogDB 数据库安装完成后,官方文档提供了刷新参数的脚本,推荐执行脚本来进行初始化 ...
- 解密prompt系列27. LLM对齐经验之如何降低通用能力损失
前面我们已经聊过众多指令微调的方案,这一章我们重点讨论下如何注入某一类任务或能力的同时,尽可能不损失模型原有的通用指令理解能力.因为在下游或垂直领域应用中,我们设计的推理任务风格或形式,往往很难通过p ...
- CentOS 利用pam控制ssh用户的登录及SSH安全配置
CentOS 利用pam控制ssh用户的登录 有关pam的使用,请找相关的文档.下面只说两个简单的例子. 首先在/etc/pam.d/sshd加入一句: account required ...
- 免费报表工具零代码零基础轻松搞定 web 报表
话说,能制作清单式报表的方式有千千万: 骨灰级的 Excel 控,如果能轻车熟路驾驭 VBA,也能玩出各种花来,再不济借助图表插件外援也能秒杀一众小白选手: 传说中的编程控,只要需求明确没什么做不了的 ...
- nginx重新整理——————http请求的11个阶段中的preaccess[十四]
前言 简单整理一下preaccess. 正文 主要是介绍一下上文提及到的limit_req以及limit_conn. 里面是http_limit_conn_module 默认编译进去. 生效范围: 全 ...
- jenkins 持续集成和交付 —— git hook(七)
前言 这个hook的意思叫做钩子哈,前端听得多. 正文 好吧,这个git hook 有什么用呢? 前面说了一个轮询SCM这个东西呢,我是真的觉得这东西没啥用,经常扫描仓储算怎么回事呢? 但是如果主动通 ...