/
main.go
265 lines (244 loc) · 6.09 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package main
import (
"bytes"
"context"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"github.com/livebud/cli"
"github.com/livebud/watcher"
"github.com/matthewmueller/dev/internal/graceful"
"github.com/matthewmueller/dev/internal/hot"
"github.com/matthewmueller/dev/internal/pubsub"
"github.com/matthewmueller/dev/internal/sh"
"github.com/matthewmueller/dev/internal/virtual"
"golang.org/x/sync/errgroup"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
cli := cli.New("dev", "personal dev tooling")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
{ // serve [flags] [dir]
cmd := new(Serve)
cli := cli.Command("serve", "serve a directory")
cli.Flag("listen", "address to listen on").String(&cmd.Listen).Default(":3000")
cli.Flag("live", "enable live reloading").Bool(&cmd.Live).Default(true)
cli.Flag("open", "open browser").Bool(&cmd.Browser).Default(true)
cli.Arg("dir").String(&cmd.Dir).Default(".")
cli.Run(cmd.Run)
}
{ // watch [flags] [dir]
cmd := new(Watch)
cli := cli.Command("watch", "watch a directory")
cli.Flag("ignore", "ignore files matching pattern").Strings(&cmd.Ignore).Default()
cli.Flag("clear", "clear screen every change").Bool(&cmd.Clear).Default(true)
cli.Arg("command").String(&cmd.Command)
cli.Args("args").Strings(&cmd.Args).Default()
cli.Run(cmd.Run)
}
return cli.Parse(ctx, os.Args[1:]...)
}
type Serve struct {
Listen string
Live bool
Dir string
Browser bool
}
func (s *Serve) Run(ctx context.Context) error {
eg, ctx := errgroup.WithContext(ctx)
ps := pubsub.New()
host, portStr, err := net.SplitHostPort(s.Listen)
if err != nil {
return err
}
port, err := strconv.Atoi(portStr)
if err != nil {
return err
}
// Find the next available port
ln, port, err := findNextPort(host, port)
if err != nil {
return err
}
url := formatAddr(host, port)
fmt.Println("Listening on", url)
eg.Go(s.serve(ctx, ln, ps))
if s.Live {
eg.Go(s.watch(ctx, ps))
}
if s.Browser {
if err := exec.CommandContext(ctx, "open", url).Run(); err != nil {
return err
}
}
return eg.Wait()
}
func (s *Serve) serve(ctx context.Context, ln net.Listener, ps pubsub.Subscriber) func() error {
return func() error {
fs := http.FileServer(http.FS(s))
return graceful.Serve(ctx, ln, s.handler(hot.New(ps), fs))
}
}
// Minimal favicon
var favicon = []byte{
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49,
0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02,
0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xde, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52,
0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x04, 0x67, 0x41,
0x4d, 0x41, 0x00, 0x00, 0xb1, 0x8f, 0x0b, 0xfc, 0x61, 0x05, 0x00, 0x00, 0x00,
0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0e, 0xc4, 0x00, 0x00, 0x0e, 0xc4,
0x01, 0x95, 0x2b, 0x0e, 0x1b, 0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41, 0x54,
0x08, 0xd7, 0x63, 0xf8,
}
func (s *Serve) handler(live http.Handler, fs http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/favicon.ico":
w.Header().Set("Content-Type", "image/png")
w.Write(favicon)
case "/.live":
live.ServeHTTP(w, r)
default:
w.Header().Set("Cache-Control", "no-store")
fs.ServeHTTP(w, r)
}
})
}
const liveReloadScript = `
<script>
var es = new EventSource('/.live');
es.onmessage = function(e) { window.location.reload(); }
</script>
`
const htmlPage = `<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
%s
%s
</body>
</html>
`
func (s *Serve) Open(name string) (fs.File, error) {
if filepath.Ext(name) != ".html" {
return os.Open(filepath.Join(s.Dir, name))
}
f, err := os.Open(filepath.Join(s.Dir, name))
if err != nil {
return nil, err
}
fi, err := f.Stat()
if err != nil {
return nil, err
}
// Skip directories
if fi.IsDir() {
return f, nil
}
defer f.Close()
// If we detect HTML, inject the live reload script
html, err := io.ReadAll(f)
if err != nil {
return nil, err
}
// Close the existing file because we don't need it anymore
if f.Close(); err != nil {
return nil, err
}
// Inject the live reload script
if bytes.Contains(html, []byte("<html>")) {
html = append(html, []byte(liveReloadScript)...)
} else {
html = []byte(fmt.Sprintf(htmlPage, liveReloadScript, string(html)))
}
// Create a buffered file
bf := &virtual.File{
Path: name,
Data: html,
Mode: fi.Mode(),
ModTime: fi.ModTime(),
}
return bf.Open(), nil
}
func (s *Serve) watch(ctx context.Context, ps pubsub.Publisher) func() error {
return func() error {
return watcher.Watch(ctx, s.Dir, func(events []watcher.Event) error {
if len(events) == 0 {
return nil
}
event := events[0]
ps.Publish(string(event.Op), []byte(event.Path))
return nil
})
}
}
type Watch struct {
Ignore []string
Clear bool
Command string
Args []string
}
func (w *Watch) Run(ctx context.Context) error {
if w.Clear {
clear()
}
// Run initially
cmd := sh.Command{
Stderr: os.Stderr,
Stdout: os.Stdout,
Stdin: os.Stdin,
Env: os.Environ(),
Dir: ".",
}
if err := cmd.Start(ctx, w.Command, w.Args...); err != nil {
// Don't exit on errors
fmt.Fprintln(os.Stderr, err)
}
// Watch for changes
return watcher.Watch(ctx, ".", func(events []watcher.Event) error {
if len(events) == 0 {
return nil
}
if w.Clear {
clear()
}
if err := cmd.Restart(ctx); err != nil {
// Don't exit on errors
fmt.Fprintln(os.Stderr, err)
}
return nil
})
}
func clear() {
fmt.Fprint(os.Stdout, "\033[H\033[2J")
}
// Find the next available port starting at 3000
func findNextPort(host string, port int) (net.Listener, int, error) {
for i := 0; i < 100; i++ {
ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port+i))
if err == nil {
return ln, port + i, nil
}
}
return nil, 0, fmt.Errorf("could not find an available port")
}
func formatAddr(host string, port int) string {
if host == "" {
host = "0.0.0.0"
}
return fmt.Sprintf("http://%s:%d", host, port)
}