-
Notifications
You must be signed in to change notification settings - Fork 2
/
watch.go
78 lines (68 loc) · 1.68 KB
/
watch.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
// Package watch monitors markdown files for changes and generates html
package watch
import (
"log"
"os"
"strings"
"time"
"github.com/edwinwalela/tiwi/pkg/parse"
"github.com/fsnotify/fsnotify"
)
// getMdFileName extracts markdown file name from directory path
func getMdFileName(path string) string {
vals := strings.Split(path, "/")
for i := range vals {
if strings.Contains(vals[i], ".md") {
return vals[i]
}
}
return ""
}
// logEvent outputs details regarding file changed
func logEvent(event *fsnotify.Event) {
log.Printf("File changed: %v. Rebuilding HTML\n", getMdFileName(event.Name))
}
// Watch monitors markdown files and rebuilds HTML when markdown changes
func Watch(args []string) {
var projectDir string
wDir, err := os.Getwd()
if err != nil {
log.Fatalf("failed to get working directory: %s", err.Error())
}
if len(args) == 0 {
projectDir = wDir
} else {
projectDir = wDir + "/" + args[0]
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatalf("failed to watch directory: %s", err.Error())
}
defer watcher.Close()
parse.Build(args, false, true, false)
done := make(chan bool)
go func() {
var (
timer *time.Timer
lastEvent fsnotify.Event
)
timer = time.NewTimer(time.Millisecond)
<-timer.C
for {
select {
case event := <-watcher.Events:
lastEvent = event
timer.Reset(time.Millisecond * 100)
case err := <-watcher.Errors:
log.Fatalf("failed to watch directory: %s", err.Error())
case <-timer.C:
logEvent(&lastEvent)
parse.Build(args, false, true, true)
}
}
}()
if err := watcher.Add(projectDir); err != nil {
log.Fatalf("Failed to watch project directory: %s", err.Error())
}
<-done
}