Files
spectre.console/docs/input/cli/commands.md
Patrik Svensson 45799107a3 Remove Spectre.Console.Cli from repository
* Move Spectre.Console.Cli to its own repository
* Update build script to use Cake.Sdk and .NET Make
* Remove StyleCop (unmaintained)
* Add linting using dotnet format
* Fix generator which was broken
* Update dependencies
2025-11-12 20:56:48 +01:00

2.2 KiB

Title: Creating Commands Order: 6 Description: "How to create commands for Spectre.Console.Cli"

Commands in Spectre.Console.Cli are defined by creating a class that inherits from either Command<TSettings> or AsyncCommand<TSettings>. Command<TSettings> must implement an Execute method that returns an int where as AsyncCommand<TSettings> must implement ExecuteAsync returning Task<int>.

public class HelloCommand : Command<HelloCommand.Settings>
{
    public class Settings : CommandSettings
    {
        [CommandArgument(0, "[Name]")]
        public string Name { get; set; }
    }


    public override int Execute(CommandContext context, Settings settings, CancellationToken cancellationToken)
    {
        AnsiConsole.MarkupLine($"Hello, [blue]{settings.Name}[/]");
        return 0;
    }
}

Configuring

Commands are configured via the CommandApp's Configure method.

var app = new CommandApp();
app.Configure(config =>
{
    config.AddCommand<HelloCommand>("hello")
        .WithAlias("hola")
        .WithDescription("Say hello")
        .WithExample("hello", "Phil")
        .WithExample("hello", "Phil", "--count", "4");
});
  • WithAlias allows commands to have multiple names.
  • WithDescription is used by the help renderer to give commands a description when displaying help.
  • WithExample is used by the help renderer to provide examples to the user for running the commands. The parameters is a string array that matches the values passed in Main(string[] args).

Dependency Injection

Constructor injection is supported on commands. See the CommandApp documentation for further information on configuring Spectre.Console for your container.

Validation

While the settings can validate themselves, the command also provides a validation. For example, IFileSystem might be injected into the command which we want to use to validate that a path passed in exists.

public override ValidationResult Validate(CommandContext context, Settings settings)
{
    if (_fileSystem.IO.File.Exists(settings.Path))
    {
        return ValidationResult.Error($"Path not found - {settings.Path}");
    }

    return base.Validate(context, settings);
}