SHOW:
|
|
- or go back to the newest paste.
| 1 | package main | |
| 2 | ||
| 3 | import ( | |
| 4 | "flag" | |
| 5 | "fmt" | |
| 6 | "log" | |
| 7 | "os" | |
| 8 | "os/exec" | |
| 9 | "strconv" | |
| 10 | "sync" | |
| 11 | "time" | |
| 12 | ) | |
| 13 | ||
| 14 | type Color string | |
| 15 | ||
| 16 | const ( | |
| 17 | Version = "0.1" | |
| 18 | ||
| 19 | ColorGreen = "2" | |
| 20 | ColorYellow = "3" | |
| 21 | ColorGray = "7" | |
| 22 | ) | |
| 23 | ||
| 24 | var ( | |
| 25 | roIndex int | |
| 26 | ) | |
| 27 | ||
| 28 | func printLog(color Color, args ...interface{}) {
| |
| 29 | format := []interface{}{"- \x1b[3" + color + "m[godemon]"}
| |
| 30 | format = append(format, args...) | |
| 31 | format = append(format, "\x1b[0m") | |
| 32 | log.Println(format...) | |
| 33 | } | |
| 34 | ||
| 35 | func startGo(file string, args []string, gwg *sync.WaitGroup, kill *chan bool) {
| |
| 36 | params := []string{"run", file}
| |
| 37 | params = append(params, args...) | |
| 38 | params = append(params, strconv.Itoa(roIndex)) | |
| 39 | roIndex += 1 | |
| 40 | ||
| 41 | printLog(ColorGreen, "starting `"+file+"`") | |
| 42 | ||
| 43 | cmd := exec.Command("go", params...)
| |
| 44 | cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr | |
| 45 | cmd.Start() | |
| 46 | ||
| 47 | var wg sync.WaitGroup | |
| 48 | wg.Add(1) | |
| 49 | ||
| 50 | go func() {
| |
| 51 | <-*kill | |
| 52 | - | //cmd.Process.Kill() |
| 52 | + | cmd.Process.Kill() // - убийство |
| 53 | - | cmd.Process.Signal(os.Kill) |
| 53 | + | |
| 54 | }() | |
| 55 | ||
| 56 | cmd.Wait() | |
| 57 | close(*kill) | |
| 58 | wg.Wait() | |
| 59 | ||
| 60 | printLog(ColorGreen, "clean exit - waiting for changes before restart") | |
| 61 | ||
| 62 | gwg.Done() | |
| 63 | } | |
| 64 | ||
| 65 | func init() {
| |
| 66 | flag.Parse() | |
| 67 | log.SetPrefix("\x1b[3" + ColorGray + "m")
| |
| 68 | } | |
| 69 | ||
| 70 | func main() {
| |
| 71 | pattern := *flag.String("w", "**/*.*", "watching glob pattern")
| |
| 72 | ||
| 73 | if len(flag.Args()) == 0 {
| |
| 74 | fmt.Println("Usage: godemon gofile [args]\n\n" +
| |
| 75 | "See \"godemon --help\" for more.") | |
| 76 | os.Exit(0) | |
| 77 | } | |
| 78 | ||
| 79 | printLog(ColorYellow, "v"+Version) | |
| 80 | printLog(ColorYellow, "watching:", pattern) | |
| 81 | ||
| 82 | file := flag.Arg(0) + ".go" | |
| 83 | args := flag.Args()[1:] | |
| 84 | ||
| 85 | for {
| |
| 86 | var wg sync.WaitGroup | |
| 87 | kill := make(chan bool) | |
| 88 | ||
| 89 | wg.Add(1) | |
| 90 | go startGo(file, args, &wg, &kill) | |
| 91 | time.Sleep(time.Second) | |
| 92 | kill <- true | |
| 93 | wg.Wait() | |
| 94 | } | |
| 95 | } |