-
Notifications
You must be signed in to change notification settings - Fork 4
/
prompt.go
53 lines (45 loc) · 1.08 KB
/
prompt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package util
import (
"context"
"fmt"
"strings"
log "github.com/sirupsen/logrus"
)
type confirmResponse struct {
responseStr string
err error
}
// Confirm gets a yes/no confirmation from the user on the command-line before continuing.
func Confirm(ctx context.Context, prompt string, skip bool) (bool, error) {
fmt.Printf("%s (yes/no) ", prompt)
if skip {
log.Infof("Automatically answering yes because skip is set to true")
return true, nil
}
responseChan := make(chan confirmResponse, 1)
go func() {
var responseStr string
_, err := fmt.Scanln(&responseStr)
responseChan <- confirmResponse{
responseStr: responseStr,
err: err,
}
}()
select {
case response := <-responseChan:
if response.err != nil {
log.Warnf(
"Got error reading response, not continuing: %+v",
response.err,
)
return false, response.err
}
if r := strings.TrimSpace(strings.ToLower(response.responseStr)); r != "y" && r != "yes" {
log.Infof("Not continuing")
return false, nil
}
return true, nil
case <-ctx.Done():
return false, ctx.Err()
}
}