-
Notifications
You must be signed in to change notification settings - Fork 0
/
wr.go
489 lines (413 loc) · 12.8 KB
/
wr.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
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
package main
import (
"database/sql"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"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"
)
// https://stackoverflow.com/questions/36419054/go-projects-main-goroutine-sleep-forever
var (
quit = make(chan bool)
restart = make(chan bool)
port = os.Getenv("PORT")
)
var db *sql.DB
func main() {
// let us have colored logs
helpers.ConfigureLogger()
app := &cli.App{
//Flags: []cli.Flag {
// &cli.StringFlag{
// Name: "lang",
// Value: "english",
// Usage: "language for the greeting",
// },
//},
Name: "wr",
Usage: "wr is an internal tool to improve developer experience at webRidge",
Action: start,
}
err := app.Run(os.Args)
if err != nil {
log.Fatal().Err(err).Msg("can not run app")
}
// to quit program from somewhere else use close(quit)
<-quit
}
func start(c *cli.Context) error {
fmt.Println(" _ _____ _ _ \n | | | __ \\(_) | | \n __ _____| |__ | |__) |_ __| | __ _ ___ \n \\ \\ /\\ / / _ \\ '_ \\| _ /| |/ _` |/ _` |/ _ \\\n \\ V V / __/ |_) | | \\ \\| | (_| | (_| | __/\n \\_/\\_/ \\___|_.__/|_| \\_\\_|\\__,_|\\__, |\\___|\n __/ | \n |___/ ") //nolint:lll
fmt.Println("")
backendPath, err := os.Getwd()
checkErrorWithFatal("cant get current dir", err)
startPath := filepath.Dir(backendPath)
directories := strings.Split(startPath, string(os.PathSeparator))
organizationName := directories[len(directories)-2]
log.Debug().Str("organization", organizationName).Msg("starting backend and dependencies")
frontendPath := path.Join(startPath, "frontend")
installYarn1()
installPrettier()
installFrontendDependencies()
installSqlBoiler()
installSqlBoilerMysqlDriver()
// first we start the database
go startDbInDocker()
// wait till the db is started
time.Sleep(1 * time.Second)
db = helpers.WaitForDatabase()
// try to start server, if it fails, we will try again
existingServer := startServerInBackground(true)
dropDatabase()
runMigrations()
runMergeSchemasWithRelay()
runConvertPlugin()
runSeeder()
// start watching migrations/code
go watch(backendPath, frontendPath)
// start server and wait for restarts
existingServer = startServerInBackground(false)
defer stopServer(existingServer)
for <-restart {
log.Debug().Msg("restarting backend...")
stopServer(existingServer)
existingServer = startServerInBackground(true)
log.Debug().Msg("✅ restarted backend..")
}
return nil
}
func installYarn1() {
log.Debug().Msg("install yarn1")
cmd := exec.Command("npm", "install", "-g", "yarn@1", "--force", "--silent")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
checkError("failed to install yarn1", err)
log.Debug().Msg("✅ installed yarn1")
}
func installFrontendDependencies() {
log.Debug().Msg("install frontend dependencies")
cmd := exec.Command("yarn", "install")
cmd.Dir = "../frontend"
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
checkError("failed to install frontend dependencies", err)
log.Debug().Msg("✅ installed frontend dependencies")
}
func installPrettier() {
log.Debug().Msg("install prettier")
cmd := exec.Command("npm", "install", "-g", "prettier@latest", "--force", "--silent")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
checkError("failed to install prettier", err)
log.Debug().Msg("✅ installed prettier")
}
func installSqlBoiler() {
log.Debug().Msg("install sqlboiler")
cmd := exec.Command("go", "install", "github.com/volatiletech/sqlboiler/v4@latest")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
checkError("failed to install sqlboiler", err)
log.Debug().Msg("✅ installed sqlboiler")
}
func installSqlBoilerMysqlDriver() {
log.Debug().Msg("install sqlboiler mysql driver")
cmd := exec.Command("go", "install", "github.com/volatiletech/sqlboiler/v4/drivers/sqlboiler-mysql@latest")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
checkError("failed to install sqlboiler mysql driver", err)
log.Debug().Msg("✅ installed sqlboiler mysql driver")
}
func notify(title, message string) {
err := beeep.Notify(title, message, "./icon.png")
checkError("could not notify", err)
}
func stopServer(existingServer *exec.Cmd) {
// https://stackoverflow.com/a/68179972/2508481
// Send kill signal to the process group instead of single process (it gets the same value as the PID, only negative)
if existingServer != nil && existingServer.Process != nil {
//TODO: implement global kill for all systems
specific.Kill(existingServer)
}
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
// https://stackoverflow.com/a/68179972/2508481
// Request the OS to assign process group to the new process, to which all its children will belong
// cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.SysProcAttr = &syscall.SysProcAttr{}
go func() {
err := cmd.Run()
if err != nil {
checkServerError(err)
}
defer func() {
stopServer(cmd)
}()
}()
return cmd
}
func checkServerError(err error) {
if err != nil && strings.Contains(err.Error(), "signal: killed") {
return
}
checkError("failed to run server", err)
}
func runMigrations() {
log.Debug().Msg("run migrations")
cmd := exec.Command("go", "run", "migrate.go")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
checkError("failed to run migrations", err)
log.Debug().Msg("✅ done migrating!")
return
}
func dropDatabase() {
log.Debug().Msg("drop db")
name := os.Getenv("DATABASE_NAME")
var err error
_, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS `%v`", name))
checkErrorWithFatal("could not drop database", err)
_, err = db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%v`", name))
checkErrorWithFatal("could not create database", err)
log.Debug().Msg("✅ dropped db!")
}
func runConvertPlugin() {
log.Debug().Msg("start convert/convert.go")
cmd := exec.Command("go", "run", "convert.go")
cmd.Dir = "./convert"
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
checkError("failed to run convert/convert.go", err)
log.Debug().Msg("✅ done convert/convert.go")
}
func killPortProcess(port string) {
if runtime.GOOS == "windows" {
command := fmt.Sprintf("(Get-NetTCPConnection -LocalPort %s).OwningProcess", port)
execKillCommand(exec.Command("powershell", "-Command", fmt.Sprintf("& {Stop-Process -Id (%s) -Force}", command)))
} else {
command := fmt.Sprintf("lsof -i tcp:%s | grep LISTEN | awk '{print $2}' | xargs kill -9", port)
execKillCommand(exec.Command("bash", "-c", command))
}
}
// Execute command and return exited code.
func execKillCommand(cmd *exec.Cmd) {
var waitStatus syscall.WaitStatus
if err := cmd.Run(); err != nil {
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("Error: %s\n", err.Error()))
}
if exitError, ok := err.(*exec.ExitError); ok {
waitStatus = exitError.Sys().(syscall.WaitStatus)
fmt.Printf("Error during killing (exit code: %s)\n", []byte(fmt.Sprintf("%d", waitStatus.ExitStatus())))
}
} else {
waitStatus = cmd.ProcessState.Sys().(syscall.WaitStatus)
fmt.Printf("Port successfully killed (exit code: %s)\n", []byte(fmt.Sprintf("%d", waitStatus.ExitStatus())))
}
}
func runMergeSchemasWithRelay() {
runMergeSchemas()
runRelay()
}
func runMergeSchemas() {
log.Debug().Msg("run merge-schemas")
cmd := exec.Command("yarn", "merge-schemas")
cmd.Dir = "../frontend"
// cmd.Stdout = os.Stdout
// cmd.Stderr = os.Stderr
err := cmd.Run()
checkError("failed to run convert/convert.go", err)
log.Debug().Msg("✅ done with merge-schemas")
}
func runRelay() {
log.Debug().Msg("run relay.dev")
cmd := exec.Command("yarn", "relay")
cmd.Dir = "../frontend"
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
checkError("failed to run convert/convert.go", err)
log.Debug().Msg("✅ done with relay.dev")
}
func runSeeder() {
log.Debug().Msg("start seed/seed.go")
cmd := exec.Command("go", "run", "seed.go")
cmd.Dir = "./seed"
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "DATABASE_DEBUG=false")
err := cmd.Run()
checkError("failed to run seed/seed.go", err)
log.Debug().Msg("✅ done seed/seed.go")
}
func watch(backendPath, frontendPath string) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal().Err(err).Msg("can not start file watcher")
}
defer func(watcher *fsnotify.Watcher) {
err := watcher.Close()
if err != nil {
log.Fatal().Err(err).Msg("could not stop file watcher")
}
}(watcher)
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write {
// log.Debug().Str("file", event.Name).Msg("modified file")
fileChanged(event)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Err(err).Msg("error while watching files")
}
}
}()
filesOrDirectoriesToWatch := getDirectoryWithSubDirectories()
filesOrDirectoriesToWatch = append(filesOrDirectoriesToWatch, []string{
"../frontend/schema_custom.graphql",
"../frontend/src/__generated__",
}...)
// fmt.Println(filesOrDirectoriesToWatch)
for _, w := range filesOrDirectoriesToWatch {
err = watcher.Add(w)
checkError(fmt.Sprintf("failed to watch %v", w), err)
}
<-done
}
var debounced = debounce.New(200 * time.Millisecond)
func runSqlChanged() {
dropDatabase()
runMigrations()
runConvertPlugin()
runSeeder()
runMergeSchemasWithRelay()
restart <- true
}
func runSchemaChanged() {
runConvertPlugin()
runMergeSchemasWithRelay()
restart <- true
}
func runSeedChanged() {
runSeeder()
}
func runGoChanged() {
restart <- true
}
func runMigrationsChanged() {
runMigrations()
runConvertPlugin()
restart <- true
}
func fileChanged(event fsnotify.Event) {
envChanged := strings.Contains(event.Name, ".env")
sqlChanged := strings.Contains(event.Name, ".sql")
schemaChanged := strings.Contains(event.Name, ".graphql")
seedChanged := strings.Contains(event.Name, "seed/")
generatedChanged := strings.Contains(event.Name, "__generated__/")
migrationsChanged := strings.Contains(event.Name, "migrations/")
goChanged := strings.Contains(event.Name, ".go") || strings.Contains(event.Name, ".gohtml")
goGeneratedChanged := strings.Contains(event.Name, "generated_") && goChanged
log.Debug().Str("file", event.Name).Msg("modified file")
// we only change models from here so we don't need to subscribe
if goGeneratedChanged {
log.Debug().Msg("generated files from go changed, do nothing")
return
}
switch true {
case generatedChanged:
log.Debug().Msg("generated files relay.dev changed, do nothing")
case sqlChanged:
log.Debug().Msg("sql changed, run migrations + convert plugin")
debounced(runSqlChanged)
case schemaChanged:
log.Debug().Msg("run convert & merge schema's with relay")
debounced(runSchemaChanged)
case seedChanged:
log.Debug().Msg("re-rerun seed.go")
debounced(runSeedChanged)
case goChanged, envChanged:
log.Debug().Bool("goChanged", goChanged).Bool("envChanged", envChanged).Msg("restart server")
debounced(runGoChanged)
case migrationsChanged:
log.Debug().Bool("migrationsChanged", migrationsChanged).Msg("run migrations + convert plugin")
debounced(runMigrationsChanged)
}
}
func startDbInDocker() *exec.Cmd {
cmd := exec.Command("docker", "compose", "up", "-d", "db")
// cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
checkError("failed to start db", cmd.Run())
return cmd
}
func checkError(s string, err error) {
if err != nil {
notify("Error 🔥🔥🔥", s)
log.Error().Err(err).Msg("🔥🔥🔥 " + s)
}
}
func checkErrorWithFatal(s string, err error) {
if err != nil {
notify("Fatal Error 🔥🔥🔥", s)
log.Fatal().Err(err).Msg("🔥🔥🔥 " + s)
}
}
func getDirectoryWithSubDirectories() []string {
var a []string
a = append(a, "./")
err := filepath.Walk(".",
func(path string, info os.FileInfo, err error) error {
checkErrorWithFatal("walking files", err)
if info.IsDir() {
if strings.Contains(path, "models/") {
return nil
}
if strings.Contains(path, ".idea") {
return nil
}
a = append(a, path)
}
return nil
})
checkErrorWithFatal("could not get dir with sub dirs", err)
return a
}