Last active
June 1, 2017 13:03
-
-
Save NigelGreenway/a2817bd0b17a735fb3d044fa0cc6e865 to your computer and use it in GitHub Desktop.
File watcher for ReactPHP
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
# to run: | |
# ./react.go {path_to_server.php} ./dir_one ./dir_two ... | |
package main | |
import ( | |
"log" | |
"os" | |
"os/exec" | |
"fmt" | |
"github.com/fsnotify/fsnotify" | |
) | |
func restartApp(serverPath string) { | |
fmt.Println("Restarting app") | |
cmd := fmt.Sprintf("ps aux|grep 'php %s'|head -n1|awk -d\"\\t\" '{ print $2}'", serverPath) | |
out, _ := exec.Command("sh", "-c", cmd).Output() | |
exec.Command("sh","-c", "kill " + string(out)).Output() | |
startApp(serverPath) | |
} | |
func systemWithoutOutput(cmd string, arg ...string) { | |
exec.Command(cmd, arg...).Start() | |
} | |
func startApp(pathToServer string) { | |
systemWithoutOutput("php", pathToServer) | |
} | |
func main() { | |
if len(os.Args) == 1 { | |
log.Fatal("A server file path is required!") | |
} | |
var ( | |
serverPath = os.Args[1] | |
directoriesToWatch = os.Args[2:] | |
) | |
startApp(serverPath) | |
log.Println("Running React App") | |
watcher, err := fsnotify.NewWatcher() | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer watcher.Close() | |
done := make(chan bool) | |
go func() { | |
for { | |
select { | |
case event := <-watcher.Events: | |
if event.Op&fsnotify.Write == fsnotify.Write { | |
restartApp(serverPath) | |
} | |
case err := <-watcher.Errors: | |
log.Println("error:", err) | |
} | |
} | |
}() | |
for _, directory := range directoriesToWatch { | |
err = watcher.Add(directory) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
<-done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment