github.com/pdmccormick/importable-docker-buildx@v0.0.0-20240426161518-e47091289030/commands/util.go (about) 1 package commands 2 3 import ( 4 "bufio" 5 "context" 6 "fmt" 7 "io" 8 "os" 9 "runtime" 10 "strings" 11 12 "github.com/docker/cli/cli/streams" 13 ) 14 15 func prompt(ctx context.Context, ins io.Reader, out io.Writer, msg string) (bool, error) { 16 done := make(chan struct{}) 17 var ok bool 18 go func() { 19 ok = promptForConfirmation(ins, out, msg) 20 close(done) 21 }() 22 select { 23 case <-ctx.Done(): 24 return false, context.Cause(ctx) 25 case <-done: 26 return ok, nil 27 } 28 } 29 30 // promptForConfirmation requests and checks confirmation from user. 31 // This will display the provided message followed by ' [y/N] '. If 32 // the user input 'y' or 'Y' it returns true other false. If no 33 // message is provided "Are you sure you want to proceed? [y/N] " 34 // will be used instead. 35 // 36 // Copied from github.com/docker/cli since the upstream version changed 37 // recently with an incompatible change. 38 // 39 // See https://github.com/docker/buildx/pull/2359#discussion_r1544736494 40 // for discussion on the issue. 41 func promptForConfirmation(ins io.Reader, outs io.Writer, message string) bool { 42 if message == "" { 43 message = "Are you sure you want to proceed?" 44 } 45 message += " [y/N] " 46 47 _, _ = fmt.Fprint(outs, message) 48 49 // On Windows, force the use of the regular OS stdin stream. 50 if runtime.GOOS == "windows" { 51 ins = streams.NewIn(os.Stdin) 52 } 53 54 reader := bufio.NewReader(ins) 55 answer, _, _ := reader.ReadLine() 56 return strings.ToLower(string(answer)) == "y" 57 }