-
Notifications
You must be signed in to change notification settings - Fork 1
/
live.go
98 lines (85 loc) · 2.16 KB
/
live.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
package main
import (
"fmt"
"io/fs"
"log"
"path/filepath"
"time"
"github.com/bep/debounce"
"github.com/fsnotify/fsnotify"
)
func live(sourceFolder, basepath, config string, port int, minifyOutput, draft bool) error {
// Initial build
target := "./.tmp"
builder, err := NewBuilder()
if err != nil {
return fmt.Errorf("error constructing builder: %w", err)
}
build := func() error {
return builder.Build(sourceFolder, target, config, minifyOutput, draft)
}
if err := build(); err != nil {
// We don't return an error here, since the user can simply try
// fixing the issue, causing the watcher to automatically rebuild.
log.Println("Error running initial build:", err)
}
// Then watch for changes and rebuild.
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
// Start listening for events.
go func() {
debouncer := debounce.New(100 * time.Millisecond)
for {
select {
case event, channelOpen := <-watcher.Events:
if !channelOpen {
return
}
// Permission changes do not affect the build
// outcome, therefore we ignore these types of events.
if event.Op == fsnotify.Chmod {
continue
}
// Some editors or IDEs migth write multiple times,
// therefore we debounce, to prevent unnecessar lag.
// Another scenario where this might be useful, are
// for example reformats or search and replace invocations
// on the whole codebase.
debouncer(func() {
log.Println("Rebuilding ...", event)
now := time.Now()
if err := build(); err != nil {
log.Println("Error rebuilding:", err)
} else {
log.Printf("Rebuild successful. (%s)\n", time.Since(now).String())
}
})
case err, channelOpen := <-watcher.Errors:
if !channelOpen {
return
}
log.Println("watcher error:", err)
}
}
}()
err = filepath.WalkDir(
sourceFolder,
func(path string, dirEntry fs.DirEntry, err error) error {
if err != nil {
return err
}
if dirEntry.IsDir() {
if err := watcher.Add(path); err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
return serve(target, basepath, port)
}