Scorpio.CommandLine 0.0.4

dotnet add package Scorpio.CommandLine --version 0.0.4
                    
NuGet\Install-Package Scorpio.CommandLine -Version 0.0.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Scorpio.CommandLine" Version="0.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Scorpio.CommandLine" Version="0.0.4" />
                    
Directory.Packages.props
<PackageReference Include="Scorpio.CommandLine" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Scorpio.CommandLine --version 0.0.4
                    
#r "nuget: Scorpio.CommandLine, 0.0.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Scorpio.CommandLine@0.0.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Scorpio.CommandLine&version=0.0.4
                    
Install as a Cake Addin
#tool nuget:?package=Scorpio.CommandLine&version=0.0.4
                    
Install as a Cake Tool

Scorpio.CommandLine

一个简洁、强大的 .NET 命令行参数解析库,支持子命令、中间件、类型转换、异步操作等功能。

特性

  • ✅ 简洁的 API 设计
  • ✅ 自动参数类型转换
  • ✅ 支持必需参数和默认值
  • ✅ 支持参数别名(长/短选项)
  • ✅ 支持数组参数
  • ✅ 支持布尔标志
  • ✅ 支持子命令和多层子命令
  • ✅ 中间件系统
  • ✅ 自动生成帮助文档
  • ✅ 支持异步命令
  • ✅ 隐藏选项支持
  • ✅ .NET Standard 2.0 兼容

安装

dotnet add package Scorpio.CommandLine

或通过 NuGet 包管理器:

Install-Package Scorpio.CommandLine

快速开始

1. 基础用法

using Scorpio.CommandLine.Attributes;
using Scorpio.CommandLine.Perform;

var perform = new Perform
{
    ApplicationName = "MyApp",
    ApplicationDescription = "我的命令行应用"
};

// 添加一个简单命令
perform.AddCommand("greet", (
    [Option(Description = "用户名")] string name,
    [Option(Description = "年龄")] int age) =>
{
    Console.WriteLine($"你好, {name}! 你 {age} 岁了。");
}, "问候命令");

return perform.Start(args);

使用:

# 使用自动生成的参数名(支持单横线或双横线)
myapp greet -name 张三 -age 25
myapp greet --name 张三 --age 25

2. 必需参数和默认值

perform.AddCommand("build", (
    [Option(Required = true, Description = "输入文件")] string input,
    [Option(DefaultValue = "./output", Description = "输出目录")] string output,
    [Option(DefaultValue = "Debug", Description = "构建配置")] string configuration) =>
{
    Console.WriteLine($"构建 {input} -> {output} ({configuration})");
}, "构建项目");

使用:

# 使用默认值
myapp build -input project.csproj
# 或使用双横线
myapp build --input project.csproj

# 覆盖默认值
myapp build -input project.csproj -output ./dist -configuration Release

3. 参数别名

perform.AddCommand("serve", (
    [Option(Aliases = new[] { "-p", "--port" }, DefaultValue = "8080")] string port,
    [Option(Aliases = new[] { "-v", "--verbose" })] bool verbose) =>
{
    Console.WriteLine($"启动服务器,端口: {port}");
    if (verbose) Console.WriteLine("详细模式已启用");
}, "启动服务器");

使用:

myapp serve -p 3000 -v
# 或
myapp serve --port 3000 --verbose

4. 数组参数

perform.AddCommand("process", (
    [Option(Description = "文件列表")] string[] files,
    [Option(Description = "排除的目录")] string[] exclude) =>
{
    Console.WriteLine($"处理 {files?.Length ?? 0} 个文件");
    foreach (var file in files ?? Array.Empty<string>())
    {
        Console.WriteLine($"  - {file}");
    }
}, "处理多个文件");

使用:

# 使用自动生成的参数名
myapp process -files file1.txt file2.txt file3.txt -exclude node_modules dist
# 或使用双横线
myapp process --files file1.txt file2.txt file3.txt --exclude node_modules dist

5. 子命令

// 创建主命令
var gitCmd = perform.AddCommand("git", null, "Git 命令集");

// 添加子命令
gitCmd.AddSubCommand("clone", (
    [Option(Required = true, Aliases = new[] { "-u", "--url" })] string url,
    [Option(DefaultValue = ".")] string path) =>
{
    Console.WriteLine($"克隆仓库: {url} -> {path}");
}, "克隆远程仓库");

