-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathwatcher.go
More file actions
107 lines (86 loc) · 2.19 KB
/
watcher.go
File metadata and controls
107 lines (86 loc) · 2.19 KB
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
package json
import (
"bufio"
"context"
"encoding/json"
"io"
"strings"
"github.com/src-d/lookout"
"github.com/src-d/lookout/util/ctxlog"
"gopkg.in/src-d/go-log.v1"
)
// Provider is the name
const Provider = "json"
// Watcher watches for new json events in the console
type Watcher struct {
o *lookout.WatchOptions
scanner *bufio.Scanner
}
// NewWatcher returns a new json console watcher
func NewWatcher(reader io.Reader, o *lookout.WatchOptions) (*Watcher, error) {
return &Watcher{
o: o,
scanner: bufio.NewScanner(reader),
}, nil
}
// Watch reads json from stdin and calls cb for each new event
func (w *Watcher) Watch(ctx context.Context, cb lookout.EventHandler) error {
ctxlog.Get(ctx).With(log.Fields{"provider": Provider}).Infof("Starting watcher")
lines := make(chan string, 1)
go func() {
for w.scanner.Scan() {
lines <- w.scanner.Text()
}
}()
for {
select {
case <-ctx.Done():
return ctx.Err()
case line := <-lines:
if err := w.handleInput(ctx, cb, line); err != nil {
if lookout.NoErrStopWatcher.Is(err) {
return nil
}
return err
}
}
}
}
type eventType struct {
Event string `json:"event"`
}
func (w *Watcher) handleInput(ctx context.Context, cb lookout.EventHandler, line string) error {
if line == "" {
return nil
}
logger := ctxlog.Get(ctx).With(log.Fields{"input": line})
var eventType eventType
if err := json.Unmarshal([]byte(line), &eventType); err != nil {
logger.Errorf(err, "could not unmarshal the event")
return nil
}
var event lookout.Event
switch strings.ToLower(eventType.Event) {
case "":
logger.Errorf(nil, `field "event" is mandatory`)
return nil
case "review":
var reviewEvent *lookout.ReviewEvent
if err := json.Unmarshal([]byte(line), &reviewEvent); err != nil {
logger.Errorf(err, "could not unmarshal the ReviewEvent")
return nil
}
event = reviewEvent
case "push":
var pushEvent *lookout.PushEvent
if err := json.Unmarshal([]byte(line), &pushEvent); err != nil {
logger.Errorf(err, "could not unmarshal the PushEvent")
return nil
}
event = pushEvent
default:
logger.Errorf(nil, "event %q not supported", eventType.Event)
return nil
}
return cb(event)
}