-
Notifications
You must be signed in to change notification settings - Fork 18
/
console.go
80 lines (72 loc) · 1.3 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
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
"sync"
"github.com/chzyer/readline"
)
func startConsole(servers []*Server) {
rl, err := readline.New("> ")
if err != nil {
panic(err)
}
defer rl.Close()
type output struct {
serv *Server
output string
}
isTerminal := readline.IsTerminal(int(os.Stdin.Fd()))
for {
var line string
var err error
if isTerminal {
line, err = rl.Readline()
} else {
lineb, er := ioutil.ReadAll(os.Stdin)
line, err = string(lineb), er
}
if err != nil { // io.EOF
break
}
outputc := make(chan output)
var mutex sync.Mutex
var count int
var wg sync.WaitGroup
wg.Add(1)
go func() {
for {
mutex.Lock()
output := <-outputc
prompt := output.serv.prompt()
if isTerminal {
prompt += " " + line
}
if count > 0 && strings.TrimSpace(output.output) != "" {
prompt = "\n" + prompt
}
fmt.Println(prompt)
if strings.TrimSpace(output.output) != "" {
fmt.Printf(output.output)
}
if count++; count >= len(servers) {
break
}
mutex.Unlock()
}
wg.Done()
}()
for _, serv := range servers {
wg.Add(1)
go func(serv *Server) {
outputc <- output{serv: serv, output: serv.exec(line)}
wg.Done()
}(serv)
}
wg.Wait()
if !isTerminal {
return
}
}
}