Skip to content

Instantly share code, notes, and snippets.

@seesharprun
Last active May 22, 2025 22:00
Show Gist options
  • Select an option

  • Save seesharprun/f84abfeb613b39ae870c51e6b1bfadd7 to your computer and use it in GitHub Desktop.

Select an option

Save seesharprun/f84abfeb613b39ae870c51e6b1bfadd7 to your computer and use it in GitHub Desktop.
Spectre.Console composed CLI
using System.ComponentModel;
using Spectre.Console;
using Spectre.Console.Cli;
using Console = Spectre.Console.AnsiConsole;
CommandApp app = new();
app.Configure(configuration =>
{
configuration.UseAssemblyInformationalVersion();
configuration.AddCommand<HelloCommand>("hello")
.WithDescription("Greets the user with a hello message.");
configuration.AddCommand<GoodbyeCommand>("goodbye")
.WithDescription("Greets the user with a goodbye message.");
});
return await app.RunAsync(args);
internal abstract class GreetCommandSettings : CommandSettings
{
[CommandOption("-n|--name")]
[Description("The name of the person to greet. Defaults to 'World'.")]
[DefaultValue("World")]
public string? Name { get; set; }
}
internal sealed class HelloCommandSettings : GreetCommandSettings;
internal sealed class GoodbyeCommandSettings : GreetCommandSettings;
internal sealed class HelloCommand : Command<HelloCommandSettings>
{
public override int Execute(CommandContext context, HelloCommandSettings settings)
=> context.ProcessGreeting("Hello", settings);
}
internal sealed class GoodbyeCommand : Command<GoodbyeCommandSettings>
{
public override int Execute(CommandContext context, GoodbyeCommandSettings settings)
=> context.ProcessGreeting("Goodbye", settings);
}
internal static class GreetCommandExtensions
{
public static int ProcessGreeting(this CommandContext _, string salutation, GreetCommandSettings settings)
{
string greeting = $"{salutation}, {settings.Name}!";
Panel panel = new Panel($"[blue bold]{greeting}[/]")
.Border(BoxBorder.Rounded)
.BorderColor(Color.Green)
.Header("[red italic]Greeting[/]")
.Padding(2, 4)
.Expand();
Console.Write(panel);
return 0;
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Spectre.Console" Version="0.50.0" />
<PackageReference Include="Spectre.Console.Cli" Version="0.50.0" />
</ItemGroup>
</Project>
<Solution>
<Project Path="project.csproj" />
</Solution>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment