-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
174 lines (159 loc) · 3.62 KB
/
Copy pathmain.go
File metadata and controls
174 lines (159 loc) · 3.62 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
package main
import (
"bufio"
"io"
"log"
"os"
"os/exec"
"os/signal"
"path/filepath"
"syscall"
"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"
)
type processSignal struct {
signal os.Signal
exitProcess bool
}
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, 1)
signal.Notify(done, os.Interrupt)
var cmd *exec.Cmd
cmdSignal := make(chan *processSignal, 1)
go runCommand(cmd, c.Args(), cmdSignal)
go handleWatchEvents(watcher, cmdSignal, c.Bool("dir"))
startFileWatch(watcher)
exitSignal := <-done
if cmd != nil {
cmdSignal <- &processSignal{signal: exitSignal, exitProcess: true}
cmd.Wait()
}
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.",
},
},
}
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)
}
}
}
}
func handleWatchEvents(watcher *fsnotify.Watcher, cmdSignal chan *processSignal, watchDirs bool) {
for {
select {
case event, ok := <-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, exitProcess: false}
} else if event.Op == fsnotify.Create && watchDirs {
logrus.Debugf("created: %s", event.Name)
signal = &processSignal{signal: syscall.SIGTERM, exitProcess: true}
}
if signal == nil {
return
}
select {
case cmdSignal <- signal:
default:
logrus.Debugln("restart already scheduled, ignoring change.")
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
logrus.Warnf("error: %s", err.Error())
}
}
}
func runCommand(cmd *exec.Cmd, args cli.Args, cmdSignal chan *processSignal) {
for {
running := true
cmd = exec.Command(args.First(), args.Slice()[1:]...)
cmd.Env = os.Environ()
stdoutPipe, _ := cmd.StdoutPipe()
stderrPipe, _ := cmd.StderrPipe()
err := 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 := <-cmdSignal
if !running {
return
}
logrus.Debugf("got signal %+v", signal)
if signal.exitProcess {
running = false
}
cmd.Process.Signal(signal.signal)
cmd.Wait()
}()
logrus.Debugln("process started")
cmd.Wait()
logrus.Debugln("process killed")
if !running {
os.Exit(cmd.ProcessState.ExitCode())
break
}
}
}