Skip to content

Instantly share code, notes, and snippets.

@mmcdaris
Created February 25, 2014 10:15
Show Gist options
  • Save mmcdaris/9206314 to your computer and use it in GitHub Desktop.
Save mmcdaris/9206314 to your computer and use it in GitHub Desktop.
restart an upstart script when there is an inotify event
// this is almost complete :)
// name: watchfiles.go
// purpose: emit a restart
package main
import (
"log" // printing
"code.google.com/p/go.exp/inotify" // inotify events
"os" // argument handling
"os/exec" // used to call initctl restart process name
)
func main() {
args := os.Args[:]
if len(args) == 3 {
file := args[1]
job := args[2]
log.Printf("Gophers now Watching your file:\033[35m %s \033[0m\nWhen Changed,\033[34m %s, \033[0m will be restarted\n", file, job)
watch(file, job)
} else {
log.Printf("usage: \033[34mwatchfiles\033[0m file_to_watch upstart_job\n")
}
}
func restartJob(file string, job string) {
out, err := exec.Command("restart", job).Output()
if err != nil {
log.Println("ERR: restart job failed")
log.Println(out)
log.Fatal(err)
}
log.Printf("Result Of Command:\n%s\n", out)
}
func watch(file string, job string) {
watcher, err := inotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
err = watcher.Watch(file)
if err != nil {
log.Fatal(err)
}
for {
select {
case ev := <-watcher.Event:
log.Println("Event:", ev)
restartJob(file, job)
case err := <-watcher.Error:
log.Println("Error:", err)
}
}
}
@mmcdaris
Copy link
Author

Usage: sudo watchfiles /path/to/project/.git upstart_job_name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment