Port a .NET CLI from System.CommandLine (2.0 or any 2.0 beta, including SetHandler/InvocationContext/CommandLineBuilder, NamingConventionBinder, Hosting, DragonFruit) to TimeWarp.Nuru. Use when asked to migrate, port, or convert a System.CommandLine app to Nuru, to make a System.CommandLine CLI Native AOT or trim clean, or to map RootCommand/Command/Option<T>/Argument<T>/SetAction to Nuru routes.
Maintained in timewarp-nuru · Canonical file: SKILL.md
Install
With TimeWarp.Skills:
dnx TimeWarp.Skills -- add tw-nuru-migrate-system-commandline https://timewarp.software/
Add a harness target and skills sync (see the TimeWarp.Skills page). Or copy the SKILL.md into your agent's skills directory.
Port a System.CommandLine CLI to TimeWarp.Nuru
The full explanation, with the reasons and the long tables, is the docs page
Migrating from System.CommandLine
(online: https://github.com/TimeWarpEngineering/timewarp-nuru/blob/master/documentation/user/guides/migrating-from-system-commandline.md).
This skill is the recipe. Load the tw-nuru skill too for general Nuru syntax.
Follow the steps in order. When a step does not say how to do something you need, do not guess silently: write it down as an invented step in your report, so the page and this skill can be fixed.
Step 0: Inventory
Before you edit anything, list:
- Every
System.CommandLine*package reference and its version. A version below2.0.0-beta5means beta4 APIs (SetHandler,InvocationContext,CommandLineBuilder). - Every
RootCommandandCommand, with its options, arguments, aliases, defaults,Required/IsRequired,Recursive/AddGlobalOption, validators, andAcceptOnlyFromAmong/FromAmong. - How the action reads values (
GetValue,SetHandlervalue descriptors, a customBinderBase<T>, orCommandHandler.Createby name). - How it sets the exit code and handles exceptions.
- Passthrough (
--,TreatUnmatchedTokensAsErrors = false,UnmatchedTokens) and free-form trailing items (key=value,Header:value). - Verbosity and configuration (
UseHost,IConfiguration, a--verbosityoption,ILogger). - The project's target frameworks,
PackAsTool,PublishAot,IsAotCompatible, andTreatWarningsAsErrors. - Existing tests that call the parser (
root.Parse(...),InvokeAsync(...)). They need porting too.
Run the old CLI's --help for each command and save the output. You compare against it at the end.
Step 1: Project file
<TargetFramework>net11.0</TargetFramework>. Nuru 4.0 shipslib/net11.0only. Drop older targets from every project that references Nuru (the CLI and its tests). Libraries that do not reference Nuru can keep their targets.- Under
TreatWarningsAsErrors, retarget the library projects the CLI references too: Nuru's 11.0Microsoft.Extensions.*packages warn in theirnet8.0/net9.0builds. - If
global.jsonpins an older SDK, setsdk.versionto an installed .NET 11 SDK. Repos versioned by Nerdbank.GitVersioning need full history (git fetch --unshallow) to build. GeneratePackageOnBuildbreaks an AOT publish. Make itCondition="'$(PublishAot)' != 'true'".- Add
<PackageReference Include="TimeWarp.Nuru" Version="4.0.0-beta.14" />(or the latest 4.0 beta). Central package management: add the version toDirectory.Packages.props. - Remove
System.CommandLine,System.CommandLine.NamingConventionBinder,System.CommandLine.Hosting,System.CommandLine.DragonFruit,System.CommandLine.Rendering. - Do not add
Microsoft.Extensions.Logging.Console,Microsoft.Extensions.Configuration*, orMicrosoft.Extensions.Options.ConfigurationExtensionsat a lower version. Nuru brings the 11.0 versions, and a lower direct reference fails restore withNU1605(package downgrade). - AOT:
<PublishAot>true</PublishAot>, and<EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>when the code callsconfiguration.Get<T>()orBind(). - Global tool: keep
PackAsToolandToolCommandName. Add<RollForward>Major</RollForward>if it is not there. - The TimeWarp build tasks print a
Failed to retrieve git metadatawarning outside a git repository. Build inside the repo clone.
Step 2: Entry point
Replace the RootCommand setup and Parse(args).Invoke() with:
using TimeWarp.Nuru;
NuruApp app = NuruApp.CreateBuilder()
.WithDescription("One line about the tool")
.DiscoverEndpoints()
.Build();
return await app.RunAsync(args);
.WithDescription(...) takes a plain or raw string literal only. An interpolated string compiles but
prints an empty description.
Program.cs must use top-level statements or an async Task<int> Main (update tests that call Main).
Keep RunAsync on an app you built in the same method (NURU_I001 warns otherwise).
Step 3: One endpoint class per command
| System.CommandLine | Nuru |
|---|---|
RootCommand action |
[NuruRoute("")] class |
Command("name") |
[NuruRoute("name", Description = "...")] class |
Subcommand of parent |
Class inherits an abstract [NuruRouteGroup("parent")] base |
Aliases.Add("x") on a command |
[NuruRouteAlias("x")] |
Argument<T> required |
[Parameter] public T Name { get; set; } (non-nullable) |
Argument<T?> optional |
[Parameter] public T? Name { get; set; } |
| optional argument with a default | nullable property, default applied in the handler (?? "x") |
optional argument before a required one ([method] url) |
one catch-all, classify tokens in the handler |
Argument<T[]> |
[Parameter(IsCatchAll = true)] public string[] Items { get; set; } = []; (last) |
| several arguments | one [Parameter] property each, with Order (0, 1, 2, ...). NURU_A002 is an error when two or more omit it. One parameter may omit Order. A catch-all stays last |
Option<T>("--name", "-n") |
[Option("name", "n")] (no dashes) |
extra long aliases (--offline, --dry-run) |
one [Option] takes one long + one short (the short may be multi-char: "cs" → -cs); add a property per extra long name and OR them, or rewrite aliases in argv before RunAsync |
an existing -h option |
loses -h (reserved for help); keep the long form |
Option<bool> |
bool property: a flag (absent = false). Presence is true. The next token stays a positional, even when it looks like a boolean (--verbose 0) |
Option<bool> defaulting to true |
[Option("create")] public bool Create { get; set; } = true; (absence stays true; --create false binds false). A bare --create is Unknown command, exit 1 |
--flag true / --flag false |
the next token is not the flag's value. --flag=true is an unknown option |
| default value | property initializer. It applies when the option is absent. A bare -o on a required value is Unknown command, exit 1 |
Required = true / IsRequired |
nullable property + check in handler (no attribute) |
Option<T[]>, AllowMultipleArgumentsPerToken |
[Option("x")] public string[] X { get; set; } = [];. --x a b binds both. IsRepeated = true on a scalar is NURU_A004 |
AcceptOnlyFromAmong / FromAmong |
an enum property, or a handler check |
Validators.Add / AddValidator |
handler check |
Recursive = true / AddGlobalOption |
[GroupOption("name", "n")] on the group base |
| options shared by top-level sibling commands | abstract base with [NuruRouteGroup("")] + [GroupOption] properties |
SetAction / SetHandler body |
nested public sealed class Handler : IRequestHandler<TEndpoint, Unit> |
GetValue(option) |
command.Property |
IConsole / context.Console |
inject ITerminal (using TimeWarp.Terminal;) |
System.CommandLine.Rendering |
TimeWarp.Terminal colors/widgets, or keep the existing output library (Spectre works) |
CancellationToken |
Handle(..., CancellationToken cancellationToken) |
Template:
using TimeWarp.Mediator;
using TimeWarp.Nuru;
using TimeWarp.Terminal;
[NuruRoute("deploy", Description = "Deploy the app")]
public sealed class DeployCommand : ICommand<Unit>
{
[Parameter(Description = "Target environment")]
public string Environment { get; set; } = string.Empty;
[Option("tag", "t", Description = "Image tag")]
public string? Tag { get; set; }
[Option("replicas", Description = "Replica count")]
public int Replicas { get; set; } = 1;
public sealed class Handler(ITerminal terminal) : IRequestHandler<DeployCommand, Unit>
{
public ValueTask<Unit> Handle(DeployCommand command, CancellationToken cancellationToken)
{
// old action body; on failure:
// terminal.WriteErrorLine("..."); System.Environment.ExitCode = 1;
terminal.WriteLine($"Deploying {command.Tag ?? "latest"} to {command.Environment}");
return Unit.ValueTask;
}
}
}
Rules:
- Endpoint and
Handleraresealed, and eitherpublicorinternal. Useinternalwhen the handler takes aninternalservice (CS0051otherwise).[NuruRoute]takes one literal or"", never a pattern. - A plain
[Option]on a base class without[NuruRouteGroup]is silently ignored (the option becomesUnknown option). Shared options go on a[NuruRouteGroup]base as[GroupOption]; use[NuruRouteGroup("")]for no prefix. Astring[][GroupOption]repeats like astring[][Option]. - An enum cannot hold a hyphenated choice (
dotnet-coverage). Usestringand check it in the handler. - A property may be named
Type, or another C# keyword. Generated locals escape it as a whole identifier (@type). Enum option types may share a simple name across namespaces; generated code uses the fully qualified name. A name you write yourself (public Modewhile both namespaces are imported) is still your source's ambiguity. On 4.0.0-beta.14 a property namedTypefailed to compile, and two same-named enums wereCS0104in generated code. Fixed in task 591-006. - Under strict analyzers (
AnalysisMode=AllEnabledByDefault), make endpointsinternal sealedto avoid CA1515/CA1034/CS1591 on generated-facing public types. - The
Handleparameter is namedrequestinIRequestHandler. Repos with Roslynator (RCS1168) want that name. HandlereturnsValueTask<T>:return Unit.ValueTask;from a synchronous body,return Unit.Value;from anasyncone. UseICommand<Unit>(side effects),IQuery<Unit>(read-only), orIIdempotentCommand<Unit>. These live inTimeWarp.Mediator.- A property named like a type in scope (
Environment) shadows it. WriteSystem.Environment.ExitCode. - An endpoint property of type
FileInfo,DirectoryInfo, orIPAddressbinds from the argument string (FileInfoandDirectoryInfotake the path;IPAddressusesIPAddress.TryParse). Endpoint properties also bindstring, the numeric types,bool,char,Guid,DateTime,DateTimeOffset,TimeSpan,DateOnly,TimeOnly,BigInteger,Uri,Version, and enums. On 4.0.0-beta.14 those three properties did not bind; bindstringand convert in the handler on that package. - Keep business logic where it was. Move only the parsing and wiring.
- The builder must be one literal chain in one method. A ternary or helper around part of the chain fails
with
NURU_S999.
Step 4: Exit codes and errors
return 2;from an action →System.Environment.ExitCode = 2; return Unit.ValueTask;in the synchronous Step 3 template (return Unit.Value;only in anasyncHandle). A returnedintis printed, not used as the exit code.context.ExitCode = n(beta4) → same.RunAsyncwrites a handler exception's message to stderr and returns 1 (the oldEnableDefaultExceptionHandler/UseExceptionHandler). It does not print the stack trace.OptionsValidationExceptionstill propagates.ExecuteAsyncandInvokeAsyncstill let exceptions propagate, so a host can catch them. On 4.0.0-beta.14 a handler exception aborted the process (exit 134 on Linux) unlessProgram.cscaught it. Fixed in task 591-005.- Required options:
if (command.X is null) { terminal.WriteErrorLine("Option '--x' is required."); System.Environment.ExitCode = 1; return Unit.ValueTask; }
Step 5: Passthrough and free-form tails
--passthrough andUnmatchedTokens→[Parameter(IsCatchAll = true)] public string[] Args { get; set; } = [];as the last declared parameter property.- Before
--, an undeclared-xor--nametoken is an error (Unknown option). After--, it goes into the catch-all. Nuru removes the--itself. Add it back if the child program needs it. - Free-form items (
key=value,key:=1,Header:value) arrive unchanged in the catch-all. Classify them in the handler. Declared options can sit between them. - Tokens after
--are never removed or taken as configuration, so/p:Configuration=Releaseand--verbosity=quietforward through a catch-all unchanged. - Before
--,--name=valueand--name:valuebind a declared long option (value = everything after the first=or:). Undeclared names (--Section:Key=v) and every slash form (/Mode=fast, declared or not) are still configuration overrides.-o=valuebinds a declared short value option. Before the release after 4.0.0-beta.14,--name=valuenever bound. - Users rely on a legacy alias with
=(--old=value)? An undeclared alias is taken as configuration. Rewrite argv inProgram.csbeforeRunAsync: turn the alias into the canonical name. Stop at--and copy it and the tail unchanged. Example: Option syntax. - Split at
--first when the tool takes variable items before--and forwards items after it (a single catch-all cannot tell them apart):
// Program.cs, before CreateBuilder (the class goes after the top-level statements)
int separator = Array.IndexOf(args, "--");
if (separator >= 0)
{
Passthrough.Arguments = args[(separator + 1)..];
args = args[..separator];
}
internal static class Passthrough { public static string[] Arguments { get; set; } = []; }
The handler forwards Passthrough.Arguments. The route's catch-all then holds only the items before --.
Step 6: Configuration and verbosity
- A tool that builds its own
ServiceCollectioncan keep it: store theIServiceProviderin a static and resolve in handlers, or move registrations intoConfigureServiceswith.UseMicrosoftDependencyInjection(). UseHost(...)→.ConfigureServices(services => ...)on the builder (using Microsoft.Extensions.DependencyInjection;). Register services withAddSingleton/AddScoped/AddTransient. Factory lambdas need.UseMicrosoftDependencyInjection().- Configuration: inject
IOptions<T>orIConfigurationinto theHandlerconstructor.IOptions<DatabaseOptions>binds theDatabasesection (a trailingOptionsis removed);[ConfigurationKey("Api")]selects the section. AnIValidateOptions<T>in the project runs when the value is created.services.Configure<T>(...)reportsNURU052and does nothing under source-generated DI. Call.UseMicrosoftDependencyInjection()forConfigure, data annotations,IOptionsSnapshot<T>, orIOptionsMonitor<T>.IConfigurationstill works:configuration.GetSection("X").Get<XOptions>(). - Sources:
appsettings.json,{app}.settings.json, environment variables (no prefix),--Section:Key=value. - Verbosity: the
AddLogginglambda is compiled, soSetMinimumLevel(fromArgs)cannot work. Use a runtime filter:
.ConfigureServices(services => services.AddLogging(logging => logging
.AddConsole(options => options.LogToStandardErrorThreshold = LogLevel.Trace)
.SetMinimumLevel(LogLevel.Trace)
.AddFilter((category, level) => level >= Verbosity.Minimum)))
public static class Verbosity { public static LogLevel Minimum { get; set; } = LogLevel.Warning; }
Then put [GroupOption("verbosity", "v")] public LogLevel? Level { get; set; } on the group base (or an
[Option] per endpoint), and set Verbosity.Minimum at the top of each handler, or once in a pipeline
behavior.
Step 7: Output
JsonSerializer.Serialize(result)→ return a named record or class from the handler (ICommand<MyResult>). Nuru writes it as JSON with a generated context. An anonymous type printsToString().- Keep your own
JsonSerializercalls only with aJsonSerializerContext(AOT). - Logs to stderr, results to stdout.
Step 8: Tests
Port parser tests to run the app with a TestTerminal:
using TestTerminal terminal = new();
NuruApp app = NuruApp.CreateBuilder().UseTerminal(terminal).Map<DeployCommand>().Build();
int exitCode = await app.RunAsync(["deploy", "prod", "--tag", "v1"]);
Use Map<T>(), not DiscoverEndpoints(), in a test assembly that builds several apps (NURU_A003).
Separate test project (the usual layout). An app built in the test assembly fails with
NoHandlerException, and the test project gets CS0436 (both assemblies generate a Mediator type). Do this:
- In the CLI project, add
internal static class CliAppwithinternal static async Task<int> RunAsync(string[] args, ITerminal? terminal = null)that builds the app (two literal chains: with and without.UseTerminal(terminal)).Program.cscalls it. InternalsVisibleTothe test project. Tests callCliApp.RunAsync([...], terminal).- Keep the generators out of the test project:
PrivateAssets="analyzers;build"on the CLI project'sTimeWarp.NuruPackageReference. Exactly that value:allbreaks the AOT binary (TimeWarp.Nurunot loaded), and addingcompilebreaks Mediator contract use. IfCS0436remains, remove the analyzer in the test project:
<Target Name="RemoveTransitiveMediatorGenerator" BeforeTargets="CoreCompile;GenerateMSBuildEditorConfigFileCore">
<ItemGroup>
<Analyzer Remove="@(Analyzer)" Condition="$([System.String]::Copy('%(Filename)').StartsWith('TimeWarp.Mediator.Generators'))" />
</ItemGroup>
</Target>
- Reset
Environment.ExitCode = 0before each exit-code assertion (it is process-wide). Errors written withConsole.Errorare not captured byTestTerminal; move them toITerminalif tests assert them. ConfigureServiceslambdas are compiled, so tests cannot inject substitutes. Expose the services tests replace as settable statics that the registration or handler reads.
Full example: Tests.
Step 9: Verify
dotnet buildwith zero warnings (keep the repo'sTreatWarningsAsErrors).- Every command's
--helpagainst the Step 0 output. Root--helplists the default route's parameters, options, and examples. A default route with only a description still shows that description underCommands:with a blank name. - The old tests, ported, pass.
- Run each command with the arguments from the tool's readme. Check that
--name=valueexamples bind declared options and that--flag=trueon a bool flag is not used. - AOT:
dotnet publish -c Release -r linux-x64(withPublishAot; add-f net11.0if the project uses plural<TargetFrameworks>). Expect zeroIL2xxx/IL3xxxwarnings from Nuru. Fix new warnings in the code. Do not suppress them. Warnings from other dependencies (Dapper, Roslyn scripting) stay theirs. - Tool:
dotnet pack -c Release -o ./artifacts, thendotnet tool install --tool-path ./tool-test --add-source ./artifacts <PackageId> --prerelease, then./tool-test/<command> --help. Run it from a folder with no project file. If a private feed innuget.configreturns401, use--source ./artifactsinstead of--add-source.
Behavior differences to tell the user about
--flag=trueon a bool flag is an unknown-option error (Unknown option '--verbose=true'), exit 1. A following token is not the flag's value, so--verbose 0keeps0as a positional. A bool initializer= truestays true when the flag is absent. A bare--createon that option isUnknown command, exit 1 (System.CommandLine binds the bare flag as true).- Extra positional arguments are
Unknown command, exit 1, unless the route has a catch-all. A repeated option takes every following value (--env A Bbinds both) and swallows a following optional positional. A required positional keeps the trailing values it still needs. When a catch-all follows and the route has no--before it, a string or enum repeated option (or any other element with no built-in conversion) takes one value per flag (--env A=1 nginx echo hibinds the env value, then the image, then the command). Repeat the flag for more values, or put--before the catch-all. A repeated option whose element has a built-in conversion still takes every token that converts. - Help is a table about 80 columns wide: long names truncated, no defaults, no
(REQUIRED), no enum choices. - Parse and argument errors go to stderr. On 4.0.0-beta.14 some of them printed to stdout. Fixed in task 591-005.
- A user option named
versionbinds--version 1.2; bare--versionis the built-in. - Ctrl+C cancels the handler's
CancellationToken. If the handler is still running afterProcessTerminationTimeout(two seconds by default), the process exits 130. SIGTERM exits 143.nullturns that off. The REPL still cancels only the current command. On 4.0.0-beta.14 Ctrl+C ended the process and did not cancel the token. Fixed in task 591-005. - A handler exception in
RunAsyncprints the message to stderr and returns 1.OptionsValidationExceptionstill propagates. On 4.0.0-beta.14 the process aborted unlessProgram.cscaught the exception. Fixed in task 591-005. -owith no value, when the value is required, isUnknown command, exit 1. The initializer applies only when the option is absent. A nullable value still binds null.- No
-?, no bundled short options (-vo), option names case-sensitive,-his help. --help,-h,--version,--capabilities,--json-argsare reserved.- A property named
Type, and two enums with the same simple name in different namespaces, compile. On 4.0.0-beta.14 the property emitted@type_0and failed to compile, and the enums wereCS0104in generated code. Fixed in task 591-006. A name you write yourself can still be ambiguous. - An endpoint property of type
FileInfo,DirectoryInfo, orIPAddressbinds. On 4.0.0-beta.14 it did not. Fixed in task 591-007.
Details and examples: Behavior differences to check.
Report
End a port with:
- What was ported, what was left out and why.
- Gate results (build, tests,
--helpcomparison, AOT publish warnings count, tool pack/install). - Invented steps: anything this skill or the docs page did not tell you how to do.
- Behavior differences the tool's users will see.