From 4b87403b15bbb836297ae02461aa9b515f79d50d Mon Sep 17 00:00:00 2001 From: Asad Jibran Ahmed Date: Sat, 7 Mar 2015 23:01:01 +0400 Subject: [PATCH] Added package watcher to allow gin to listen to changes in packages The package watcher looks at the package in the current working directory, and parses the source code to find out the imports. It then figures out which of those imports are outside of the GOROOT (and thus not part of the stdlib), and uses fsnotify.v1 to listen to changes to files in all those packages. This allows gin to; for example, reload the web server providing a web API to another library that is not a subpackage of the web server. --- main.go | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index e9310a0..937f78e 100644 --- a/main.go +++ b/main.go @@ -7,6 +7,7 @@ import ( "github.com/codegangsta/cli" "github.com/codegangsta/envy/lib" "github.com/codegangsta/gin/lib" + "github.com/theonejb/watchman" "log" "os" @@ -58,6 +59,10 @@ func main() { Name: "godep,g", Usage: "use godep when building", }, + cli.BoolFlag{ + Name: "pkgwatch,w", + Usage: "watch the package and any imported packages for change instead of files in the current dir", + }, } app.Commands = []cli.Command{ { @@ -81,6 +86,7 @@ func MainAction(c *cli.Context) { port := c.GlobalInt("port") appPort := strconv.Itoa(c.GlobalInt("appPort")) immediate = c.GlobalBool("immediate") + pkgWatch := c.GlobalBool("pkgwatch") // Bootstrap the environment envy.Bootstrap() @@ -116,10 +122,17 @@ func MainAction(c *cli.Context) { build(builder, runner, logger) // scan for changes - scanChanges(c.GlobalString("path"), func(path string) { + cb := func(path string) { runner.Kill() build(builder, runner, logger) - }) + } + if pkgWatch { + fmt.Println("Using Pkg Watcher") + scanChangesWithWatcher(c.GlobalString("path"), cb) + } else { + fmt.Println("Using file watcher") + scanChanges(c.GlobalString("path"), cb) + } } func EnvAction(c *cli.Context) { @@ -181,6 +194,13 @@ func scanChanges(watchPath string, cb scanCallback) { } } +func scanChangesWithWatcher(watchPath string, cb scanCallback) { + for { + watchman.WatchPackageAndReturnOnChange(watchPath) + cb(watchPath) + } +} + func shutdown(runner gin.Runner) { c := make(chan os.Signal, 2) signal.Notify(c, os.Interrupt, syscall.SIGTERM)