forked from shiyanhui/hero
/
main.go
101 lines (85 loc) · 1.53 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
package main
import (
"flag"
"log"
"os"
"os/signal"
"path/filepath"
"syscall"
"github.com/howeyc/fsnotify"
"github.com/shiyanhui/hero"
)
var (
watch bool
source, dest, pkgName string
)
func init() {
flag.StringVar(
&source,
"source",
"./",
"the html template file or dir",
)
flag.StringVar(
&dest,
"dest",
"",
"generated golang files dir, it will be the same with source if not set",
)
flag.StringVar(
&pkgName,
"pkgname",
"template",
"the generated template package name, default is `template`",
)
flag.BoolVar(
&watch,
"watch",
false,
"whether automatically compile when the source files change",
)
}
func watchFile(watcher *fsnotify.Watcher, path string) {
if err := watcher.Watch(path); err != nil {
log.Fatal(err)
}
}
func main() {
flag.Parse()
if dest == "" {
dest = source
}
hero.Generate(source, dest, pkgName)
if !watch {
return
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
go func() {
for {
select {
case ev := <-watcher.Event:
if ev.IsDelete() || ev.IsModify() || ev.IsRename() {
hero.Generate(source, dest, pkgName)
}
}
}
}()
watchFile(watcher, source)
stat, _ := os.Stat(source)
if stat.IsDir() {
filepath.Walk(source, func(path string, _ os.FileInfo, err error) error {
stat, _ := os.Stat(path)
if stat.IsDir() {
watchFile(watcher, path)
}
return nil
})
}
done := make(chan os.Signal)
signal.Notify(done, syscall.SIGINT, syscall.SIGTERM)
<-done
watcher.Close()
}