System.CommandLine CLI Developer

System.CommandLine CLI Developer

Teaches an agent the rules and patterns for adding and reviewing commands in a .NET CLI built with System.CommandLine, including base classes, options, handlers and command groups.

Skill files1 file
SKILL.md318 lines
1
---
2
name: system-commandline-cli
3
description: "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, adding options or arguments, wiring command handlers, registering subcommands, building command groups, or any architecture decision about CLI command structure. Also use when the user mentions 'System.CommandLine', 'CommandBase', 'SetAction', 'ParseResult', 'RootCommand', 'subcommand', or asks to add a verb to the CLI. Do NOT use for general C# coding, web APIs, UI work, or non-CLI projects."
4
---
5
6
# System.CommandLine CLI Developer Skill
7
8
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**.
9
Follow these rules and patterns strictly when creating or modifying CLI commands.
10
11
---
12
13
## Architecture Overview
14
15
```
16
<CLI Project>/
17
├── Program.cs # Entry point and command invocation
18
└── Commands/
19
├── CommandBase.cs # Base class for all commands
20
├── GlobalOptions.cs # Defines global options for the CLI
21
├── RootCommand.cs # Registers top-level commands
22
└── <Group>/ # One folder per command group
23
├── <Group>Command.cs # Parent command that registers its children
24
└── <Group><Verb>Command.cs # Leaf command with its handler
25
```
26
27
28
---
29
30
## RULE 1 — Prefer a Project-Specific Command Base Class
31
32
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.
33
34
```csharp
35
internal abstract class CommandBase : Command
36
{
37
protected CommandBase(string name, string? description = null)
38
: base(name, description)
39
{
40
}
41
}
42
43
internal sealed class MyCommand : CommandBase
44
{
45
public MyCommand()
46
: base("command-name", "Help text shown in --help")
47
{
48
this.SetAction(CommandHandler);
49
}
50
51
private async Task<int> CommandHandler(
52
ParseResult parseResult,
53
CancellationToken cancellationToken)
54
{
55
// implementation
56
return 0;
57
}
58
}
59
```
60
61
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.
62
63
---
64
65
## RULE 2 — Options and Arguments
66
67
### Defining Options
68
69
```csharp
70
private readonly Option<string> _myOption;
71
72
// In constructor:
73
_myOption = new Option<string>("--my-option")
74
{
75
Description = "Clear description of what this option does",
76
Required = true, // or false
77
};
78
_myOption.Aliases.Add("-m"); // Add a short alias
79
this.Options.Add(_myOption);
80
```
81
82
### Defining Arguments (positional)
83
84
```csharp
85
private readonly Argument<string> _fileArgument;
86
87
// In constructor:
88
_fileArgument = new Argument<string>("file")
89
{
90
Description = "Path to the input file"
91
};
92
this.Arguments.Add(_fileArgument);
93
```
94
95
### Reading Values in Handlers
96
97
```csharp
98
// Required option/argument — use GetValue:
99
var value = parseResult.GetValue(_myOption);
100
```
101
102
---
103
104
## RULE 3 — Command Handler Pattern
105
106
Handlers are **async methods** wired via `SetAction`:
107
108
```csharp
109
this.SetAction(CommandHandler);
110
111
private async Task<int> CommandHandler(ParseResult parseResult, CancellationToken cancellationToken)
112
{
113
// 1. Read option/argument values
114
// 2. Load session settings (if needed)
115
// 3. Validate configuration early — fail fast with clear error
116
// 4. Execute business logic
117
// 5. Output results with Console
118
119
return 0; // or non-zero exit code
120
}
121
```
122
123
---
124
125
## RULE 4 — Command Group (Parent with Subcommands)
126
127
A **group command** registers children but does **not** call `SetAction`:
128
129
```csharp
130
internal class MyGroupCommand : CommandBase
131
{
132
public MyGroupCommand()
133
: base("mygroup", "Manages my-group resources")
134
{
135
this.Subcommands.Add(new MyGroupListCommand());
136
this.Subcommands.Add(new MyGroupCreateCommand());
137
this.Subcommands.Add(new MyGroupDeleteCommand());
138
}
139
}
140
```
141
142
A command may define both an action and subcommands when the direct invocation has meaningful behavior.
143
144
---
145
146
## RULE 5 — Registration
147
148
- **Top-level commands** → register in `RootCommand.cs`:
149
```csharp
150
this.Subcommands.Add(new MyGroupCommand());
151
```
152
153
- **Subcommands** → register inside the parent command's constructor:
154
```csharp
155
this.Subcommands.Add(new MyGroupCreateCommand());
156
```
157
158
---
159
160
## RULE 6 — User Confirmation for Destructive Operations
161
162
```csharp
163
Console.WriteLine("Are you sure you want to delete X? This action cannot be undone. (yes/no)");
164
var confirmation = Console.ReadLine();
165
if (confirmation?.ToLower() != "yes" && confirmation?.ToLower() != "y")
166
{
167
Console.WriteLine("Operation cancelled.");
168
return 0;
169
}
170
```
171
172
---
173
174
## RULE 7 — Command Logic
175
176
The logic of each command should be in one or more **service classes** that implement interfaces.
177
The command receives interfaces through **dependency injection (DI)**, not concrete implementations.
178
The command handler should not contain business logic.
179
The command handler should be thin, responsible only for:
180
1. Parsing input
181
2. Validating configuration
182
3. Calling the service method
183
4. Outputting results
184
185
Service class should be injected in the command constructor via DI, not instantiated directly.
186
187
---
188
189
## RULE 8 — Dependency Injection
190
191
Services are registered in `Program.cs`:
192
193
```csharp
194
serviceCollection.TryAddSingleton<IMyService, MyServiceImpl>();
195
```
196
197
Add a convenience extension in `ServiceProviderExtensions.cs`:
198
199
```csharp
200
public static IMyService GetMyService(this ServiceProvider provider)
201
=> provider.GetRequiredService<IMyService>();
202
```
203
204
---
205
206
## RULE 9 — Naming Conventions
207
208
| Element | Convention | Example |
209
|---------|-----------|---------|
210
| CLI command name | lowercase kebab-case | `agent create`, `set show` |
211
| Command class | PascalCase + `Command` suffix | `AgentCreateCommand` |
212
| Option field | `_camelCaseOption` (private readonly) | `_projectNameOption` |
213
| Option long name | `--kebab-case` | `--project-name` |
214
| Option short alias | `-x` (1-2 chars) | `-p`, `-id`, `-md` |
215
| Argument field | `_camelCaseArgument` | `_fileArgument` |
216
| Namespace | `MyProject.Commands.<Group>` | `MyProject.Commands.Agent` |
217
| Folder | `Commands/<Group>/` | `Commands/Agent/` |
218
219
---
220
221
## RULE 10 — Visibility
222
223
- All command classes are `internal`.
224
225
---
226
227
## RULE 11 — Global Options and Validation
228
229
Define options shared by the entire command tree once in `GlobalOptions.cs`. Reuse the same
230
`Option<T>` instance when registering, validating, and reading the option.
231
232
```csharp
233
internal static class GlobalOptions
234
{
235
public static readonly Option<string> EndpointOption = CreateEndpointOption();
236
237
private static Option<string> CreateEndpointOption()
238
{
239
var option = new Option<string>(...);
240
241
// add option description, aliases, and Required flag
242
// Add validation to the option's Validators collection
243
244
return option;
245
}
246
}
247
```
248
249
### Using Global Options in a Command
250
251
Expose repeated parsing or conversion through protected `CommandBase` helpers:
252
253
```csharp
254
/// <summary>Resolves the validated endpoint from the global option.</summary>
255
protected Uri GetEndpoint(ParseResult parseResult)
256
{
257
var baseUrl = parseResult.GetValue(GlobalOptions.EndpointOption)!;
258
return new Uri(baseUrl);
259
}
260
261
/// <summary>Resolves the optional key from the global option.</summary>
262
protected string? GetKey(ParseResult parseResult)
263
=> parseResult.GetValue(GlobalOptions.KeyOption);
264
```
265
266
Consume those helpers from the leaf command's handler. The command must not add the global options to its own
267
`Options` collection; recursive registration on the root already makes them available in its `ParseResult`.
268
269
```csharp
270
private async Task<int> CommandHandler(
271
ParseResult parseResult,
272
CancellationToken cancellationToken)
273
{
274
var endpoint = GetEndpoint(parseResult);
275
var key = GetKey(parseResult);
276
277
...
278
279
return 0;
280
}
281
```
282
283
Read a global option directly in a leaf handler only when no shared conversion or fallback logic is needed.
284
Always use the static `GlobalOptions` symbol; never create a second `Option<T>` with the same aliases.
285
286
Follow these requirements:
287
288
1. Set `Recursive = true` so the option is accepted for every descendant command.
289
2. Add each global option exactly once to `RootCommand.Options`; do not duplicate it on leaf commands.
290
3. Read values through the shared symbol, for example
291
`parseResult.GetValue(GlobalOptions.Endpoint)`, preferably behind a `CommandBase` helper.
292
4. Add validation to the option's `Validators` collection so invalid input becomes a parse error and
293
the command handler is not invoked. Do not rely on exceptions from `new Uri(...)` or downstream services.
294
5. Validate endpoint options as nonblank absolute `http` or `https` URIs. Reject unsupported schemes,
295
relative URIs, query strings, and fragments because appending a fixed endpoint path would change their meaning.
296
6. For optional secret options such as `--key`, allow omission but reject an explicitly supplied blank or
297
whitespace-only value. Validate the value without logging, displaying, trimming, or otherwise mutating it.
298
7. Keep validation separate from derivation.
299
8. Use stable, actionable validation messages that name the option and the accepted format.
300
9. Test global options through the root parser, including the default, explicit valid values, invalid values,
301
and placement before and after a representative subcommand. Verify invalid input prevents handler execution.
302
303
---
304
305
## RULE 12 — Checklist for New Commands
306
307
When creating a new command, verify:
308
309
1. ✅ Inherits from the project’s command base class when one exists or provides meaningful shared behavior
310
2. ✅ Constructor passes `name`, `description` to base
311
3. ✅ All options have `Description`, `Required`
312
4. ✅ Handler wired via `this.SetAction(CommandHandler)`
313
5. ✅ Handler signature: `async Task<int> CommandHandler(ParseResult, CancellationToken)`
314
6. ✅ Command registered in parent (RootCommand or group command)
315
7. ✅ Class is `internal`
316
8. ✅ File placed in `Commands/<Group>/` folder
317
9. ✅ Namespace matches folder: `MyProject.CLI.Commands.<Group>`
318

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 6,373 prompts

