-
Notifications
You must be signed in to change notification settings - Fork 0
/
dev.go
92 lines (76 loc) · 1.76 KB
/
dev.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
package dev
import (
"fmt"
"log/slog"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/fsnotify/fsnotify"
"github.com/lukeshay/gocden/pkg/cmds"
"github.com/lukeshay/gocden/pkg/cmds/build"
"github.com/lukeshay/gocden/pkg/cmds/serve"
"github.com/lukeshay/gocden/pkg/util"
"github.com/urfave/cli/v2"
)
func Dev(c *cli.Context) error {
cwd := cmds.GetCwdFlag(c)
config := cmds.GetConfigFromCliContext(c)
if _, _, err := build.BuildAllFiles(c); err != nil {
return err
}
go func() {
if err := serve.RunServer(c); err != nil {
os.Exit(1)
}
}()
// Create new watcher.
watcher, err := fsnotify.NewWatcher()
if err != nil {
fmt.Printf("Error creating watcher: %v\n", err)
return err
}
defer watcher.Close()
sig := make(chan os.Signal)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
go func() {
<-sig
fmt.Println("Shutting down server...")
os.Exit(1)
}()
debounce := util.NewDebouncer(250 * time.Millisecond)
// Start listening for events.
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
slog.Info("File system even detected", "even", event)
if event.Has(fsnotify.Create) || event.Has(fsnotify.Remove) || event.Has(fsnotify.Write) {
debounce(func() {
if _, _, err := build.BuildAllFiles(c); err != nil {
fmt.Printf("Error building: %v\n", err)
}
})
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
fmt.Printf("Error while watching file system: %v\n", err)
}
}
}()
// Add a path.
err = watcher.Add(filepath.Join(cwd, config.Build.Source))
if err != nil {
fmt.Printf("Error watching source directory: %v\n", err)
return err
}
// Block main goroutine forever.
<-make(chan struct{})
return nil
}