forked from YaoApp/yao
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
62 lines (51 loc) · 960 Bytes
/
cli.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
package cli
import (
"bufio"
"fmt"
"io"
"os"
"github.com/fatih/color"
)
// Cli the CLI
type Cli struct {
option *Option
}
// In the input stream
var reader io.Reader = os.Stdin
// Option the CLI option
type Option struct {
Label string
Reader io.Reader
}
// SetReader set the reader
func SetReader(r io.Reader) {
reader = r
}
// New create a new CLI
func New(option *Option) *Cli {
if option.Reader == nil {
option.Reader = reader
}
return &Cli{
option: option,
}
}
// Render the CLI UI
func (cli *Cli) Render(args []any) ([]string, error) {
scanner := bufio.NewScanner(cli.option.Reader)
var lines []string
color.Blue("%s", cli.option.Label)
fmt.Printf("%s", color.WhiteString("> "))
for scanner.Scan() {
line := scanner.Text()
if line == "exit()" {
break
}
lines = append(lines, line)
fmt.Printf("%s", color.WhiteString("> "))
}
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
}