Allow to reuse watcher (#350)

* Make watcher reusable

* Allow to add multiple watched targets

* Move watcher

* Allow to ignore
This commit is contained in:
Sung Won Cho 2019-11-26 15:13:33 +08:00 committed by GitHub
commit 0e83ba1a5c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 39 additions and 8 deletions

1
pkg/watcher/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/main

View file

@ -19,12 +19,15 @@
package main
import (
"flag"
"log"
"os"
"os/exec"
"strings"
"syscall"
"time"
"github.com/pkg/errors"
"github.com/radovskyb/watcher"
)
@ -47,8 +50,25 @@ func command(binary string, args []string, entryPoint string) *exec.Cmd {
return cmd
}
func execCmd() *exec.Cmd {
return command("go", []string{"run", "main.go", "start", "-port", "3000"}, "..")
func execCmd(task string, watchDir string) *exec.Cmd {
parts := strings.Fields(task)
return command(parts[0], parts[1:], watchDir)
}
var task, context, ignore string
func init() {
flag.StringVar(&task, "task", "", "the command to execute")
flag.StringVar(&context, "context", ".", "the file or directory from which to execute the task")
flag.StringVar(&ignore, "ignore", ".", "the file or directory to ignore")
flag.Parse()
if task == "" {
log.Println("task was not provided. Exiting the watcher...")
os.Exit(1)
}
}
func main() {
@ -56,6 +76,8 @@ func main() {
w.IgnoreHiddenFiles(true)
w.SetMaxEvents(1)
targets := flag.Args()
var e *exec.Cmd
go func() {
@ -74,7 +96,7 @@ func main() {
}
// Starting it again here or starting for the first time.
e = execCmd()
e = execCmd(task, context)
case err := <-w.Error:
log.Fatalln(err)
case <-w.Closed:
@ -83,14 +105,22 @@ func main() {
}
}()
if err := w.AddRecursive(".."); err != nil {
log.Fatalln(err)
if ignore != "" {
if err := w.Ignore(ignore); err != nil {
log.Fatalln(errors.Wrapf(err, "ignoring %s", ignore))
}
}
e = execCmd()
for _, target := range targets {
if err := w.AddRecursive(target); err != nil {
log.Fatalln(errors.Wrap(err, "watching the given pattern"))
}
}
e = execCmd(task, context)
log.Printf("watching %d files", len(w.WatchedFiles()))
if err := w.Start(time.Millisecond * 1000); err != nil {
log.Fatalln(err)
log.Fatalln(errors.Wrap(err, "starting watcher"))
}
}

View file

@ -37,4 +37,4 @@ set +a
devServerPID=$!
# run server
(cd "$serverPath/watcher" && go run main.go)
(cd "$basePath/pkg/watcher" && go run main.go --task="go run main.go start -port 3000" --context="$serverPath" "$serverPath")