# ScorpioCommandLine **Repository Path**: qingfeng346/ScorpioCommandLine ## Basic Information - **Project Name**: ScorpioCommandLine - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-01-23 - **Last Updated**: 2026-01-26 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Scorpio.CommandLine 一个简洁、强大的 .NET 命令行参数解析库,支持子命令、中间件、类型转换、异步操作等功能。 ## 特性 - ✅ 简洁的 API 设计 - ✅ 自动参数类型转换 - ✅ 支持必需参数和默认值 - ✅ 支持参数别名(长/短选项) - ✅ 支持数组参数 - ✅ 支持布尔标志 - ✅ 支持子命令和多层子命令 - ✅ 中间件系统 - ✅ 自动生成帮助文档 - ✅ 支持异步命令 - ✅ 隐藏选项支持 - ✅ .NET Standard 2.0 兼容 ## 安装 ```bash dotnet add package Scorpio.CommandLine ``` 或通过 NuGet 包管理器: ``` Install-Package Scorpio.CommandLine ``` ## 快速开始 ### 1. 基础用法 ```csharp 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); ``` **使用:** ```bash # 使用自动生成的参数名(支持单横线或双横线) myapp greet -name 张三 -age 25 myapp greet --name 张三 --age 25 ``` ### 2. 必需参数和默认值 ```csharp 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})"); }, "构建项目"); ``` **使用:** ```bash # 使用默认值 myapp build -input project.csproj # 或使用双横线 myapp build --input project.csproj # 覆盖默认值 myapp build -input project.csproj -output ./dist -configuration Release ``` ### 3. 参数别名 ```csharp 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("详细模式已启用"); }, "启动服务器"); ``` **使用:** ```bash myapp serve -p 3000 -v # 或 myapp serve --port 3000 --verbose ``` ### 4. 数组参数 ```csharp perform.AddCommand("process", ( [Option(Description = "文件列表")] string[] files, [Option(Description = "排除的目录")] string[] exclude) => { Console.WriteLine($"处理 {files?.Length ?? 0} 个文件"); foreach (var file in files ?? Array.Empty()) { Console.WriteLine($" - {file}"); } }, "处理多个文件"); ``` **使用:** ```bash # 使用自动生成的参数名 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. 子命令 ```csharp // 创建主命令 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("显示工作区状态"); }, "显示状态"); ``` **使用:** ```bash # -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` 中写**空格分隔的命令路径**来表示子命令: ```csharp [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. 多层子命令 ```csharp 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}"); }, "设置配置项"); ``` **使用:** ```bash # -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. 异步命令 ```csharp perform.AddCommand("download", async ( [Option(Required = true)] string url, [Option(DefaultValue = "2000")] int timeout) => { Console.WriteLine($"开始下载: {url}"); await Task.Delay(timeout); Console.WriteLine("下载完成!"); }, "下载文件"); ``` **使用:** ```bash # url 和 timeout 是自动生成的参数名 myapp download -url https://example.com/file.zip myapp download --url https://example.com/file.zip -timeout 5000 ``` ### 8. 中间件 ```csharp // 执行前中间件 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 对象 ```csharp 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 类 ```csharp 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("-count", 10); bool flag = cmdLine.GetValue("-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" }`)
**注意:** 如果不定义 Aliases,框架会自动生成 `--{参数名}` 和 `-{参数名}` 两个别名 | | `IsHidden` | bool | 是否隐藏(不在帮助中显示) | ## 支持的参数类型 - `string` - 字符串 - `int`, `long`, `short`, `byte` - 整数类型 - `float`, `double`, `decimal` - 浮点类型 - `bool` - 布尔值(标志) - `string[]`, `int[]`, `double[]` 等 - 数组类型 - `CommandLine` - 命令行对象(自动注入) ## 帮助系统 框架会自动生成帮助文档: ```bash # 显示所有命令 myapp --help myapp -h # 显示特定命令的帮助 myapp build --help myapp git clone -h # 显示子命令列表 myapp remote --help ``` ## 命令格式 ```bash # 基本格式 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](./Example) 目录获取完整的示例代码,包含所有功能的演示。 运行示例: ```bash cd Example dotnet run ``` 或运行单个测试: ```bash 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 middleware)` - 添加执行前中间件 - `UseAfterExecute(Action middleware)` - 添加执行后中间件 - `UseErrorHandler(Func handler)` - 添加错误处理中间件 - `UseTiming(Action handler)` - 添加计时中间件 **属性:** - `ApplicationName` - 应用名称 - `ApplicationDescription` - 应用描述 - `CurrentCommand` - 当前执行的命令 - `CommandLine` - 当前命令行对象 ### CommandLine 类 命令行解析结果。 **静态方法:** - `Parse(string[] args)` - 解析命令行参数 **实例方法:** - `HasOption(string key)` - 检查参数是否存在 - `GetValue(string key, T defaultValue = default)` - 获取参数值 - `GetValues(string key)` - 获取数组参数 - `AddAlias(string option, string alias)` - 添加别名 **属性:** - `Command` - 命令名称 - `Arguments` - 所有解析的参数 - `UnparsedArgs` - 未解析的参数 ## 贡献 欢迎提交 Issue 和 Pull Request!