This repository has been archived by the owner on Oct 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
devrestarter.go
80 lines (69 loc) · 1.52 KB
/
devrestarter.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
// Package devrestarter automatically restarts your server when it's updated.
// This is suitable for use during development. When you recompile your server,
// it will be restarted.
package devrestarter
import (
"log"
"os"
"os/exec"
"sync"
"syscall"
"time"
"github.com/facebookgo/stackerr"
"github.com/fsnotify/fsnotify"
)
var debug func(v ...interface{})
func noop(v ...interface{}) {}
func init() {
if os.Getenv("RELOADER_DEBUG") == "" {
debug = noop
} else {
debug = log.Println
}
}
func watch() error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return stackerr.Wrap(err)
}
defer watcher.Close()
argv0, err := exec.LookPath(os.Args[0])
if err != nil {
return stackerr.Wrap(err)
}
debug("reloader:", argv0)
if err := watcher.Add(argv0); err != nil {
return stackerr.Wrap(err)
}
var doit <-chan time.Time
for {
select {
case <-doit:
log.Println("Restarting", argv0)
if err := syscall.Exec(argv0, os.Args, os.Environ()); err != nil {
return stackerr.Wrap(err)
}
case event := <-watcher.Events:
debug("watcher.Event:", event)
doit = time.After(500 * time.Millisecond)
if err := watcher.Add(event.Name); err != nil {
return stackerr.Wrap(err)
}
case err := <-watcher.Errors:
debug("watcher.Error:", err)
}
}
}
// make Init idempotent.
var once sync.Once
// Init initializes the background goroutine that will restart the binary when
// it changes.
func Init() {
once.Do(func() {
go func() {
if err := watch(); err != nil {
panic(err)
}
}()
})
}