forked from yosssi/goat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
101 lines (87 loc) · 2.21 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
package main
import (
"flag"
"fmt"
"log"
"os"
"os/exec"
"runtime"
"strings"
"github.com/yosssi/goat/consts"
"github.com/yosssi/goat/context"
)
// main executes main processes.
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
version := flag.Bool("v", false, "Show Goat version")
interval := flag.Int("i", consts.DefaultInterval, "An interval(ms) of a watchers' file check loop")
flag.Parse()
if *version {
fmt.Printf("Goat %s\n", consts.Version)
os.Exit(0)
}
ctx, err := context.NewContext(*interval)
if err != nil {
log.Fatal(err)
}
initTasks := ctx.Config.InitTasks
if initTasks != nil && len(initTasks) > 0 {
executeTasks(initTasks, nil)
}
jobsC := make(chan context.Job, consts.JobsChannelBuffer)
launchWatchers(ctx, jobsC)
handleJobs(jobsC)
}
// launchWatchers launches watchers.
func launchWatchers(ctx *context.Context, jobsC chan<- context.Job) {
for _, watcher := range ctx.Config.Watchers {
go watcher.Launch(ctx, jobsC)
}
}
// handleJobs handle jobs.
func handleJobs(jobsC <-chan context.Job) {
for job := range jobsC {
watcher := job.Watcher
watcher.Printf("%s", job.Message)
executeTasks(watcher.Tasks, watcher)
}
}
// executeTasks executes tasks.
func executeTasks(tasks []*context.Task, watcher *context.Watcher) {
for _, task := range tasks {
command := task.Command
tokens := strings.Split(command, " ")
name := tokens[0]
var cmdArg []string
if len(tokens) > 1 {
cmdArg = tokens[1:]
}
cmd := exec.Command(name, cmdArg...)
if task.Nowait {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
printf(watcher, "execute(nowait): %s", command)
if err := cmd.Start(); err != nil {
printf(watcher, "An error occurred: %s \n\n", err.Error())
} else {
printf(watcher, "end(nowait): %s \n\n", command)
}
} else {
printf(watcher, "execute: %s", command)
bytes, err := cmd.CombinedOutput()
if err != nil {
printf(watcher, "An error occurred: %s - %s \n\n", cmd.Stderr, err.Error())
} else {
fmt.Print(string(bytes))
printf(watcher, "end: %s \n\n", command)
}
}
}
}
func printf(watcher *context.Watcher, format string, v ...interface{}) {
if watcher != nil {
watcher.Printf(format, v)
} else {
log.Printf(format, v)
}
}