replaced archived survey dep with osutils.YesNoPrompt helper
This commit is contained in:
@@ -1,8 +1,12 @@
|
||||
package osutils
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/go-ozzo/ozzo-validation/v4/is"
|
||||
)
|
||||
@@ -29,3 +33,33 @@ func LaunchURL(url string) error {
|
||||
return exec.Command("xdg-open", url).Start()
|
||||
}
|
||||
}
|
||||
|
||||
// YesNoPrompt performs a console prompt that asks the user for Yes/No answer.
|
||||
//
|
||||
// If the user just press Enter (aka. doesn't type anything) it returns the fallback value.
|
||||
func YesNoPrompt(message string, fallback bool) bool {
|
||||
options := "Y/n"
|
||||
if !fallback {
|
||||
options = "y/N"
|
||||
}
|
||||
|
||||
r := bufio.NewReader(os.Stdin)
|
||||
|
||||
var s string
|
||||
for {
|
||||
fmt.Fprintf(os.Stderr, "%s (%s) ", message, options)
|
||||
|
||||
s, _ = r.ReadString('\n')
|
||||
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
|
||||
switch s {
|
||||
case "":
|
||||
return fallback
|
||||
case "y", "yes":
|
||||
return true
|
||||
case "n", "no":
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package osutils_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/tools/osutils"
|
||||
)
|
||||
|
||||
func TestYesNoPrompt(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
stdin string
|
||||
fallback bool
|
||||
expected bool
|
||||
}{
|
||||
{"", false, false},
|
||||
{"", true, true},
|
||||
|
||||
// yes
|
||||
{"y", false, true},
|
||||
{"Y", false, true},
|
||||
{"Yes", false, true},
|
||||
{"yes", false, true},
|
||||
|
||||
// no
|
||||
{"n", true, false},
|
||||
{"N", true, false},
|
||||
{"No", true, false},
|
||||
{"no", true, false},
|
||||
|
||||
// invalid -> no/yes
|
||||
{"invalid|no", true, false},
|
||||
{"invalid|yes", false, true},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(fmt.Sprintf("%s_%v", s.stdin, s.fallback), func(t *testing.T) {
|
||||
stdinread, stdinwrite, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
parts := strings.Split(s.stdin, "|")
|
||||
for _, p := range parts {
|
||||
if _, err := stdinwrite.WriteString(p + "\n"); err != nil {
|
||||
t.Fatalf("Failed to write test stdin part %q: %v", p, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err = stdinwrite.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
defer func(oldStdin *os.File) { os.Stdin = oldStdin }(os.Stdin)
|
||||
os.Stdin = stdinread
|
||||
|
||||
result := osutils.YesNoPrompt("test", s.fallback)
|
||||
|
||||
if result != s.expected {
|
||||
t.Fatalf("Expected %v, got %v", s.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user