-
Notifications
You must be signed in to change notification settings - Fork 20
/
events.go
360 lines (293 loc) · 7.92 KB
/
events.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
* ZEUS - An Electrifying Build System
* Copyright (c) 2017 Philipp Mieden <dreadl0ck [at] protonmail [dot] ch>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package main
import (
"errors"
"os"
"strings"
"sync"
"github.com/fsnotify/fsnotify"
"github.com/sirupsen/logrus"
)
var (
// ignore the the write event when updating the config using the shell command
disableWriteEvent = false
disableWriteEventMutex = &sync.Mutex{}
// ErrInvalidEventType means the given event type string is invalid
ErrInvalidEventType = errors.New("invalid fsnotify event type. available types are: WRITE | REMOVE | RENAME | CHMOD")
// ErrInvalidUsage means the command was used incorrectly
ErrInvalidUsage = errors.New("invalid usage")
)
// temporarily disable change event
func blockWriteEvent() {
disableWriteEventMutex.Lock()
disableWriteEvent = true
disableWriteEventMutex.Unlock()
}
// Event represents a watched path, along with an an action
// that will be performed when an operation of the specified type occurs
type Event struct {
// Event Name
Name string
// Event ID
ID string
// Path to watch
Path string
// Operation type
Op fsnotify.Op
// optional File Type Extension
// if empty the event will be fired for all file types
FileExtension string
// Command to be executed upon event
Command string
// custom event handler func
handler func(fsnotify.Event)
// shutdown chan
stopChan chan bool
}
func printEventsUsageErr() {
l.Println(ErrInvalidUsage)
l.Println("usage: events [add <optype> <path> <filetype> <commandChain>] [remove <path>]")
}
// handle events command
func handleEventsCommand(args []string) {
if len(args) < 2 {
printEvents()
return
}
if len(args) < 3 {
printEventsUsageErr()
return
}
switch args[1] {
case "remove":
removeEvent(args[2])
case "add":
registerEvent(args)
default:
printEventsUsageErr()
}
}
// register an event for a given path, operation type, and optionally filetype
// plus a commandChain to be executed once the event occurs
func registerEvent(args []string) {
if len(args) < 5 {
printEventsUsageErr()
return
}
// check if event type is valid
op, err := getEventType(args[2])
if err != nil {
Log.Error(err)
return
}
// check if path exists
_, err = os.Stat(args[3])
if err != nil {
Log.Error(err)
return
}
var (
fields []string
filetype string
)
if strings.HasPrefix(args[4], ".") {
fields = args[5:]
filetype = args[4]
} else {
fields = args[4:]
}
if filetype != "" && len(fields) == 0 {
Log.Error("no command supplied")
return
}
if _, ok := validCommandChain(fields, true); ok {
Log.Info("adding command chain")
} else {
Log.Info("adding shell command")
}
chain := strings.Join(fields, " ")
go func() {
e := newEvent(args[3], op, "custom event", filetype, "", chain, func(event fsnotify.Event) {
Log.Debug("event fired, name: ", event.Name, " path: ", args[3])
if cmdChain, ok := validCommandChain(fields, true); ok {
cmdChain.exec(fields)
} else {
// its a shell command
if len(fields) > 1 {
passCommandToShell(fields[0], fields[1:])
} else {
passCommandToShell(fields[0], []string{})
}
}
})
err := addEvent(e)
if err != nil {
Log.Error("failed to watch path: ", args[3])
}
}()
}
// parse command type string and fsnotify type
func getEventType(event string) (fsnotify.Op, error) {
switch event {
case "WRITE":
return fsnotify.Write, nil
case "REMOVE":
return fsnotify.Remove, nil
case "RENAME":
return fsnotify.Rename, nil
case "CHMOD":
return fsnotify.Chmod, nil
default:
return 0, ErrInvalidEventType
}
}
// list all currently registered events
func printEvents() {
w := 25
l.Println(cp.Prompt + pad("name", w) + pad("ID", w) + pad("operation", w) + pad("command", w) + pad("filetype", w) + pad("path", w))
for _, e := range projectData.fields.Events {
l.Println(cp.Text + pad(e.Name, w) + pad(e.ID, w) + pad(e.Op.String(), w) + pad(e.Command, w) + pad(e.FileExtension, w) + pad(e.Path, w))
}
}
// remove the event for the given path
func removeEvent(id string) {
projectData.Lock()
// check if event exists
if e, ok := projectData.fields.Events[id]; ok {
if e.stopChan != nil {
// stop event handler
e.stopChan <- true
}
// delete event
delete(projectData.fields.Events, id)
projectData.Unlock()
Log.Debug("removed event with name ", e.Name)
// update project data
projectData.update()
return
}
projectData.Unlock()
Log.Error("event with ID ", id, " does not exist")
}
// create a new event
// if the supplied eventID is empty it will be generated
func newEvent(path string, op fsnotify.Op, name, filetype, eventID, command string, handler func(fsnotify.Event)) *Event {
if eventID == "" {
eventID = randomString()
}
// create event
return &Event{
Path: path,
Name: name,
ID: eventID,
Op: op,
handler: handler,
stopChan: make(chan bool, 1),
Command: command,
FileExtension: filetype,
}
}
// addEvent takes an event, registers it, creates a watcher for the events path
// and registers a handler that will fire if operation op occurs
func addEvent(e *Event) error {
var cLog = Log.WithField("prefix", "addEvent")
Log.WithField("path", e.Path).Debug("adding event")
// init new watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
// add to events
projectData.Lock()
projectData.fields.Events[e.ID] = e
projectData.Unlock()
// update projectData on disk
projectData.update()
// listen for events
done := make(chan bool)
go func() {
for {
select {
case event := <-watcher.Events:
// cLog.WithFields(logrus.Fields{
// "event": event,
// "path": path,
// }).Debug("incoming event")
// check operation type
if event.Op == e.Op {
if e.FileExtension != "" {
if !strings.HasSuffix(event.Name, e.FileExtension) {
Log.WithField("e.FileExtension", e.FileExtension).Debug("ignoring event because file type does not match: ", event.Name)
continue
}
}
// check if write event was disabled.
// example: when updating the config with the config command
// revalidating the config is not necessary
disableWriteEventMutex.Lock()
if disableWriteEvent {
disableWriteEvent = false
disableWriteEventMutex.Unlock()
cLog.Debug("ignoring WRITE event for path: ", e.Path)
continue
}
disableWriteEventMutex.Unlock()
// fire handler
e.handler(event)
}
case err := <-watcher.Errors:
cLog.WithError(err).Fatal("watcher failed")
case _ = <-e.stopChan:
watcher.Close()
done <- true
return
}
}
}()
// add path to watcher
err = watcher.Add(e.Path)
if err != nil {
cLog.WithFields(logrus.Fields{
"error": err,
"path": e.Path,
}).Error("failed to add path to watcher")
e.stopChan <- true
return err
}
// wait for it
<-done
return nil
}
// reload an internal event from project data
func reloadEvent(e *Event) {
Log.Debug("reloading event: ", e.Name)
switch e.Name {
case "config watcher":
go conf.watch(e.ID)
case "formatter watcher":
if conf.fields.AutoFormat {
go f.watchScriptDir(e.ID)
}
case "commandsFile watcher":
go watchCommandsFile(commandsFilePath, e.ID)
default:
Log.Warn("reload event called for an unknown event: ", e.Name)
}
}