-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwr.go
More file actions
719 lines (650 loc) · 19 KB
/
wr.go
File metadata and controls
719 lines (650 loc) · 19 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
package main
import (
"bufio"
"context"
"database/sql"
"fmt"
"os"
"os/exec"
"os/signal"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/bep/debounce"
"github.com/fsnotify/fsnotify"
"github.com/gen2brain/beeep"
_ "github.com/joho/godotenv/autoload"
"github.com/rs/zerolog/log"
"github.com/urfave/cli/v2"
"github.com/web-ridge/wr/helpers"
"github.com/web-ridge/wr/specific"
)
var (
quit = make(chan bool)
restart = make(chan bool)
port = os.Getenv("PORT")
db *sql.DB
)
type paths struct {
backend string
frontend string
orgName string
}
func main() {
helpers.ConfigureLogger()
app := &cli.App{
Name: "wr",
Usage: "WebRidge dev tool - hot reload for Go/GraphQL projects",
Description: `Watches for file changes and automatically runs build steps:
.go/.gohtml/.env → Restart server
.sql → Drop DB + Migrate + Convert + Seed + Restart
.graphql → Convert + Merge schemas + Relay
seed/ → Re-run seeder
migrations/ → Run migrations + Convert
Keyboard shortcuts (always available during session):
r = Restart server c = Run convert s = Run seeder
m = Run migrations a = Run all h = Show help`,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "no-watch",
Aliases: []string{"n"},
Usage: "Disable file watcher, use keyboard shortcuts only",
},
&cli.BoolFlag{
Name: "go",
Aliases: []string{"g"},
Usage: "Only watch Go files (no convert/seed/migrations on file change)",
},
&cli.BoolFlag{
Name: "kill",
Aliases: []string{"k"},
Usage: "Kill other wr instances before starting",
},
},
Action: start,
}
if err := app.Run(os.Args); err != nil {
log.Fatal().Err(err).Msg("cannot run app")
}
}
func start(c *cli.Context) error {
noWatch := c.Bool("no-watch")
goOnly := c.Bool("go")
killOthers := c.Bool("kill")
// Kill other wr instances if requested
if killOthers {
killed := killOtherWrInstances()
if killed > 0 {
log.Info().Int("count", killed).Msg("killed other wr instances")
}
}
log.Info().Msg(`
_ _____ _ _
| | | __ \(_) | |
__ _____| |__ | |__) |_ __| | __ _ ___
\ \ /\ / / _ \ '_ \| _ /| |/ _` + "`" + ` |/ _` + "`" + ` |/ _ \
\ V V / __/ |_) | | \ \| | (_| | (_| | __/
\_/\_/ \___|_.__/|_| \_\_|\__,_|\__,_|\___|
|___/
`)
printKeyboardShortcuts()
// Set up context with cancellation for graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Set up signal handling for Ctrl+C and termination
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
var dockerCmd *exec.Cmd
var existingServer *exec.Cmd
// Cleanup function for graceful shutdown
defer func() {
log.Info().Msg("shutting down, cleaning up processes...")
cancel() // Signal all goroutines to stop
if existingServer != nil {
stopServer(existingServer)
}
if dockerCmd != nil {
stopDocker()
}
killPortProcess(port)
close(quit)
}()
p, err := setupPaths()
if err != nil {
return fmt.Errorf("setup paths: %w", err)
}
if err := installDependencies(p.frontend); err != nil {
return fmt.Errorf("install dependencies: %w", err)
}
dockerCmd = startDbInDocker()
time.Sleep(1 * time.Second)
db = helpers.WaitForDatabase()
if err := runInitialSetup(); err != nil {
log.Error().Err(err).Msg("runInitialSetup failed, continuing to watch for changes")
}
// Start server after initial setup
killPortProcess(port)
existingServer = startServerInBackground(true)
if existingServer == nil {
log.Error().Msg("initial server start failed, continuing to watch for changes")
}
// Start file watcher unless --no-watch is set
if !noWatch {
if useNativeWatcher() {
go watchNative(ctx, p.backend, p.frontend, goOnly)
} else {
go watch(ctx, p.backend, p.frontend, goOnly)
}
} else {
log.Info().Msg("file watcher disabled, use keyboard shortcuts to trigger actions")
}
// Start keyboard input handler
keyChan := make(chan rune, 1)
go readKeyboardInput(ctx, keyChan)
// Main loop for restarts and signal handling
for {
select {
case key := <-keyChan:
switch key {
case 'r':
log.Info().Msg("⌨️ [r] restarting server...")
if existingServer != nil {
stopServer(existingServer)
}
killPortProcess(port)
existingServer = startServerInBackground(true)
if existingServer != nil {
log.Info().Msg("✅ server restarted")
}
case 'c':
log.Info().Msg("⌨️ [c] running convert...")
go func() {
if err := runConvertPlugin(); err != nil {
log.Error().Err(err).Msg("convert failed")
} else {
log.Info().Msg("✅ convert done")
}
}()
case 's':
log.Info().Msg("⌨️ [s] running seeder...")
go func() {
if err := runSeeder(); err != nil {
log.Error().Err(err).Msg("seeder failed")
} else {
log.Info().Msg("✅ seeder done")
}
}()
case 'm':
log.Info().Msg("⌨️ [m] running migrations...")
go func() {
if err := runMigrations(); err != nil {
log.Error().Err(err).Msg("migrations failed")
} else {
log.Info().Msg("✅ migrations done")
}
}()
case 'a':
log.Info().Msg("⌨️ [a] running all (migrate + convert + seed + restart)...")
go func() {
if err := runMigrations(); err != nil {
log.Error().Err(err).Msg("migrations failed")
return
}
if err := runConvertPlugin(); err != nil {
log.Error().Err(err).Msg("convert failed")
return
}
if err := runSeeder(); err != nil {
log.Error().Err(err).Msg("seeder failed")
return
}
restart <- true
log.Info().Msg("✅ all done")
}()
case 'h', '?':
printKeyboardShortcuts()
}
case <-restart:
log.Debug().Msg("restarting backend...")
if existingServer != nil {
stopServer(existingServer)
}
killPortProcess(port)
existingServer = startServerInBackground(true)
if existingServer == nil {
log.Error().Msg("server restart failed, continuing to watch for changes")
continue
}
log.Debug().Msg("✅ restarted backend")
case <-sigChan:
log.Info().Msg("received shutdown signal")
return nil
case <-quit:
return nil
}
}
}
func setupPaths() (paths, error) {
backend, err := os.Getwd()
if err != nil {
return paths{}, fmt.Errorf("get current dir: %w", err)
}
startPath := filepath.Dir(backend)
dirs := strings.Split(startPath, string(os.PathSeparator))
if len(dirs) < 2 {
return paths{}, fmt.Errorf("invalid path structure")
}
return paths{
backend: backend,
frontend: path.Join(startPath, "frontend"),
orgName: dirs[len(dirs)-2],
}, nil
}
func installDependencies(frontendPath string) error {
for _, fn := range []func() error{
installBun,
func() error { return installFrontendDependencies(frontendPath) },
installPrettier,
installSqlBoiler,
installSqlBoilerMysqlDriver,
} {
if err := fn(); err != nil {
return err
}
}
return nil
}
func installBun() error {
// Only install Bun if it is not already installed
if _, err := exec.LookPath("bun"); err == nil {
log.Debug().Msg("bun already installed, skipping installation")
return nil
}
log.Debug().Msg("install bun")
cmd := exec.Command("sh", "-c", "curl -fsSL https://bun.com/install | bash")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func installFrontendDependencies(frontendPath string) error {
log.Debug().Msg("install frontend dependencies")
cmd := exec.Command("bun", "install")
cmd.Dir = frontendPath
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func installPrettier() error {
log.Debug().Msg("install prettier")
cmd := exec.Command("npm", "install", "-g", "prettier@latest", "--force", "--silent")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func installSqlBoiler() error {
log.Debug().Msg("install sqlboiler")
cmd := exec.Command("go", "install", "github.com/aarondl/sqlboiler/v4@latest")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func installSqlBoilerMysqlDriver() error {
log.Debug().Msg("install sqlboiler mysql driver")
cmd := exec.Command("go", "install", "github.com/aarondl/sqlboiler/v4/drivers/sqlboiler-mysql@latest")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func sendNotification(title, message string) {
if err := beeep.Notify(title, message, "./icon.png"); err != nil {
log.Error().Err(err).Msg("could not notify")
}
}
func stopServer(cmd *exec.Cmd) {
if cmd != nil && cmd.Process != nil {
specific.Kill(cmd) // No error return expected
}
killPortProcess(port)
}
func startServerInBackground(restart bool) *exec.Cmd {
killPortProcess(port)
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.Command("cmd.exe", "/C", fmt.Sprintf("set WR_RESTART=%v && go run server.go", restart))
} else {
cmd = exec.Command("/bin/sh", "-c", fmt.Sprintf("WR_RESTART=%v go run server.go", restart))
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = nil // Don't inherit stdin, it's used for keyboard shortcuts
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} // Ensure process group is set for proper cleanup
go func() {
if err := cmd.Run(); err != nil && !strings.Contains(err.Error(), "signal: killed") {
sendNotification("Server Error", fmt.Sprintf("failed to run server: %v", err))
log.Error().Err(err).Msg("failed to run server")
}
}()
// Wait briefly to check if the server started successfully
time.Sleep(500 * time.Millisecond)
if cmd.Process == nil || cmd.ProcessState != nil && cmd.ProcessState.Exited() {
log.Error().Msg("server failed to start or exited immediately")
return nil
}
return cmd
}
func startDbInDocker() *exec.Cmd {
cmd := exec.Command("docker", "compose", "up", "-d")
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
sendNotification("DB Error", "failed to start db")
log.Fatal().Err(err).Msg("failed to start db")
}
return cmd
}
func stopDocker() {
cmd := exec.Command("docker", "compose", "down")
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Error().Err(err).Msg("failed to stop docker containers")
}
}
func killPortProcess(port string) {
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.Command("powershell", "-Command", fmt.Sprintf("Stop-Process -Id (Get-NetTCPConnection -LocalPort %s).OwningProcess -Force", port))
} else {
cmd = exec.Command("bash", "-c", fmt.Sprintf("lsof -i tcp:%s | grep LISTEN | awk '{print $2}' | xargs kill -9", port))
}
if err := cmd.Run(); err != nil {
log.Debug().Err(err).Msg("error killing port process")
}
}
func killOtherWrInstances() int {
currentPid := os.Getpid()
killed := 0
if runtime.GOOS == "windows" {
// On Windows, use tasklist and taskkill
cmd := exec.Command("powershell", "-Command",
fmt.Sprintf("Get-Process -Name wr -ErrorAction SilentlyContinue | Where-Object { $_.Id -ne %d } | Stop-Process -Force", currentPid))
if err := cmd.Run(); err == nil {
killed++ // Can't easily count on Windows
}
} else {
// On Unix, use pgrep to find wr processes and kill them
cmd := exec.Command("pgrep", "-x", "wr")
output, err := cmd.Output()
if err != nil {
return 0
}
pids := strings.Split(strings.TrimSpace(string(output)), "\n")
for _, pidStr := range pids {
pid, err := strconv.Atoi(pidStr)
if err != nil || pid == currentPid {
continue
}
if proc, err := os.FindProcess(pid); err == nil {
if err := proc.Kill(); err == nil {
killed++
}
}
}
}
return killed
}
func runInitialSetup() error {
for _, fn := range []func() error{
dropDatabase,
runMigrations,
runConvertPlugin,
runMergeSchemasWithRelay,
runSeeder,
} {
if err := fn(); err != nil {
return err
}
}
log.Info().Msg("Done migrating :)")
return nil
}
func runMigrations() error {
log.Debug().Msg("run migrations")
cmd := exec.Command("go", "run", "migrate.go")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func dropDatabase() error {
log.Debug().Msg("drop db")
name := os.Getenv("DATABASE_NAME")
_, err := db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS `%v`", name))
if err != nil {
return fmt.Errorf("drop database: %w", err)
}
_, err = db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%v`", name))
if err != nil {
return fmt.Errorf("create database: %w", err)
}
log.Debug().Msg("✅ dropped db")
return nil
}
func runConvertPlugin() error {
log.Debug().Msg("run ./convert")
cmd := exec.Command("go", "run", ".")
cmd.Dir = "./convert"
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func runMergeSchemasWithRelay() error {
if err := runMergeSchemas(); err != nil {
return err
}
return runRelay()
}
func runMergeSchemas() error {
log.Debug().Msg("run merge-schemas")
cmd := exec.Command("bun", "run", "merge-schemas")
cmd.Dir = "../frontend"
return cmd.Run()
}
func runRelay() error {
log.Debug().Msg("run relay.dev")
cmd := exec.Command("bun", "run", "relay")
cmd.Dir = "../frontend"
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func runSeeder() error {
log.Debug().Msg("run ./seed")
cmd := exec.Command("go", "run", ".")
cmd.Dir = "./seed"
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = append(os.Environ(), "DATABASE_DEBUG=false")
return cmd.Run()
}
func watch(ctx context.Context, backendPath, frontendPath string, goOnly bool) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal().Err(err).Msg("cannot start file watcher")
}
defer watcher.Close()
watchPaths := append(getDirectoryWithSubDirectories(),
"../frontend/schema_custom.graphql",
"../frontend/src/__generated__",
)
for _, w := range watchPaths {
if err := watcher.Add(w); err != nil {
log.Error().Err(err).Str("path", w).Msg("failed to watch path")
}
}
if goOnly {
log.Info().Msg("file watcher started (fsnotify) - Go files only mode")
} else {
log.Info().Msg("file watcher started (fsnotify)")
}
for {
select {
case <-ctx.Done():
log.Debug().Msg("file watcher stopping...")
return
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write ||
event.Op&fsnotify.Create == fsnotify.Create ||
event.Op&fsnotify.Rename == fsnotify.Rename {
fileChanged(event, goOnly)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Error().Err(err).Msg("error while watching files")
}
}
}
var debounced = debounce.New(200 * time.Millisecond)
func runSqlChanged() {
if err := dropDatabase(); err != nil {
log.Fatal().Err(err).Msg("sql changed: drop database")
}
if err := runMigrations(); err != nil {
log.Fatal().Err(err).Msg("sql changed: run migrations")
}
if err := runConvertPlugin(); err != nil {
log.Fatal().Err(err).Msg("sql changed: run convert plugin")
}
if err := runSeeder(); err != nil {
log.Fatal().Err(err).Msg("sql changed: run seeder")
}
if err := runMergeSchemasWithRelay(); err != nil {
log.Fatal().Err(err).Msg("sql changed: run merge schemas with relay")
}
restart <- true
}
func runSchemaChanged() {
if err := runConvertPlugin(); err != nil {
log.Fatal().Err(err).Msg("schema changed: run convert plugin")
}
if err := runMergeSchemasWithRelay(); err != nil {
log.Fatal().Err(err).Msg("schema changed: run merge schemas with relay")
}
restart <- true
}
func runSeedChanged() {
if err := runSeeder(); err != nil {
log.Fatal().Err(err).Msg("seed changed: run seeder")
}
}
func runGoChanged() {
restart <- true
}
func runMigrationsChanged() {
if err := runMigrations(); err != nil {
log.Fatal().Err(err).Msg("migrations changed: run migrations")
}
if err := runConvertPlugin(); err != nil {
log.Fatal().Err(err).Msg("migrations changed: run convert plugin")
}
restart <- true
}
func fileChanged(event fsnotify.Event, goOnly bool) {
log.Debug().Str("file", event.Name).Msg("modified file")
isGeneratedGo := strings.Contains(event.Name, "generated_") &&
(strings.Contains(event.Name, ".go") || strings.Contains(event.Name, ".gohtml"))
if isGeneratedGo || strings.Contains(event.Name, "__generated__/") {
log.Debug().Msg("generated files changed, skipping")
return
}
// In goOnly mode, only restart server on Go file changes
if goOnly {
if strings.Contains(event.Name, ".go") || strings.Contains(event.Name, ".gohtml") || strings.Contains(event.Name, ".env") {
log.Debug().Msg("restart server (go-only mode)")
debounced(runGoChanged)
}
return
}
switch {
case strings.Contains(event.Name, ".sql"):
log.Debug().Msg("sql changed, run migrations + convert plugin")
debounced(runSqlChanged)
case strings.Contains(event.Name, ".graphql"):
log.Debug().Msg("run convert & merge schemas with relay")
debounced(runSchemaChanged)
case strings.Contains(event.Name, "seed/"):
log.Debug().Msg("re-run seed.go")
debounced(runSeedChanged)
case strings.Contains(event.Name, ".env") ||
strings.Contains(event.Name, ".go") ||
strings.Contains(event.Name, ".gohtml"):
log.Debug().Msg("restart server")
debounced(runGoChanged)
case strings.Contains(event.Name, "migrations/"):
log.Debug().Msg("run migrations + convert plugin")
debounced(runMigrationsChanged)
}
}
func getDirectoryWithSubDirectories() []string {
var dirs []string
dirs = append(dirs, "./")
if err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Fatal().Err(err).Msg("walking files")
}
if info.IsDir() && !strings.Contains(path, "models/") && !strings.Contains(path, ".idea") {
dirs = append(dirs, path)
}
return nil
}); err != nil {
log.Fatal().Err(err).Msg("could not get dir with sub dirs")
}
return dirs
}
func printKeyboardShortcuts() {
fmt.Println("\n┌──────────────────────────────────────────┐")
fmt.Println("│ Commands (type + Enter) │")
fmt.Println("├──────────────────────────────────────────┤")
fmt.Println("│ r - Restart server │")
fmt.Println("│ c - Run convert │")
fmt.Println("│ s - Run seeder │")
fmt.Println("│ m - Run migrations │")
fmt.Println("│ a - Run all (migrate+convert+seed) │")
fmt.Println("│ h - Show this help │")
fmt.Println("│ ^C - Quit │")
fmt.Println("└──────────────────────────────────────────┘\n")
}
func readKeyboardInput(ctx context.Context, keyChan chan<- rune) {
reader := bufio.NewReader(os.Stdin)
lineChan := make(chan string)
// Read lines in a separate goroutine
go func() {
for {
line, err := reader.ReadString('\n')
if err != nil {
close(lineChan)
return
}
lineChan <- strings.TrimSpace(line)
}
}()
for {
select {
case <-ctx.Done():
return
case line, ok := <-lineChan:
if !ok {
return
}
if len(line) > 0 {
keyChan <- rune(line[0])
}
}
}
}