gitCmd.AddSubCommand("status", () =>
{
    Console.WriteLine("显示工作区状态");
}, "显示状态");

使用:

# -u 和 --url 是定义的别名
myapp git clone -u https://github.com/user/repo.git
myapp git clone --url https://github.com/user/repo.git

# -path 是自动生成的参数名
myapp git clone -u https://github.com/user/repo.git -path ./myrepo

myapp git status
myapp git --help

5.1 使用 [CommandFunc] 声明子命令(推荐用于“特性扫描注册”场景)

当你使用 Perform.AddCommandByAssembly / AddCommandByType 扫描 [CommandClass]/[CommandFunc] 自动注册命令时, 可以直接在 CommandFuncAttribute.Name 中写空格分隔的命令路径来表示子命令:

[CommandClass]
public static class Cli {
    [CommandFunc("sc git clone", "克隆仓库")]
    public static void Clone([Option(Description = "url")] string url) {
        Console.WriteLine($"clone {url}");
    }

    [CommandFunc("sc git remote add", "添加 remote")]
    public static void RemoteAdd(
        [Option(Description = "name")] string name,
        [Option(Description = "url")] string url) {
        Console.WriteLine($"remote add {name} {url}");
    }
}

上面的例子会自动形成命令树:

  • sc
    • git
      • clone
      • remote
        • add

其中 sc / git / remote 等中间节点会自动作为“分组节点”创建(handler 为 null), 并支持 --help 查看其下的子命令列表。

6. 多层子命令

var remoteCmd = perform.AddCommand("remote", null, "远程仓库管理");

// 添加二级子命令
remoteCmd.AddSubCommand("config", null, "配置管理");
var configCmd = remoteCmd.GetSubCommand("config");

// 添加三级子命令
configCmd.AddSubCommand("global", null, "全局配置");
var globalCmd = configCmd.GetSubCommand("global");

globalCmd.AddSubCommand("get", (
    [Option(Required = true, Aliases = new[] { "-k", "--key" })] string key) =>
{
    Console.WriteLine($"获取配置: {key}");
}, "获取配置项");

globalCmd.AddSubCommand("set", (
    [Option(Required = true)] string key,
    [Option(Required = true)] string value) =>
{
    Console.WriteLine($"设置配置: {key} = {value}");
}, "设置配置项");

使用:

# -k 和 --key 是定义的别名
myapp remote config global get -k user.name
myapp remote config global get --key user.name

myapp remote config global set -k user.email -v test@example.com
myapp remote config global set --key user.email --value test@example.com

7. 异步命令

perform.AddCommand("download", async (
    [Option(Required = true)] string url,
    [Option(DefaultValue = "2000")] int timeout) =>
{
    Console.WriteLine($"开始下载: {url}");
    await Task.Delay(timeout);
    Console.WriteLine("下载完成!");
}, "下载文件");

使用:

# url 和 timeout 是自动生成的参数名
myapp download -url https://example.com/file.zip
myapp download --url https://example.com/file.zip -timeout 5000

8. 中间件

// 执行前中间件
perform.UseBeforeExecute(context =>
{
    Console.WriteLine($"[执行前] 命令: {context.Command}");
    Console.WriteLine($"[执行前] 参数: {string.Join(" ", context.Args)}");
});

// 执行后中间件
perform.UseAfterExecute(context =>
{
    Console.WriteLine($"[执行后] 命令已完成: {context.Command}");
});

// 错误处理中间件
perform.UseErrorHandler(context =>
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine($"[错误] {context.Exception.Message}");
    Console.ResetColor();
    return true; // 返回 true 表示错误已处理
});

// 计时中间件
perform.UseTiming((command, elapsed) =>
{
    Console.WriteLine($"[计时] '{command}' 耗时: {elapsed.TotalMilliseconds:F2}ms");
});

9. 访问 CommandLine 对象

perform.AddCommand("advanced", (CommandLine cmd,
    [Option] string name) =>
{
    Console.WriteLine($"命令: {cmd.Command}");
    Console.WriteLine($"参数数量: {cmd.Arguments.Count}");
    Console.WriteLine($"未解析参数: {string.Join(", ", cmd.UnparsedArgs)}");

    // 手动获取参数
    var customValue = cmd.GetValue("--custom", "default");
    Console.WriteLine($"自定义参数: {customValue}");
}, "高级用法");

