This repository has been archived by the owner on Sep 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgomon.go
96 lines (78 loc) · 1.5 KB
/
gomon.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
package main
import (
"os"
"os/exec"
"os/signal"
"fmt"
"log"
"syscall"
"github.com/fsnotify/fsnotify"
)
func main() {
if len(os.Args) < 2 {
log.Fatal("Please provide a file to watch")
}
path := os.Args[1]
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
defer watcher.Close()
defer fmt.Println("")
done := make(chan bool)
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt)
var pgid int
pgid = runCmd(path, true)
go func () {
<-signalChan
syscall.Kill(-pgid, 15)
done <- true
}()
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write {
syscall.Kill(-pgid, 15)
pgid = runCmd(path, false)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
fmt.Println("Error happened 😢", err)
}
}
}()
err = watcher.Add(path)
if err != nil {
panic(err)
}
<- done
}
func runCmd(path string, first bool) (pgid int) {
cmd := exec.Command("go", "run", path)
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Start()
if first {
formatPrint("Starting to watch")
} else {
formatPrint("Restarting due to change")
}
id, _ := syscall.Getpgid(cmd.Process.Pid)
return id
}
func formatPrint(msg string) {
fmt.Println("")
fmt.Println("\x1b[36m*")
fmt.Println(" " + msg)
fmt.Println("*\x1b[0m")
fmt.Println("")
}