Created
June 15, 2015 22:26
-
-
Save ericchiang/f34afea8111579661908 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| "os" | |
| "os/exec" | |
| "path/filepath" | |
| "time" | |
| ) | |
| func usage() { | |
| fmt.Fprintf(os.Stderr, "usage: go-watch [dir] [cmd]\n") | |
| os.Exit(2) | |
| } | |
| func main() { | |
| if len(os.Args) < 3 { | |
| usage() | |
| } | |
| runCmd := func() error { | |
| cmd := exec.Command(os.Args[2], os.Args[3:]...) | |
| cmd.Stdout = os.Stdout | |
| cmd.Stdout = os.Stderr | |
| return cmd.Run() | |
| } | |
| if err := runCmd(); err != nil { | |
| log.Fatal(err) | |
| } | |
| dir := os.Args[1] | |
| lastMod := time.Now() | |
| lastExec := time.Now() | |
| wf := func(path string, info os.FileInfo, err error) error { | |
| if err != nil { | |
| return err | |
| } | |
| mt := info.ModTime() | |
| if mt.After(lastMod) { | |
| lastMod = mt | |
| } | |
| return nil | |
| } | |
| for { | |
| time.Sleep(1 * time.Second) | |
| if err := filepath.Walk(dir, wf); err != nil { | |
| log.Fatal(err) | |
| } | |
| if lastExec.Before(lastMod) { | |
| runCmd() | |
| lastExec = lastMod | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment