-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
209 lines (190 loc) · 4.36 KB
/
Copy pathmain.go
File metadata and controls
209 lines (190 loc) · 4.36 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
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
package main
import (
"bufio"
"io"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/fsnotify/fsnotify"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
)
// Version gets overridden at build time using -X main.Version=$VERSION
var (
Version = "dev"
)
func init() {
logrus.SetOutput(os.Stdout)
logrus.SetLevel(logrus.InfoLevel)
}
func main() {
app := &cli.App{
Name: "nightwatch",
Version: Version,
Usage: "A utility for running arbitrary commands when files change",
Before: func(ctx *cli.Context) error {
if ctx.Bool("debug") {
logrus.SetLevel(logrus.DebugLevel)
}
return nil
},
Action: func(c *cli.Context) error {
if !c.Args().Present() {
logrus.Fatal("No command specified")
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
logrus.Fatal(err)
}
defer watcher.Close()
done := make(chan os.Signal, 2)
signal.Notify(done, os.Interrupt, syscall.SIGTERM)
nightWatch := &NightWatch{
cmdSignal: make(chan *processSignal, 1),
args: c.Args(),
watcher: watcher,
exitOnChange: c.Int("exit-on-change"),
watchDirs: c.Bool("dir"),
}
nightWatch.Run()
startFileWatch(watcher)
exitSignal := <-done
exitCode := nightWatch.Stop(exitSignal)
time.Sleep(10 * time.Second)
os.Exit(exitCode)
return nil
},
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "debug",
Usage: "Debug logging.",
},
&cli.BoolFlag{
Name: "dir",
Aliases: []string{"d"},
Usage: "Track the directories of regular files provided as input and exit if a new file is added.",
},
&cli.IntFlag{
Name: "exit-on-change",
Usage: "Exit on file change with a given code.",
Value: 255,
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func startFileWatch(watcher *fsnotify.Watcher) {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
file := scanner.Text()
absFile, err := filepath.Abs(file)
if err == nil {
err = watcher.Add(absFile)
if err != nil {
logrus.Warningf("failed to watch file %s", absFile)
}
}
}
}
type processSignal struct {
signal os.Signal
}
type NightWatch struct {
cmd *exec.Cmd
args cli.Args
cmdSignal chan *processSignal
watcher *fsnotify.Watcher
exitOnChange int
watchDirs bool
}
func (n *NightWatch) Run() {
go n.handleWatchEvents()
go n.runCommand()
}
func (n *NightWatch) Stop(exitSignal os.Signal) int {
if n.cmd == nil {
return 0
}
if n.cmd.ProcessState != nil && n.cmd.ProcessState.Exited() {
return n.cmd.ProcessState.ExitCode()
}
logrus.Debugf("stop requested: %s", exitSignal)
n.cmdSignal <- &processSignal{signal: exitSignal}
n.cmd.Wait()
return n.cmd.ProcessState.ExitCode()
}
func (n *NightWatch) handleWatchEvents() {
for {
select {
case event, ok := <-n.watcher.Events:
if !ok {
return
}
var signal *processSignal
if event.Op == fsnotify.Write || event.Op == fsnotify.Chmod {
logrus.Debugf("modified file: %s", event.Name)
signal = &processSignal{signal: syscall.SIGTERM}
} else if event.Op == fsnotify.Create && n.watchDirs {
logrus.Debugf("created: %s", event.Name)
signal = &processSignal{signal: syscall.SIGTERM}
}
if signal == nil {
return
}
select {
case n.cmdSignal <- signal:
default:
logrus.Debugln("restart already scheduled, ignoring change.")
}
case err, ok := <-n.watcher.Errors:
if !ok {
return
}
logrus.Warnf("error: %s", err.Error())
}
}
}
func (n *NightWatch) runCommand() {
for {
changeDetected := false
n.cmd = exec.Command(n.args.First(), n.args.Slice()[1:]...)
n.cmd.Env = os.Environ()
stdoutPipe, _ := n.cmd.StdoutPipe()
stderrPipe, _ := n.cmd.StderrPipe()
defer stdoutPipe.Close()
defer stderrPipe.Close()
err := n.cmd.Start()
if err != nil {
logrus.Fatal(err.Error())
}
go func() {
io.Copy(os.Stdout, stdoutPipe)
}()
go func() {
io.Copy(os.Stderr, stderrPipe)
}()
go func() {
signal := <-n.cmdSignal
changeDetected = true
logrus.Debugf("got signal %+v", signal)
n.cmd.Process.Signal(signal.signal)
n.cmd.Wait()
}()
logrus.Debugln("process started")
n.cmd.Wait()
logrus.Debugln("process killed")
if changeDetected {
os.Exit(n.exitOnChange)
} else if n.cmd.ProcessState.ExitCode() == 0 {
os.Exit(0)
}
time.Sleep(500 * time.Millisecond)
}
}