More by @OpenSourceBuffGuy

See all
Website Clone Architect prompt image

Website Clone Architect

Reverse-engineers a website section by section, writes component specs, and hands them to parallel builder agents in git worktrees to rebuild it.

agent-skill, orchestrator, parallel-agents, multi-agent, plan-then-execute, web-development, frontend, codebase-analysis, scaffolding, css, html, nextjs, typescript, git, mcp, claude-code, for-developers, for-designers, long-form, advanced, technical-spec, task-decomposition, structured-output, design-systems, ui-ux, tool-use, checklist, report, vibe-coding

Italian Terrace Cafe Candid Portrait prompt image

Italian Terrace Cafe Candid Portrait

Generates a photorealistic candid shot of a woman in a white corset dress laughing at a sunny hotel terrace cafe, written as detailed JSON.

image-prompt, json-prompt, structured-output, photorealistic, portrait, woman, candid, fashion, cottagecore, natural-light, golden-hour, bokeh, summer, travel, cityscape, mountains, medium-shot, vibrant-colors, for-photographers, nano-banana, fashion-shoot, luxury

Night Street Photo With Leashed Cat prompt image

Night Street Photo With Leashed Cat

Generates a flash-lit night street photo of a blonde woman in a retro track jacket walking a hissing tabby cat on a leash.

image-prompt, json-prompt, nano-banana, structured-output, portrait, woman, animals, pet-portrait, night-scene, street-photography, candid, editorial, fashion, dramatic-lighting, photorealistic, vertical-format, medium-shot, graffiti, for-photographers, for-content-creators

1 view

Reviews

Loading reviews…

Discussion

Loading comments…