/
main.go
125 lines (108 loc) · 2.37 KB
/
main.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"flag"
"log"
"os"
"os/signal"
"sync"
"time"
"github.com/nsf/termbox-go"
"github.com/rhcarvalho/redgreen/redgreen"
)
// Command-line flags and arguments.
var (
testCommand = []string{"go", "test"}
timeout time.Duration
debug bool
)
func init() {
flag.BoolVar(&debug, "debug", false, "Enable debug mode, disable termbox.")
flag.DurationVar(&timeout, "timeout", 5*time.Second, "Maximum time to wait for command to finish. Set to 0 to disable.")
}
func main() {
flag.Parse()
// Customize testCommand if passed as arguments.
if flag.NArg() > 0 {
testCommand = flag.Args()
}
if err := do(); err != nil {
log.Fatalf("ERROR: %v", err)
}
}
func do() error {
// Initialize and defer termination of termbox.
if !debug {
if err := termbox.Init(); err != nil {
return err
}
defer termbox.Close()
termbox.HideCursor()
termbox.SetOutputMode(termbox.Output256)
}
// wg waits for all goroutines started by this function to return.
var wg sync.WaitGroup
defer wg.Wait()
// Closing done signals all goroutines to terminate.
done := make(chan struct{})
defer close(done)
w, err := redgreen.Watch(done, ".", 200*time.Millisecond)
if err != nil {
return err
}
runSpec := redgreen.RunSpec{Command: testCommand, Timeout: timeout}
run := make(chan redgreen.RunSpec, 1)
res := redgreen.Run(done, run)
// Trigger an initial run of the test command.
run <- runSpec
// Run tests every time a file is created/removed/modified.
wg.Add(1)
go func() {
defer wg.Done()
for range w {
run <- runSpec
}
}()
state := make(chan redgreen.State)
wg.Add(1)
go func() {
defer wg.Done()
redgreen.Render(done, state)
}()
s := redgreen.State{Debug: debug}
var mu sync.RWMutex // synchronizes access to s.
// Render initial state.
state <- s
// Render after every test command result.
wg.Add(1)
go func() {
defer wg.Done()
for r := range res {
mu.Lock()
s.Results = append(s.Results, r)
mu.Unlock()
mu.RLock()
state <- s
mu.RUnlock()
}
}()
if debug {
// Wait for Ctrl-C.
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
<-ch
} else {
// Block until Esc is pressed.
for {
e := termbox.PollEvent()
if e.Type == termbox.EventKey && e.Key == termbox.KeyEsc {
break
}
if e.Type == termbox.EventResize {
mu.RLock()
state <- s
mu.RUnlock()
}
}
}
return nil
}