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:

  1. Every System.CommandLine* package reference and its version. A version below 2.0.0-beta5 means beta4 APIs (SetHandler, InvocationContext, CommandLineBuilder).
  2. Every RootCommand and Command, with its options, arguments, aliases, defaults, Required/IsRequired, Recursive/AddGlobalOption, validators, and AcceptOnlyFromAmong/FromAmong.
  3. How the action reads values (GetValue, SetHandler value descriptors, a custom BinderBase<T>, or CommandHandler.Create by name).
  4. How it sets the exit code and handles exceptions.
  5. Passthrough (--, TreatUnmatchedTokensAsErrors = false, UnmatchedTokens) and free-form trailing items (key=value, Header:value).
  6. Verbosity and configuration (UseHost, IConfiguration, a --verbosity option, ILogger).
  7. The project's target frameworks, PackAsTool, PublishAot, IsAotCompatible, and TreatWarningsAsErrors.
  8. 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

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:

Step 4: Exit codes and errors

Step 5: Passthrough and free-form tails

// 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

.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

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:

  1. In the CLI project, add internal static class CliApp with internal static async Task<int> RunAsync(string[] args, ITerminal? terminal = null) that builds the app (two literal chains: with and without .UseTerminal(terminal)). Program.cs calls it.
  2. InternalsVisibleTo the test project. Tests call CliApp.RunAsync([...], terminal).
  3. Keep the generators out of the test project: PrivateAssets="analyzers;build" on the CLI project's TimeWarp.Nuru PackageReference. Exactly that value: all breaks the AOT binary (TimeWarp.Nuru not loaded), and adding compile breaks Mediator contract use. If CS0436 remains, 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>
  1. Reset Environment.ExitCode = 0 before each exit-code assertion (it is process-wide). Errors written with Console.Error are not captured by TestTerminal; move them to ITerminal if tests assert them.
  2. ConfigureServices lambdas 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

  1. dotnet build with zero warnings (keep the repo's TreatWarningsAsErrors).
  2. Every command's --help against the Step 0 output. Root --help lists the default route's parameters, options, and examples. A default route with only a description still shows that description under Commands: with a blank name.
  3. The old tests, ported, pass.
  4. Run each command with the arguments from the tool's readme. Check that --name=value examples bind declared options and that --flag=true on a bool flag is not used.
  5. AOT: dotnet publish -c Release -r linux-x64 (with PublishAot; add -f net11.0 if the project uses plural <TargetFrameworks>). Expect zero IL2xxx/IL3xxx warnings from Nuru. Fix new warnings in the code. Do not suppress them. Warnings from other dependencies (Dapper, Roslyn scripting) stay theirs.
  6. Tool: dotnet pack -c Release -o ./artifacts, then dotnet 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 in nuget.config returns 401, use --source ./artifacts instead of --add-source.

Behavior differences to tell the user about

Details and examples: Behavior differences to check.

Report

End a port with: