/
main.go
102 lines (89 loc) · 1.97 KB
/
main.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/codegangsta/cli"
"github.com/jaschaephraim/lrserver"
"gopkg.in/fsnotify.v1"
)
func main() {
app := cli.NewApp()
app.Flags = []cli.Flag{
cli.StringSliceFlag{
Name: "watch",
Value: &cli.StringSlice{"."},
},
cli.StringSliceFlag{
Name: "service",
Value: &cli.StringSlice{},
},
}
app.Action = run
app.Run(os.Args)
}
func run(ctx *cli.Context) {
watchDirs := ctx.StringSlice("watch")
services := ctx.StringSlice("service")
watcher, err := fsnotify.NewWatcher()
if err != nil {
fmt.Fprintf(os.Stderr, "error setting up file watcher: %v", err)
}
for _, d := range watchDirs {
watcher.Add(d)
}
defer watcher.Close()
lr, err := lrserver.New(lrserver.DefaultName, lrserver.DefaultPort)
if err != nil {
fmt.Fprintf(os.Stderr, "error starting live reload: %v", err)
}
go lr.ListenAndServe()
composeBin, err := exec.LookPath("docker-compose")
if err != nil {
fmt.Fprintf(os.Stderr, "could not find docker-compose path")
os.Exit(1)
}
var cmd *exec.Cmd
var t <-chan time.Time
var ignore bool
MainLoop:
for {
select {
case e := <-watcher.Events:
select {
case <-t:
ignore = false
default:
if ignore {
continue MainLoop
}
match, _ := filepath.Match("*.sw*", e.Name)
if match || strings.HasSuffix(e.Name, "~") {
continue MainLoop
}
}
if len(services) == 0 {
cmd = exec.Command(composeBin, "up")
} else {
args := []string{"up", "--no-deps"}
args = append(args, services...)
cmd = exec.Command(composeBin, args...)
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
fmt.Fprintf(os.Stderr, "error reloading compose file: %v", err)
}
ignore = true
time.Sleep(1 * time.Second)
lr.Reload("")
t = time.After(3 * time.Second)
case err := <-watcher.Errors:
fmt.Fprintf(os.Stderr, "error watching files: %v", err)
os.Exit(1)
}
}
}