### Adding Command Usage Examples Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/configurators.md Use WithExample to add one or more usage examples for a command. Each example is provided as a string array of arguments. This is useful for demonstrating how to invoke the command. ```csharp config.AddCommand("publish") .WithDescription("Publish the application") .WithExample("-e", "production") .WithExample("-e", "staging", "--dry-run"); ``` -------------------------------- ### Enable Example Validation Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/application-settings.md Enables validation of examples at startup to ensure they execute without errors. Defaults to false. ```csharp config.Settings.ValidateExamples = true; // Examples that fail to parse will cause startup errors ``` -------------------------------- ### Minimal CommandApp Setup Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/quick-reference.md This snippet shows the basic setup for a CommandApp. It configures the application to add a specific command and then runs it with provided arguments. ```csharp var app = new CommandApp(); app.Configure(config => config.AddCommand("cmd")); await app.RunAsync(args); ``` -------------------------------- ### Add Command-Line Usage Examples Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/configurators.md Add examples of command-line arguments to the help text. This helps users understand how to invoke commands with different options. ```csharp config.AddExample("build", "--release"); config.AddExample("publish", "-e", "prod"); ``` -------------------------------- ### Example AsyncCommand Implementation Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/commands.md An example of a concrete `AsyncCommand` that performs a file download and provides user feedback upon completion. ```csharp public class DownloadCommand : AsyncCommand { protected override async Task ExecuteAsync(CommandContext context, CancellationToken cancellationToken) { await DownloadFileAsync("https://example.com/file.zip", cancellationToken); AnsiConsole.MarkupLine("[green]Download complete![/]"); return 0; } } ``` -------------------------------- ### Adding Usage Examples to Help Text Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/advanced-features.md Usage examples can be added at the application or command level to clarify how to use them. These examples appear in the generated help text. ```csharp app.Configure(config => { // Application-level examples config.AddExample("build"); config.AddExample("deploy", "-e", "production"); config.AddCommand("build") .WithDescription("Build the project") .WithExample("-c", "Debug") .WithExample("-c", "Release", "--no-cache"); }); ``` -------------------------------- ### IConfigurator.AddExample(params string[]) Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/configurators.md Adds a usage example to the application's help text, demonstrating command-line argument patterns. ```APIDOC ## IConfigurator.AddExample(params string[]) ### Description Adds a usage example to the application's help text. ### Method POST ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### args (`string[]`) - Required - Example command-line arguments. ### Returns - `IConfigurator` - The same configurator for chaining. ### Example ```csharp config.AddExample("build", "--release"); config.AddExample("publish", "-e", "prod"); ``` ``` -------------------------------- ### Dependency Injection Setup Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/README.md Demonstrates setting up dependency injection for commands. Services registered with the registrar can be injected into command constructors. ```csharp var registrar = new DefaultTypeRegistrar(); registrar.Register(typeof(IService), typeof(ServiceImpl)); var app = new CommandApp(registrar); // Commands receive services in their constructors public class MyCommand : AsyncCommand { public MyCommand(IService service) { /* ... */ } } ``` -------------------------------- ### Complete Dependency Injection Example Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/dependency-injection.md A full example demonstrating service definition, registration using `DefaultTypeRegistrar`, and a command that utilizes injected services (`IDataService`). This illustrates the end-to-end DI flow in Spectre.Console.Cli. ```csharp // 1. Define services public interface ILogger { void Log(string message); } public class ConsoleLogger : ILogger { public void Log(string message) => Console.WriteLine(message); } public interface IDataService { Task FetchDataAsync(); } public class ApiDataService : IDataService { private readonly ILogger _logger; public ApiDataService(ILogger logger) { _logger = logger; } public async Task FetchDataAsync() { _logger.Log("Fetching data..."); return await Task.FromResult("data"); } } // 2. Register services var registrar = new DefaultTypeRegistrar(); registrar.Register(typeof(ILogger), typeof(ConsoleLogger)); registrar.Register(typeof(IDataService), typeof(ApiDataService)); // 3. Create command using injected services public class FetchCommand : AsyncCommand { private readonly IDataService _dataService; public FetchCommand(IDataService dataService) { _dataService = dataService; } protected override async Task ExecuteAsync( CommandContext context, FetchSettings settings, CancellationToken cancellationToken) { var data = await _dataService.FetchDataAsync(); AnsiConsole.MarkupLine($"[green]Data: {data}[/]"); return 0; } } // 4. Create and run app var app = new CommandApp(registrar); app.Configure(config => { config.AddCommand("fetch"); }); return await app.RunAsync(args); ``` -------------------------------- ### Basic Application Setup Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/README.md This snippet shows how to create a basic CommandApp, configure commands, and run the application. It's the entry point for most CLI applications using this library. ```csharp var app = new CommandApp(); app.Configure(config => { config.AddCommand("build"); config.AddCommand("test"); }); return await app.RunAsync(args); ``` -------------------------------- ### Parameter Attribute Examples Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/quick-reference.md Demonstrates the usage of various parameter attributes for defining command-line arguments and options. Includes examples for positional arguments, named options with optional values, boolean flags, and required options. ```csharp [CommandArgument(0, "")] // Required file argument [CommandArgument(1, "[DESTINATION]")] // Optional destination [CommandOption("-o|--output")] // Named option [CommandOption("-v|--verbose [LEVEL]")] // Optional value [CommandOption("-f|--flag")] // Boolean flag [CommandOption("-r|--required", isRequired: true)]// Required option ``` -------------------------------- ### Custom Help Provider Implementation Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/help-system.md Implement the IHelpProvider interface to create custom help documentation. This example shows a compact provider that displays command names and descriptions. ```csharp public interface IHelpProvider { IEnumerable Write(ICommandModel model, ICommandInfo? command); } ``` ```csharp // Custom help provider public class CompactHelpProvider : IHelpProvider { public IEnumerable Write(ICommandModel model, ICommandInfo? command) { if (command != null) { yield return new Markup($"[bold]{command.Name}[/]\n"); yield return new Markup(command.Description ?? ""); } else { yield return new Markup("[bold]Available Commands:[/]\n"); foreach (var cmd in model.Commands) { yield return new Markup($" {cmd.Name} - {cmd.Description}\n"); } } } } ``` -------------------------------- ### Default HelpProviderStyle Example Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/help-system.md Applies custom styles to the help provider by creating a new `HelpProviderStyle` instance and configuring its properties. ```csharp app.Configure(config => { var styles = new HelpProviderStyle { Description = new DescriptionStyle { Header = "bold cyan" }, Usage = new UsageStyle { Header = "bold green", CurrentCommand = "underline green", Command = "cyan", RequiredArgument = "yellow" } }; config.Settings.HelpProviderStyles = styles; }); ``` -------------------------------- ### Example AsyncCommand Implementation Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/commands.md A concrete `AsyncCommand` with settings, demonstrating custom validation for a config file and executing a deployment process. ```csharp public class DeployCommand : AsyncCommand { protected override ValidationResult Validate(CommandContext context, DeploySettings settings) { if (!File.Exists(settings.ConfigFile)) { return ValidationResult.Error($"Config file not found: {settings.ConfigFile}"); } return ValidationResult.Success(); } protected override async Task ExecuteAsync( CommandContext context, DeploySettings settings, CancellationToken cancellationToken) { AnsiConsole.MarkupLine($"[yellow]Deploying to {settings.Environment}...[/]"); await DeployAsync(settings, cancellationToken); AnsiConsole.MarkupLine("[green]Deployment successful![/]"); return 0; } } ``` -------------------------------- ### Configure Application with Commands and Branches Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/quick-reference.md Use the Configure method to set up your application's name, add commands with descriptions and examples, and define command branches with their own sub-commands. ```csharp app.Configure(config => { config.Settings.ApplicationName = "myapp"; config.AddCommand("build") .WithDescription("Build the project") .WithExample("-c", "Release"); config.AddBranch("db", db => { db.AddCommand("migrate"); }); }); ``` -------------------------------- ### Example: DefaultFromEnvironmentAttribute Implementation Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/attributes.md An example implementation of ParameterValueProviderAttribute that retrieves a parameter's value from an environment variable. Use this when a parameter's default should be dynamically set based on the environment. ```csharp public class DefaultFromEnvironmentAttribute : ParameterValueProviderAttribute { private readonly string _envVar; public DefaultFromEnvironmentAttribute(string envVar) { _envVar = envVar; } public override bool TryGetValue(CommandParameterContext context, out object? result) { result = Environment.GetEnvironmentVariable(_envVar); return result != null; } } public class DeploySettings : CommandSettings { [CommandOption("-e|--environment")] [DefaultFromEnvironment("DEPLOY_ENV")] public string Environment { get; set; } } ``` -------------------------------- ### ExampleStyle Class Definition Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/help-system.md Defines the style for usage examples, including the header and arguments. ```csharp public sealed class ExampleStyle { public Style? Header { get; set; } public Style? Arguments { get; set; } } ``` -------------------------------- ### Implement Custom Help Provider Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/help-system.md Example of implementing a custom IHelpProvider to render detailed command help or application-wide command lists using Spectre.Console's Grid and Renderable types. ```csharp public class VerboseHelpProvider : IHelpProvider { public IEnumerable Write(ICommandModel model, ICommandInfo? command) { if (command != null) { yield return RenderCommandHelp(command); } else { yield return RenderApplicationHelp(model); } } private IRenderable RenderCommandHelp(ICommandInfo command) { var grid = new Grid(); grid.AddColumn(new GridColumn().Padding(1, 0)); grid.AddColumn(new GridColumn().Padding(1, 0)); grid.AddRow("[bold]Command[/]", command.Name); if (!string.IsNullOrEmpty(command.Description)) { grid.AddRow("[bold]Description[/]", command.Description); } return grid; } private IRenderable RenderApplicationHelp(ICommandModel model) { var grid = new Grid(); grid.AddColumn(new GridColumn().Padding(1, 0)); grid.AddColumn(new GridColumn().Padding(1, 0)); grid.AddRow("[bold]Available Commands[/]", ""); foreach (var cmd in model.Commands.Where(c => !c.IsHidden)) { grid.AddRow($" {cmd.Name}", cmd.Description ?? ""); } return grid; } } // Usage app.Configure(config => { config.SetHelpProvider(); }); ``` -------------------------------- ### Set Maximum Indirect Examples Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/application-settings.md Control the maximum number of examples from direct child commands to display in parent help text. Defaults to 5. ```csharp config.Settings.MaximumIndirectExamples = 3; ``` -------------------------------- ### ICommandInfo Interface Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/help-system.md Provides information about a specific command, including its name, description, parameters, subcommands, and usage examples. ```csharp public interface ICommandInfo { string Name { get; } string? Description { get; } IReadOnlyList Parameters { get; } IReadOnlyList Children { get; } bool IsHidden { get; } IReadOnlyList Examples { get; } } ``` -------------------------------- ### LoggingInterceptor Example (Deprecated) Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/advanced-features.md Demonstrates a deprecated pattern for implementing ICommandInterceptor to log command execution details. The preferred approach involves registering the interceptor with ITypeRegistrar. ```csharp public class LoggingInterceptor : ICommandInterceptor { public void Intercept(CommandContext context, CommandSettings settings) { AnsiConsole.MarkupLine($"[dim]Executing command: {context.Name}[/]"); } public void InterceptResult(CommandContext context, CommandSettings settings, ref int result) { AnsiConsole.MarkupLine($"[dim]Exit code: {result}[/]"); } } // Preferred approach: Register via type registrar registrar.Register(typeof(ICommandInterceptor), typeof(LoggingInterceptor)); ``` -------------------------------- ### HelpProviderStyle Class Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/api-summary.md Defines the styling configuration for help text, allowing customization of descriptions, usage lines, examples, arguments, options, and commands. ```APIDOC ## Class: HelpProviderStyle ### Description Help text styling configuration. ### Properties - `DescriptionStyle? Description` — Description styling - `UsageStyle? Usage` — Usage line styling - `ExampleStyle? Examples` — Examples styling - `ArgumentStyle? Arguments` — Arguments styling - `OptionStyle? Options` — Options styling - `CommandStyle? Commands` — Commands styling - `static HelpProviderStyle Default` — Default styles ``` -------------------------------- ### ICommandInfo Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/api-summary.md Provides information about a specific command, including its name, description, parameters, subcommands, and examples. ```APIDOC ## ICommandInfo Command information. ### Properties - `string Name` — Command name - `string? Description` — Description - `IReadOnlyList Parameters` — Arguments and options - `IReadOnlyList Children` — Subcommands - `bool IsHidden` — Is hidden - `IReadOnlyList Examples` — Usage examples ``` -------------------------------- ### Example Usage of FlagValue Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/types.md Demonstrates how to declare and use a FlagValue for a command-line option, such as a verbose flag with an optional level. Shows how to check if the flag is set and access its value. ```csharp [CommandOption("-v|--verbose [LEVEL]")] public FlagValue Verbose { get; set; } ``` ```csharp if (settings.Verbose.IsSet) { var level = settings.Verbose.Value ?? "default"; } ``` -------------------------------- ### Branched Commands Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/README.md Shows how to group related commands under a common branch. This example creates a 'db' branch with 'migrate' and 'seed' commands, allowing for organized command-line interfaces. ```APIDOC ## Branched Commands ### Description Organizes commands into logical groups using branches. This example creates a 'db' branch containing 'migrate' and 'seed' commands. ### Method `AddBranch`, `AddCommand` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp config.AddBranch("db", db => { db.AddCommand("migrate"); db.AddCommand("seed"); }); // Usage: myapp db migrate, myapp db seed ``` ### Response N/A (Configuration step) ``` -------------------------------- ### Set Case Sensitivity in Configuration Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/types.md Example of how to apply the CaseSensitivity enum to the application's configuration settings. This is typically done during the application's setup phase. ```csharp config.Settings.CaseSensitivity = CaseSensitivity.All; ``` -------------------------------- ### FileExistsAttribute Example Source: https://github.com/spectreconsole/spectre.console.cli/blob/main/_autodocs/attributes.md An example implementation of a custom validation attribute that checks if a file exists. Use this to ensure a provided file path is valid. ```csharp public class FileExistsAttribute : ParameterValidationAttribute { public FileExistsAttribute() : base("File does not exist.") { } public override ValidationResult Validate(CommandParameterContext context) { if (context.Value is not string path) { return ValidationResult.Success(); } if (!File.Exists(path)) { return ValidationResult.Error(ErrorMessage); } return ValidationResult.Success(); } } public class DeploySettings : CommandSettings { [CommandArgument(0, "