mirror of
https://github.com/nsnail/spectre.console.git
synced 2025-06-19 13:28:16 +08:00
Expanding CLI docs
Adding new pages for commandApp, commands and settings.
This commit is contained in:

committed by
Patrik Svensson

parent
04efd1719c
commit
79af013bf2
63
docs/input/cli/commands.md
Normal file
63
docs/input/cli/commands.md
Normal file
@ -0,0 +1,63 @@
|
||||
Title: Creating Commands
|
||||
Order: 6
|
||||
---
|
||||
|
||||
Commands in `Spectre.Console.Cli` are defined by creating a class that inherits from either `Spectre.Console.Cli.Command<TSettings>` or `Spectre.Console.Cli.AsyncCommand<TSettings>`. `Command<TSettings>` must implement an `Execute` method that returns an int where as `AsyncCommand<TSettings>` must implement `ExecuteAsync` returning `Task<int>`.
|
||||
|
||||
```csharp
|
||||
public class HelloCommand : Command<HelloCommand.Settings>
|
||||
{
|
||||
public class Settings : LogCommandSettings
|
||||
{
|
||||
[CommandArgument(0, "[Name]")]
|
||||
public string Name { get; set; }
|
||||
}
|
||||
|
||||
|
||||
public override int Execute(CommandContext context, Settings settings)
|
||||
{
|
||||
AnsiConsole.MarkupLine($"Hello, [blue]{settings.Name}[/]");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
# Configuring.
|
||||
|
||||
Commands are configured via the [`CommandApp`](commandApp)'s `Configure` method.
|
||||
|
||||
```csharp
|
||||
var app = new CommandApp();
|
||||
app.Configure(config =>
|
||||
{
|
||||
config.AddCommand<HelloCommand>("hello")
|
||||
.WithAlias("hola")
|
||||
.WithDescription("Say hello")
|
||||
.WithExample(new []{"hello", "Phil"})
|
||||
.WithExample(new []{"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`](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.
|
||||
|
||||
```csharp
|
||||
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);
|
||||
}
|
||||
```
|
Reference in New Issue
Block a user