dotnet / dotnet/command-line-api

Add support for confirmation

Open
#711 0 comments 3 reactions 0 assignees View on GitHub
enhancement
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.