github.com/mkasner/goat@v0.0.0-20190419083224-77b17249a8e3/main.go (about) 1 package main 2 3 import ( 4 "flag" 5 "fmt" 6 "log" 7 "os" 8 "os/exec" 9 "runtime" 10 "strings" 11 12 "github.com/yosssi/goat/config" 13 "github.com/yosssi/goat/consts" 14 "github.com/yosssi/goat/context" 15 ) 16 17 // main executes main processes. 18 func main() { 19 runtime.GOMAXPROCS(runtime.NumCPU()) 20 21 version := flag.Bool("v", false, "Show Goat version") 22 configFile := flag.String("c", "", "Show Goat version") 23 interval := flag.Int("i", consts.DefaultInterval, "An interval(ms) of a watchers' file check loop") 24 flag.Parse() 25 26 if *configFile != "" { 27 if strings.HasSuffix(*configFile, "yml") { 28 config.YAMLConfigFile = *configFile 29 } else if strings.HasSuffix(*configFile, "json") { 30 config.JSONConfigFile = *configFile 31 } 32 } 33 34 if *version { 35 fmt.Printf("Goat %s\n", consts.Version) 36 os.Exit(0) 37 } 38 39 ctx, err := context.NewContext(*interval) 40 if err != nil { 41 log.Fatal(err) 42 } 43 44 initTasks := ctx.Config.InitTasks 45 if initTasks != nil && len(initTasks) > 0 { 46 executeTasks(initTasks, nil) 47 } 48 49 jobsC := make(chan context.Job, consts.JobsChannelBuffer) 50 51 launchWatchers(ctx, jobsC) 52 53 handleJobs(jobsC) 54 } 55 56 // launchWatchers launches watchers. 57 func launchWatchers(ctx *context.Context, jobsC chan<- context.Job) { 58 for _, watcher := range ctx.Config.Watchers { 59 go watcher.Launch(ctx, jobsC) 60 } 61 } 62 63 // handleJobs handle jobs. 64 func handleJobs(jobsC <-chan context.Job) { 65 for job := range jobsC { 66 watcher := job.Watcher 67 watcher.Printf("%s", job.Message) 68 executeTasks(watcher.Tasks, watcher) 69 } 70 } 71 72 // executeTasks executes tasks. 73 func executeTasks(tasks []*context.Task, watcher *context.Watcher) { 74 for _, task := range tasks { 75 command := task.Command 76 tokens := strings.Split(command, " ") 77 name := tokens[0] 78 var cmdArg []string 79 if len(tokens) > 1 { 80 cmdArg = tokens[1:] 81 } 82 cmd := exec.Command(name, cmdArg...) 83 cmd.Stdout = os.Stdout 84 cmd.Stderr = os.Stderr 85 if task.Nowait { 86 printf(watcher, "execute(nowait): %s", command) 87 if err := cmd.Start(); err != nil { 88 printf(watcher, "An error occurred: %s \n\n", err.Error()) 89 } else { 90 printf(watcher, "end(nowait): %s \n\n", command) 91 } 92 } else { 93 printf(watcher, "execute: %s", command) 94 err := cmd.Run() 95 if err != nil { 96 printf(watcher, "An error occurred: %s \n\n", err.Error()) 97 } else { 98 printf(watcher, "end: %s \n\n", command) 99 } 100 } 101 } 102 } 103 104 func printf(watcher *context.Watcher, format string, v ...interface{}) { 105 if watcher != nil { 106 watcher.Printf(format, v) 107 } else { 108 log.Printf(format, v) 109 } 110 }