-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrunner.go
More file actions
127 lines (108 loc) · 2.21 KB
/
Copy pathrunner.go
File metadata and controls
127 lines (108 loc) · 2.21 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package watchf
import (
"bytes"
"fmt"
"os/exec"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/mgutz/ansi"
"golang.org/x/net/context"
"gopkg.in/fsnotify.v1"
)
type Runner interface {
Run(...Action)
}
type BasicRunner struct {
Context context.Context
}
func (r BasicRunner) Run(actions ...Action) {
for _, e := range actions {
select {
case <-r.Context.Done():
break
default:
}
if op := e.Run(); op != Continue {
break
}
}
}
type StepOp int
const (
Halt StepOp = iota
Continue
)
type Action interface {
Run() StepOp
}
type cmdAction struct {
command string
event fsnotify.Event
}
func (c cmdAction) Run() StepOp {
start := time.Now()
var cmd *exec.Cmd
command := evaluate(c.command, c.event)
args := strings.Fields(command)
if len(args) > 1 {
cmd = exec.Command(args[0], args[1:]...)
} else {
cmd = exec.Command(args[0])
}
out, err := cmd.CombinedOutput()
elapsed := time.Now().Sub(start)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"elapsed": elapsed,
}).Error(highlight(fmt.Sprintf("Run: %s", command), "red+b"))
} else {
log.WithFields(log.Fields{
"elapsed": time.Now().Sub(start),
}).Info(highlight(fmt.Sprintf("Run: %s", command), "cyan+b"))
}
if len(out) > 0 {
fmt.Print(string(out))
}
if err != nil {
return Halt
}
return Continue
}
func highlight(text string, color string) string {
if !isTerminal() {
return text
}
return ansi.Color(text, color)
}
func isTerminal() bool {
return log.IsTerminal()
}
func evaluate(cmd string, evt fsnotify.Event) string {
cmd = strings.Replace(cmd, "%f", evt.Name, -1)
cmd = strings.Replace(cmd, "%t", opName(evt.Op), -1)
return cmd
}
func opName(op fsnotify.Op) string {
var buffer bytes.Buffer
if op&fsnotify.Create == fsnotify.Create {
_, _ = buffer.WriteString("|CREATE")
}
if op&fsnotify.Remove == fsnotify.Remove {
_, _ = buffer.WriteString("|REMOVE")
}
if op&fsnotify.Write == fsnotify.Write {
_, _ = buffer.WriteString("|WRITE")
}
if op&fsnotify.Rename == fsnotify.Rename {
_, _ = buffer.WriteString("|RENAME")
}
if op&fsnotify.Chmod == fsnotify.Chmod {
_, _ = buffer.WriteString("|CHMOD")
}
if buffer.Len() == 0 {
return ""
}
return buffer.String()[1:]
}