10. 直接使用 CommandLine 类

using Scorpio.CommandLine.Core;

var cmdLine = CommandLine.Parse(args);

// 获取命令名
string command = cmdLine.Command;

// 检查参数是否存在
if (cmdLine.HasOption("--verbose"))
{
    Console.WriteLine("详细模式");
}

// 获取参数值(带默认值)
// 注意:参数名区分大小写,要使用实际传入的格式
string name = cmdLine.GetValue("-name", "默认名称");
int count = cmdLine.GetValue<int>("-count", 10);
bool flag = cmdLine.GetValue<bool>("-flag", false);

// 也可以使用双横线格式
string name2 = cmdLine.GetValue("--name", "默认名称");

// 获取数组参数
string[] files = cmdLine.GetValues("-files");

// 添加别名
cmdLine.AddAlias("-name", "-n");
string aliasValue = cmdLine.GetValue("-n", "未设置");

// 获取未解析的参数
string[] unparsed = cmdLine.UnparsedArgs;

OptionAttribute 属性

属性 类型 说明
Required bool 是否为必需参数
Description string 参数描述(用于帮助文档)
DefaultValue object 默认值(单个值)
DefaultValues object[] 默认值(数组)
Aliases string[] 别名列表(如 new[] { "-n", "--name" })<br>注意: 如果不定义 Aliases,框架会自动生成 --{参数名}-{参数名} 两个别名
IsHidden bool 是否隐藏(不在帮助中显示)

支持的参数类型

  • string - 字符串
  • int, long, short, byte - 整数类型
  • float, double, decimal - 浮点类型
  • bool - 布尔值(标志)
  • string[], int[], double[] 等 - 数组类型
  • CommandLine - 命令行对象(自动注入)

帮助系统

框架会自动生成帮助文档:

# 显示所有命令
myapp --help
myapp -h

# 显示特定命令的帮助
myapp build --help
myapp git clone -h

# 显示子命令列表
myapp remote --help

命令格式

# 基本格式
program command --option value

# 短选项
program command -o value

# 布尔标志(不需要值)
program command --verbose

# 多值参数
program command --files file1.txt file2.txt file3.txt

# 等号格式
program command --option=value

# 子命令
program command subcommand --option value

# 组合使用
program command subcommand -o value --flag --list item1 item2

完整示例

查看 Example 目录获取完整的示例代码,包含所有功能的演示。

运行示例:

cd Example
dotnet run

或运行单个测试:

cd Example
# 使用单横线(推荐,更简洁)
dotnet run -- basic -name 张三 -age 25
# 或使用双横线
dotnet run -- basic --name 张三 --age 25

API 参考

Perform 类

主要的命令执行器。

方法:

  • AddCommand(string name, Delegate handler, string description, bool isHidden = false) - 添加命令
  • Start(string[] args) - 启动命令执行(同步)
  • StartAsync(string[] args) - 启动命令执行(异步)
  • UseBeforeExecute(Action<ExecutionContext> middleware) - 添加执行前中间件
  • UseAfterExecute(Action<ExecutionContext> middleware) - 添加执行后中间件
  • UseErrorHandler(Func<ErrorContext, bool> handler) - 添加错误处理中间件
  • UseTiming(Action<string, TimeSpan> handler) - 添加计时中间件

属性:

  • ApplicationName - 应用名称
  • ApplicationDescription - 应用描述
  • CurrentCommand - 当前执行的命令
  • CommandLine - 当前命令行对象

CommandLine 类

命令行解析结果。

静态方法:

  • Parse(string[] args) - 解析命令行参数

实例方法:

  • HasOption(string key) - 检查参数是否存在
  • GetValue<T>(string key, T defaultValue = default) - 获取参数值
  • GetValues(string key) - 获取数组参数
  • AddAlias(string option, string alias) - 添加别名

属性:

  • Command - 命令名称
  • Arguments - 所有解析的参数
  • UnparsedArgs - 未解析的参数

贡献

欢迎提交 Issue 和 Pull Request!

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.0.4 108 1/26/2026
0.0.2 99 1/23/2026
0.0.1 92 1/23/2026