github.com/esnet/gdg@v0.6.1-0.20240412190737-6b6eba9c14d8/internal/tools/prompt_helpers.go (about)

     1  package tools
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"log"
     7  	"log/slog"
     8  	"os"
     9  	"slices"
    10  	"strings"
    11  )
    12  
    13  var validResponse = []rune{'y', 'n'}
    14  
    15  // GetUserConfirmation prompts user to confirm operation
    16  // msg Message to prompt the user with
    17  // validate returns true/false on success or terminates the process
    18  // msg: prompt to display to the user asking for a response.
    19  // error: error message to display if app should terminate
    20  // terminate:  when set to true will terminate the app user response is not valid.
    21  func GetUserConfirmation(msg, error string, terminate bool) bool {
    22  	if error == "" {
    23  		error = "Goodbye"
    24  	}
    25  	for {
    26  		fmt.Print(msg)
    27  		r := bufio.NewReader(os.Stdin)
    28  		ans, _ := r.ReadString('\n')
    29  		ans = strings.ToLower(ans)
    30  		if !slices.Contains(validResponse, rune(ans[0])) {
    31  			slog.Error("Invalid response, please try again.  Only [yes/no] are supported")
    32  			continue
    33  		}
    34  		//Validate Response
    35  		if ans[0] != 'y' && terminate {
    36  			log.Fatal(error)
    37  		} else if ans[0] != 'y' {
    38  			return false
    39  		}
    40  		return true
    41  	}
    42  
    43  }