-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
118 lines (95 loc) · 2.26 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"fmt"
"log"
"os"
flag "github.com/ogier/pflag"
"github.com/fsnotify/fsnotify"
)
// VERSION of the application.
const VERSION = "v1.1.0"
var version, noEscape, watch bool
var source, destination, params string
func init() {
flag.StringVarP(¶ms, "params", "p", "", "")
flag.BoolVarP(&version, "version", "v", false, "")
flag.BoolVarP(&noEscape, "no-escape", "n", false, "")
flag.BoolVarP(&watch, "watch", "w", false, "")
flag.Usage = twitUsage
flag.Parse()
source = flag.Arg(0)
destination = flag.Arg(1)
if version {
fmt.Printf("twit %s\n", VERSION)
os.Exit(0)
}
if flag.NArg() < 1 {
log.Fatal("Not enough arguments.")
}
if watch && flag.NArg() < 2 {
log.Fatal("To use watch, you have to specify a destination.")
}
}
func rerender(twit *Twit, name string) {
templateParams := TemplateParams{}
templateParams.Set(params)
fmt.Printf("Changes detected in %#v\n", name)
fmt.Println("Rewriting template")
templateParams.Set(params)
twit.TemplateParams = templateParams
twit.SetSourceFromPath(source)
twit.Render()
}
func main() {
templateParams := TemplateParams{}
templateParams.Set(params)
output := os.Stdout
if destination == "" {
output = os.Stdout
} else {
output, _ = os.Create(destination)
}
twit, err := NewTwit(source, output, templateParams, !noEscape)
if err != nil {
panic(err)
}
twit.Render()
if watch {
templateWatcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
defer templateWatcher.Close()
paramsWatcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
defer paramsWatcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event := <-templateWatcher.Events:
rerender(twit, event.Name)
case err := <-templateWatcher.Errors:
panic(err)
case event := <-paramsWatcher.Events:
rerender(twit, event.Name)
case err := <-paramsWatcher.Errors:
panic(err)
}
}
}()
if err := templateWatcher.Add(source); err != nil {
panic(err)
} else {
fmt.Println("Watching" + source + " ...")
}
if err := paramsWatcher.Add(params); err != nil {
// This probably means the params were passed in as json.
} else {
fmt.Println("Watching" + params + " ...")
}
<-done
}
}