dotnet / dotnet/command-line-api
Add support for confirmation
- Dominant language
- C#
- Stars
- 3.7k
- Forks
- 428
- PR merge metrics
- No merged PRs in 30d
Description
Currently, having to repeat this pattern everywhere:
```cs
internal class changerequestNew
{
internal static Command command = new Command(
"new",
"Create a new change request"
);
static changerequestNew() {
command.AddOption(new Option(new[]{"--param", "--p"})
{
Argument = new Argument(),
Required = true,
});
// ...
// ###########################################################
// ALWAYS HAVING TO ADD THIS PATTERN
command.AddOption(new Option(new[]{"--confirm", "--c"}) { Required = false });
command.Handler = CommandHandler.Create(
// Always adding confirmation parameter to handlers
(string param, bool confirm) => handle(
param:param, confirm:confirm
)
);
// ###########################################################
}
internal static void handle(string param, bool confirm) {
Console.WriteLine($"New change request for {param}");
// ###########################################################
// ALWAYS HAVING TO ADD THIS PATTERN
if (!confirm && !Interactive.confirmation()) {
Console.WriteLine("Skipping execution.");
return;
}
// ###########################################################
Console.WriteLine("Creating new change request");
}
}
internal class Interactive
{
internal static bool confirmation() {
bool repeat = true;
while (repeat) {
Console.WriteLine($"Are you sure you want to continue? (yes/no)");
string output = Console.ReadLine();
if (output == null)
return false;
output = output.Trim().ToLower();
if (output.Length <= 0)
continue;
// ###########################################################
// Can be deceptively more complex than this
else if (output == "yes" || output == "y")
return true;
else
return false;
}
return false;
}
}
```
Would be nice to have a default "yes/no" confirmation handler in [`src/System.CommandLine/Command.cs`](https://github.com/dotnet/command-line-api/blob/master/src/System.CommandLine/Command.cs) (if a given property `Confirmation = true`)
Contributor guide
Assessment
This issue has not been assessed yet.