Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions cli/cliui/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,12 @@ func Prompt(inv *serpent.Invocation, opts PromptOptions) (string, error) {
case err := <-errCh:
return "", err
case line := <-lineCh:
if opts.IsConfirm && line != "yes" && line != "y" {
return line, xerrors.Errorf("got %q: %w", line, ErrCanceled)
if opts.IsConfirm {
answer := strings.ToLower(strings.TrimSpace(line))
if answer != ConfirmYes && answer != "y" {
return line, xerrors.Errorf("got %q: %w", line, ErrCanceled)
}
line = ConfirmYes
}
if opts.Validate != nil {
err := opts.Validate(line)
Expand Down
47 changes: 47 additions & 0 deletions cli/cliui/prompt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,53 @@ func TestPrompt(t *testing.T) {
require.Equal(t, "yes", resp)
})

t.Run("ConfirmNormalizesInput", func(t *testing.T) {
t.Parallel()

for _, input := range []string{"Yes", "YES", " yes ", "Y", " y "} {
input := input
t.Run(input, func(t *testing.T) {
t.Parallel()

ctx := testutil.Context(t, testutil.WaitShort)
ptty := ptytest.New(t)
doneChan := make(chan string)
go func() {
resp, err := newPrompt(ctx, ptty, cliui.PromptOptions{
Text: "Example",
IsConfirm: true,
}, nil)
assert.NoError(t, err)
doneChan <- resp
}()
ptty.ExpectMatch(ctx, "Example")
ptty.WriteLine(input)
resp := testutil.TryReceive(ctx, t, doneChan)
require.Equal(t, "yes", resp)
})
}
})

t.Run("ConfirmDefaultNoReturnsCanceled", func(t *testing.T) {
t.Parallel()

ctx := testutil.Context(t, testutil.WaitShort)
ptty := ptytest.New(t)
doneChan := make(chan error)
go func() {
_, err := newPrompt(ctx, ptty, cliui.PromptOptions{
Text: "Example",
IsConfirm: true,
Default: cliui.ConfirmNo,
}, nil)
doneChan <- err
}()
ptty.ExpectMatch(ctx, "Example")
ptty.WriteLine("")
err := testutil.TryReceive(ctx, t, doneChan)
require.ErrorIs(t, err, cliui.ErrCanceled)
})

t.Run("Skip", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
Expand Down
1 change: 1 addition & 0 deletions cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ func (r *RootCmd) RunWithSubcommands(subcommands []*serpent.Command) {
err = exitErr.err
}
if errors.Is(err, cliui.ErrCanceled) {
_, _ = fmt.Fprintln(os.Stderr, "Aborted.")
//nolint:revive,gocritic
os.Exit(code)
}
Expand Down
Loading