Use this skill when adding, modifying, or reviewing CLI commands in a .NET project built with System.CommandLine. Triggers include: creating a new CLI command,
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-system-commandline-cli-0a5b7018345e ,按照其中的说明把「system-commandline-cli」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
You are working on a .NET CLI application built with System.CommandLine v2.x.x, targeting .NET 8 or later or any .NET Standard 2.0 implementation, including .NET Framework 4.6.1 or later and .NET Core 2.0 or later. Follow these rules and patterns strictly when creating or modifying CLI commands.
<CLI Project>/
├── Program.cs # Entry point and command invocation
└── Commands/
├── CommandBase.cs # Base class for all commands
├── GlobalOptions.cs # Defines global options for the CLI
├── RootCommand.cs # Registers top-level commands
└── <Group>/ # One folder per command group
├── <Group>Command.cs # Parent command that registers its children
└── <Group><Verb>Command.cs # Leaf command with its handler
Prefer defining a project-specific abstract CommandBase that inherits from System.CommandLine.Command. Concrete commands should inherit from this base class so shared behavior and conventions remain centralized.
internal abstract class CommandBase : Command
{
protected CommandBase(string name, string? description = null)
: base(name, description)
{
}
}
internal sealed class MyCommand : CommandBase
{
public MyCommand()
: base("command-name", "Help text shown in --help")
{
this.SetAction(CommandHandler);
}
private async Task<int> CommandHandler(
ParseResult parseResult,
CancellationToken cancellationToken)
{
// implementation
return 0;
}
}
When the project already has a command base class, preserve its established conventions. Otherwise, introduce one when commands need shared behavior; simple applications may inherit from Command directly when a base class adds no meaningful value.
private readonly Option<string> _myOption;
// In constructor:
_myOption = new Option<string>("--my-option")
{
Description = "Clear description of what this option does",
Required = true, // or false
};
_myOption.Aliases.Add("-m"); // Add a short alias
this.Options.Add(_myOption);
private readonly Argument<string> _fileArgument;
// In constructor:
_fileArgument = new Argument<string>("file")
{
Description = "Path to the input file"
};
this.Arguments.Add(_fileArgument);
// Required option/argument — use GetValue:
var value = parseResult.GetValue(_myOption);
Handlers are async methods wired via SetAction:
this.SetAction(CommandHandler);
private async Task<int> CommandHandler(ParseResult parseResult, CancellationToken cancellationToken)
{
// 1. Read option/argument values
// 2. Load session settings (if needed)
// 3. Validate configuration early — fail fast with clear error
// 4. Execute business logic
// 5. Output results with Console
return 0; // or non-zero exit code
}
A group command registers children but does not call SetAction:
internal class MyGroupCommand : CommandBase
{
public MyGroupCommand()
: base("mygroup", "Manages my-group resources")
{
this.Subcommands.Add(new MyGroupListCommand());
this.Subcommands.Add(new MyGroupCreateCommand());
this.Subcommands.Add(new MyGroupDeleteCommand());
}
}
A command may define both an action and subcommands when the direct invocation has meaningful behavior.
Top-level commands → register in RootCommand.cs:
this.Subcommands.Add(new MyGroupCommand());
Subcommands → register inside the parent command's constructor:
this.Subcommands.Add(new MyGroupCreateCommand());
Console.WriteLine("Are you sure you want to delete X? This action cannot be undone. (yes/no)");
var confirmation = Console.ReadLine();
if (confirmation?.ToLower() != "yes" && confirmation?.ToLower() != "y")
{
Console.WriteLine("Operation cancelled.");
return 0;
}
The logic of each command should be in one or more service classes that implement interfaces. The command receives interfaces through dependency injection (DI), not concrete implementations. The command handler should not contain business logic. The command handler should be thin, responsible only for:
Service class should be injected in the command constructor via DI, not instantiated directly.
Services are registered in Program.cs:
serviceCollection.TryAddSingleton<IMyService, MyServiceImpl>();
Add a convenience extension in ServiceProviderExtensions.cs:
public static IMyService GetMyService(this ServiceProvider provider)
=> provider.GetRequiredService<IMyService>();
| Element | Convention | Example |
|---|---|---|
| CLI command name | lowercase kebab-case | agent create, set show |
| Command class | PascalCase + Command suffix | AgentCreateCommand |
| Option field | _camelCaseOption (private readonly) | _projectNameOption |
| Option long name | --kebab-case | --project-name |
| Option short alias | -x (1-2 chars) | -p, -id, -md |
| Argument field | _camelCaseArgument | _fileArgument |
| Namespace | MyProject.Commands.<Group> | MyProject.Commands.Agent |
| Folder | Commands/<Group>/ | Commands/Agent/ |
internal.Define options shared by the entire command tree once in GlobalOptions.cs. Reuse the same
Option<T> instance when registering, validating, and reading the option.
internal static class GlobalOptions
{
public static readonly Option<string> EndpointOption = CreateEndpointOption();
private static Option<string> CreateEndpointOption()
{
var option = new Option<string>(...);
// add option description, aliases, and Required flag
// Add validation to the option's Validators collection
return option;
}
}
Expose repeated parsing or conversion through protected CommandBase helpers:
/// <summary>Resolves the validated endpoint from the global option.</summary>
protected Uri GetEndpoint(ParseResult parseResult)
{
var baseUrl = parseResult.GetValue(GlobalOptions.EndpointOption)!;
return new Uri(baseUrl);
}
/// <summary>Resolves the optional key from the global option.</summary>
protected string? GetKey(ParseResult parseResult)
=> parseResult.GetValue(GlobalOptions.KeyOption);
Consume those helpers from the leaf command's handler. The command must not add the global options to its own
Options collection; recursive registration on the root already makes them available in its ParseResult.
private async Task<int> CommandHandler(
ParseResult parseResult,
CancellationToken cancellationToken)
{
var endpoint = GetEndpoint(parseResult);
var key = GetKey(parseResult);
...
return 0;
}
Read a global option directly in a leaf handler only when no shared conversion or fallback logic is needed.
Always use the static GlobalOptions symbol; never create a second Option<T> with the same aliases.
Follow these requirements:
Recursive = true so the option is accepted for every descendant command.RootCommand.Options; do not duplicate it on leaf commands.parseResult.GetValue(GlobalOptions.Endpoint), preferably behind a CommandBase helper.Validators collection so invalid input becomes a parse error and
the command handler is not invoked. Do not rely on exceptions from new Uri(...) or downstream services.http or https URIs. Reject unsupported schemes,
relative URIs, query strings, and fragments because appending a fixed endpoint path would change their meaning.--key, allow omission but reject an explicitly supplied blank or
whitespace-only value. Validate the value without logging, displaying, trimming, or otherwise mutating it.When creating a new command, verify:
name, description to baseDescription, Requiredthis.SetAction(CommandHandler)async Task<int> CommandHandler(ParseResult, CancellationToken)internalCommands/<Group>/ folderMyProject.CLI.Commands.<Group>