-
Notifications
You must be signed in to change notification settings - Fork 4
/
builder.go
279 lines (234 loc) · 4.91 KB
/
builder.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package main
import (
"bufio"
"bytes"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/Tonkpils/snag/vow"
"github.com/shiena/ansicolor"
fsn "gopkg.in/fsnotify.v1"
)
var mtimes = map[string]time.Time{}
var clearBuffer = func() {
fmt.Print("\033c")
}
type Bob struct {
w *fsn.Watcher
mtx sync.RWMutex
curVow *vow.Vow
done chan struct{}
watching map[string]struct{}
watchDir string
depWarning string
buildCmds [][]string
runCmds [][]string
ignoredItems []string
verbose bool
}
func NewBuilder(c config) (*Bob, error) {
w, err := fsn.NewWatcher()
if err != nil {
return nil, err
}
parseCmd := func(cmd string) (c []string) {
s := bufio.NewScanner(strings.NewReader(cmd))
s.Split(splitFunc)
for s.Scan() {
c = append(c, s.Text())
}
// check for environment variables inside script
if strings.Contains(cmd, "$$") {
replaceEnv(c)
}
return c
}
buildCmds := make([][]string, len(c.Build))
for i, s := range c.Build {
buildCmds[i] = parseCmd(s)
}
runCmds := make([][]string, len(c.Run))
for i, s := range c.Run {
runCmds[i] = parseCmd(s)
}
return &Bob{
w: w,
done: make(chan struct{}),
watching: map[string]struct{}{},
buildCmds: buildCmds,
runCmds: runCmds,
depWarning: c.DepWarnning,
ignoredItems: c.IgnoredItems,
verbose: c.Verbose,
}, nil
}
func splitFunc(data []byte, atEOF bool) (advance int, token []byte, err error) {
advance, token, err = bufio.ScanWords(data, atEOF)
if err != nil {
return
}
if len(token) == 0 {
return
}
b := token[0]
if b != '"' && b != '\'' {
return
}
if token[len(token)-1] == b {
return
}
chunk := data[advance-1:]
i := bytes.IndexByte(chunk, b)
if i == -1 {
advance = len(data)
token = append(token, chunk...)
return
}
advance += i
token = append(token, chunk[:i+1]...)
return
}
func replaceEnv(cmds []string) {
for i, c := range cmds {
if !strings.HasPrefix(c, "$$") {
continue
}
cmds[i] = os.Getenv(strings.TrimPrefix(c, "$$"))
}
}
func (b *Bob) Close() error {
close(b.done)
return b.w.Close()
}
func (b *Bob) Watch(path string) error {
b.watchDir = path
// this can never return false since we will always
// have at least one file in the directory (.snag.yml)
_ = b.watch(path)
b.execute()
for {
select {
case ev := <-b.w.Events:
var queueBuild bool
switch {
case isCreate(ev.Op):
queueBuild = b.watch(ev.Name)
case isDelete(ev.Op):
if _, ok := b.watching[ev.Name]; ok {
b.w.Remove(ev.Name)
delete(b.watching, ev.Name)
}
queueBuild = true
case isModify(ev.Op):
queueBuild = true
}
if queueBuild {
b.maybeQueue(ev.Name)
}
case err := <-b.w.Errors:
log.Println("error:", err)
case <-b.done:
return nil
}
}
}
func (b *Bob) maybeQueue(path string) {
if b.isExcluded(path) {
return
}
stat, err := os.Stat(path)
if err != nil {
// we couldn't find the file
// most likely a deletion
delete(mtimes, path)
b.execute()
return
}
mtime := stat.ModTime()
lasttime := mtimes[path]
if !mtime.Equal(lasttime) {
// the file has been modified and the
// file system event wasn't bogus
mtimes[path] = mtime
b.execute()
}
}
func (b *Bob) stopCurVow() {
b.mtx.Lock()
if b.curVow != nil {
b.curVow.Stop()
}
b.mtx.Unlock()
}
func (b *Bob) execute() {
b.stopCurVow()
clearBuffer()
b.mtx.Lock()
if len(b.depWarning) > 0 {
fmt.Printf("Deprecation Warnings!\n%s", b.depWarning)
}
// setup the first command
firstCmd := b.buildCmds[0]
b.curVow = vow.To(firstCmd[0], firstCmd[1:]...)
// setup the remaining commands
for i := 1; i < len(b.buildCmds); i++ {
cmd := b.buildCmds[i]
b.curVow = b.curVow.Then(cmd[0], cmd[1:]...)
}
// setup all parallel commands
for i := 0; i < len(b.runCmds); i++ {
cmd := b.runCmds[i]
b.curVow = b.curVow.ThenAsync(cmd[0], cmd[1:]...)
}
b.curVow.Verbose = b.verbose
go b.curVow.Exec(ansicolor.NewAnsiColorWriter(os.Stdout))
b.mtx.Unlock()
}
func (b *Bob) watch(path string) bool {
var shouldBuild bool
if _, ok := b.watching[path]; ok {
return false
}
filepath.Walk(path, func(p string, fi os.FileInfo, err error) error {
if fi == nil {
return filepath.SkipDir
}
if !fi.IsDir() {
shouldBuild = true
return nil
}
if b.isExcluded(p) {
return filepath.SkipDir
}
if err := b.w.Add(p); err != nil {
return err
}
b.watching[p] = struct{}{}
return nil
})
return shouldBuild
}
func (b *Bob) isExcluded(path string) bool {
// get the relative path
path = strings.TrimPrefix(path, b.watchDir+string(filepath.Separator))
for _, p := range b.ignoredItems {
if globMatch(p, path) {
return true
}
}
return false
}
func isCreate(op fsn.Op) bool {
return op&fsn.Create == fsn.Create
}
func isDelete(op fsn.Op) bool {
return op&fsn.Remove == fsn.Remove
}
func isModify(op fsn.Op) bool {
return op&fsn.Write == fsn.Write ||
op&fsn.Rename == fsn.Rename
}