-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathconsole.go
102 lines (93 loc) · 2.06 KB
/
console.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package utils
import (
"bufio"
"context"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/go-errors/errors"
"github.com/supabase/cli/pkg/cast"
"golang.org/x/term"
)
type Console struct {
IsTTY bool
stdin *bufio.Scanner
token chan string
mu sync.Mutex
}
func NewConsole() *Console {
return &Console{
IsTTY: term.IsTerminal(int(os.Stdin.Fd())),
stdin: bufio.NewScanner(os.Stdin),
token: make(chan string),
mu: sync.Mutex{},
}
}
// Prevent interactive terminals from hanging more than 10 minutes
const ttyTimeout = time.Minute * 10
func (c *Console) ReadLine(ctx context.Context) string {
// Wait a few ms for input
timeout := time.Millisecond
if c.IsTTY {
timeout = ttyTimeout
}
timer := time.NewTimer(timeout)
defer timer.Stop()
// Read from stdin in background
go func() {
c.mu.Lock()
defer c.mu.Unlock()
// Scan one line from input or file
if c.stdin.Scan() {
c.token <- strings.TrimSpace(c.stdin.Text())
}
}()
var input string
select {
case input = <-c.token:
case <-ctx.Done():
case <-timer.C:
}
return input
}
// PromptYesNo asks yes/no questions using the label.
func (c *Console) PromptYesNo(ctx context.Context, label string, def bool) (bool, error) {
choices := "Y/n"
if !def {
choices = "y/N"
}
labelWithChoice := fmt.Sprintf("%s [%s] ", label, choices)
// Any error will be handled as default value
input, err := c.PromptText(ctx, labelWithChoice)
if len(input) > 0 {
if answer := parseYesNo(input); answer != nil {
return *answer, nil
}
}
return def, err
}
func parseYesNo(s string) *bool {
s = strings.ToLower(s)
if s == "y" || s == "yes" {
return cast.Ptr(true)
}
if s == "n" || s == "no" {
return cast.Ptr(false)
}
return nil
}
// PromptText asks for input using the label.
func (c *Console) PromptText(ctx context.Context, label string) (string, error) {
fmt.Fprint(os.Stderr, label)
input := c.ReadLine(ctx)
// Echo to stderr for non-interactive terminals
if !c.IsTTY {
fmt.Fprintln(os.Stderr, input)
}
if err := ctx.Err(); err != nil {
return "", errors.New(err)
}
return input, nil
}