Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

term: Fix confirmation prompts on windows #413

Merged
merged 1 commit into from
Nov 24, 2020
Merged
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
34 changes: 27 additions & 7 deletions pkg/term/alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,42 @@ package term
import (
"bufio"
"fmt"
"io"
"os"

"github.com/pkg/errors"
)

var ErrConfirmationFailed = errors.New("aborted by user")

// Confirm asks the user for confirmation
func Confirm(msg, approval string) error {
reader := bufio.NewReader(os.Stdin)
fmt.Println(msg)
fmt.Printf("Please type '%s' to confirm: ", approval)
read, err := reader.ReadString('\n')
return confirmFrom(os.Stdin, os.Stdout, msg, approval)
}

func confirmFrom(r io.Reader, w io.Writer, msg, approval string) error {
reader := bufio.NewScanner(r)
_, err := fmt.Fprintln(w, msg)
if err != nil {
return errors.Wrap(err, "reading from stdin")
return errors.Wrap(err, "writing to stdout")
}
if read != approval+"\n" {
return errors.New("aborted by user")

_, err = fmt.Fprintf(w, "Please type '%s' to confirm: ", approval)
if err != nil {
return errors.Wrap(err, "writing to stdout")
}

if !reader.Scan() {
if err := reader.Err(); err != nil {
return errors.Wrap(err, "reading from stdin")
}

return ErrConfirmationFailed
}

if reader.Text() != approval {
return ErrConfirmationFailed
}

return nil
}
38 changes: 38 additions & 0 deletions pkg/term/alert_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package term

import (
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

func TestConfirm(t *testing.T) {
tests := []struct {
name string
input string
expected error
}{
{name: "linux yes", input: "yes\n", expected: nil},
{name: "windows yes", input: "yes\r\n", expected: nil},
{name: "linux no", input: "no\n", expected: ErrConfirmationFailed},
{name: "windows no", input: "no\r\n", expected: ErrConfirmationFailed},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
in := strings.NewReader(tt.input)
out := &strings.Builder{}

err := confirmFrom(in, out, "foo", "yes")

assert.Equal(t, "foo\nPlease type 'yes' to confirm: ", out.String())

if tt.expected != nil {
assert.EqualError(t, err, tt.expected.Error())
} else {
assert.NoError(t, err)
}
})
}
}