func watchMetadataFile(filename string, metadataChange chan string) { fmt.Printf("watching '%s'", filename) watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } exp, _ := regexp.Compile(".*(MODIFY|MOVE).*$") deleted := false for { if _, err := os.Stat(filename); err == nil { if deleted { readMetadataFile(filename, metadataChange) } err = watcher.Watch(filename) if err != nil { log.Fatal(err) } ev := <-watcher.Event if len(exp.FindStringSubmatch(ev.String())) > 0 { readMetadataFile(filename, metadataChange) } deleted = false } else { deleted = true time.Sleep(1 * time.Second) } } }
func startPostManager(brog *Brog, filepath string) (*postManager, error) { watcher, err := fsnotify.NewWatcher() if err != nil { return nil, fmt.Errorf("getting post watcher, %v", err) } postMngr := &postManager{ mu: sync.RWMutex{}, brog: brog, path: filepath, posts: make(map[string]*post), sortedPosts: []*post{}, watcher: watcher, die: make(chan struct{}), } err = postMngr.loadAllPosts() if err != nil { return nil, fmt.Errorf("while loading all posts, %v", err) } postMngr.sortPosts() if err := postMngr.watchForChanges(filepath); err != nil { return nil, fmt.Errorf("starting watch for changes on '%s', %v", filepath, err) } return postMngr, nil }
func watchFolder(path string) { watcher, err := fsnotify.NewWatcher() if err != nil { fatal(err) } go func() { for { select { case ev := <-watcher.Event: if isWatchedFile(ev.Name) { watcherLog("sending event %s", ev) startChannel <- ev.String() } case err := <-watcher.Error: watcherLog("error: %s", err) } } }() watcherLog("Watching %s", path) err = watcher.Watch(path) if err != nil { fatal(err) } }
func main() { L := lua.NewState() L.OpenLibs() defer L.Close() watcher, err := fsnotify.NewWatcher() if err != nil { panic(err) } luasPath := "./" if len(os.Args) == 2 { luasPath = os.Args[1] } watcher.WatchFlags(luasPath, fsnotify.FSN_MODIFY) ls := luas{} var ev *fsnotify.FileEvent ls.Collect(luasPath) ls.Load(L) newev: ls.Handle(ev, L) ev = <-watcher.Event goto newev }
func (this *gowatch) Watch() (err error) { if this.w, err = fsnotify.NewWatcher(); err != nil { return } for _, path := range this.Paths { if err = this.watchDirAndChildren(os.ExpandEnv(path)); err != nil { log.Fatal(err) } } this.modtime = make(map[string]time.Time) this.sig = make(chan string) for _, patten := range this.Exclude { this.reExclude = append(this.reExclude, regexp.MustCompile(patten)) } for _, patten := range this.Include { this.reInclude = append(this.reInclude, regexp.MustCompile(patten)) } this.sigOS = make(chan os.Signal, 1) signal.Notify(this.sigOS, syscall.SIGINT) go this.drainExec() this.drainEvent() return }
// ReadAndWatchConfigFile reads and watchs for changes in the configuration // file. Whenever the file change, and its contents are valid YAML, the // configuration gets updated. With this function, daemons that use this // package may reload configuration without restarting. func ReadAndWatchConfigFile(filePath string) error { err := ReadConfigFile(filePath) if err != nil { return err } w, err := fsnotify.NewWatcher() if err != nil { return err } err = w.Watch(filePath) if err != nil { return err } go func() { for { select { case e := <-w.Event: if e.IsModify() { ReadConfigFile(filePath) } case <-w.Error: // just ignore errors } } }() return nil }
func Watcher(config *SiteConfig) (chan string, error) { watcher, err := fsnotify.NewWatcher() if err != nil { return nil, err } ch := make(chan string, 10) go func() { for { ev := <-watcher.Event if ev.IsCreate() { watcher.Watch(ev.Name) } else if ev.IsDelete() { watcher.RemoveWatch(ev.Name) } ch <- ev.Name } }() filepath.Walk(config.Source, watchAll(watcher)) for _, path := range config.Templates { watcher.Watch(path) } return ch, nil }
func main() { ch_signal := make(chan os.Signal, 1) signal.Notify(ch_signal, os.Interrupt) sync_genie_config = *new(SyncGenieConfig) sync_genie_config_loaded = false sync_genie_currently_copying = make(map[string]int64) pwd, _ := os.Getwd() sync_genie_config_file = flag.String("config", filepath.Join(pwd, "syncgenie.ini"), "config") flag.Parse() SyncGenieLoadConfig() SyncGenieLoadHistory() // 3 = the main goroutine, the file lister goroutine, and the copy sync goroutine runtime.GOMAXPROCS(sync_genie_config.concurrent_copies + 3) watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } err = watcher.Watch(*sync_genie_config_file) if err != nil { log.Fatal(err) } ch := make(chan int) sync_genie_chan_new_files = make(chan SyncGenieCopyItem) go SyncGenieLister(ch) go SyncGenieQueueUpCopy() for { select { case ev := <-watcher.Event: if ev.IsModify() { log.Println("Config: Reloading") SyncGenieLoadConfig() } case err := <-watcher.Error: log.Println("Watcher: error:", err) case <-ch_signal: if len(sync_genie_currently_copying) != 0 { log.Println("Warning: currently copying files:", sync_genie_currently_copying) } log.Println("Quitting...") os.Exit(1) case <-ch: } } }
func main() { filePath := "/Users/shuaibincheng/test.txt" watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } waitChan := make(chan bool) go func() { for { select { case event := <-watcher.Event: log.Println("event: ", event) if event.IsDelete() { waitChan <- true } case err := <-watcher.Error: log.Println("error: ", err) waitChan <- false } } }() err = watcher.Watch(filePath) if err != nil { log.Fatal(err) } select { case <-waitChan: log.Println("exit") } }
// TODO func Init() { l := py.NewLock() defer l.Unlock() m, err := py.Import("sublime_plugin") if err != nil { panic(err) } sys, err := py.Import("sys") if err != nil { log4go.Debug(err) } else { defer sys.Decref() } watcher, err = fsnotify.NewWatcher() if err != nil { log4go.Error("Could not create watcher due to: %v", err) } watchedPlugins = make(map[string]*backend.WatchedPackage) go observePlugins(m) plugins := packages.ScanPlugins(backend.LIME_USER_PACKAGES_PATH, ".py") for _, p := range plugins { // TODO: add all plugins after supporting all commands if p.Name() == path.Join("..", "..", "3rdparty", "bundles", "Vintageous") { loadPlugin(p, m) } } }
func main() { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } done := make(chan bool) // goroutine receives events and prints them go func() { for { select { case ev := <-watcher.Event: log.Println("event:", ev) case err := <-watcher.Error: log.Println("error:", err) } } }() // list of directories to watch events on err = watcher.Watch("/var/cache/mig/command/ready/") err = watcher.Watch("/var/cache/mig/command/inflight/") err = watcher.Watch("/var/cache/mig/command/returned/") err = watcher.Watch("/var/cache/mig/command/done/") if err != nil { log.Fatal(err) } // block while watching for events <-done watcher.Close() }
func (w *watcher) Watch() error { watcher, err := fsnotify.NewWatcher() if err != nil { return err } go func() { for { select { case ev := <-watcher.Event: log.Println(ev.Name + " detected.") w.onEvent() case er := <-watcher.Error: log.Println(er) break } } }() for _, dir := range w.site.getDirs() { err := watcher.Watch(dir) if err != nil { return err } } return nil }
func initWatchdog() { w, err := fsnotify.NewWatcher() if err != nil { panic(err.Error()) } watcher = w //watcherDone = make(chan bool) go func() { for { select { case ev := <-watcher.Event: if ev == nil { return } if ev.IsModify() && strings.HasSuffix(ev.Name, ".glisp") { if module, ok := modulesByPath[ev.Name]; ok { module.Refresh() } } case err := <-watcher.Error: if err == nil { return } } } }() }
func newTempStore(dir string, funcs template.FuncMap) *tempStore { t := &tempStore{nil, filepath.Clean(dir), make(chan bool, 1), funcs} t.Load() watcher, err := fsnotify.NewWatcher() if err != nil { printf("%s\n", err) } go func() { for { select { case ev := <-watcher.Event: if ev.IsModify() { line := ev.Name if filepath.Ext(line) == TFIX { gtempStore.C <- true } } case err := <-watcher.Error: printf("error %s\n", err) } } }() watcher.Watch(dir) return t }
func main() { fmt.Println("Starting Watcher") watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatalf("Unable to watch: ", dir) log.Fatalf("With error: ", err) } startBuildAndRun() quitWatcher := make(chan bool) startWatcher(watcher, quitWatcher) watchRecursive(dir, watcher) log.Println("Watching directory: ", dir) interrupt := make(chan os.Signal) signal.Notify(interrupt, os.Interrupt) select { case <-interrupt: log.Println("Shutting down watcher.") watcher.Close() quitWatcher <- true log.Println("Quit watcher.") } }
func makeAi(path string, g *game.Game, ent *game.Entity, dst_iface *game.Ai, kind game.AiKind) { ai_struct := new(Ai) ai_struct.path = path var err error ai_struct.watcher, err = fsnotify.NewWatcher() if err != nil { base.Warn().Printf("Unable to create a filewatcher - '%s' will not reload ai files dynamically: %v", path, err) ai_struct.watcher = nil } ai_struct.ent = ent ai_struct.game = g ai_struct.active_set = make(chan bool) ai_struct.active_query = make(chan bool) ai_struct.exec_query = make(chan struct{}) ai_struct.pause = make(chan struct{}) ai_struct.terminate = make(chan struct{}) ai_struct.execs = make(chan game.ActionExec) ai_struct.kind = kind ai_struct.setupLuaState() go ai_struct.masterRoutine() *dst_iface = ai_struct }
func newWatcher() (w *fsnotify.Watcher) { w, err := fsnotify.NewWatcher() if err != nil { log4go.Error("Could not create watcher due to: %v", err) } return }
func StartWatching(filepath string) chan *Config { configChan := make(chan *Config) watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } go func() { for { select { case event := <-watcher.Event: log.Printf("Event: %+v", event) config, err := LoadConfig(filepath) if err != nil { configChan <- config } case err := <-watcher.Error: log.Panic("Error: %+v", err) } } }() err = watcher.Watch(filepath) if err != nil { log.Fatal("Error opening watcher", err) } return configChan }
// New creates a new in memory filesystem at root. func New(root string) (http.FileSystem, error) { root = path.Clean(root) watcher, err := fsnotify.NewWatcher() if err != nil { return nil, fmt.Errorf("failed to create watcher: %v", err) } memFS := &memFileSystem{ root: root, cache: map[string]*memFileInfo{}, lock: &sync.RWMutex{}, watcher: watcher, } // Set watcher callback. go memFS.watcherCallback() // Cache all the files and directory. err = memFS.walk() if err != nil { return nil, err } return memFS, nil }
func (self *Launcher) listenItemChanged() { dirs := getApplicationsDirs() watcher, err := fsnotify.NewWatcher() if err != nil { return } self.appMonitor = watcher for _, dir := range dirs { logger.Info("monitor:", dir) watcher.Watch(dir) } go self.eventHandler(watcher) if self.store != nil { self.store.ConnectNewDesktopAdded(func(desktopId string, timeInstalled int32) { self.emitItemChanged(desktopId, SoftwareStatusCreated, map[string]ItemChangedStatus{ desktopId: ItemChangedStatus{ timeInstalled: int64(timeInstalled), }, }) }) } }
func WatchConfig(configWrapper iConfigWrapper, configPath string) { watcherForConfigFile, err := fsnotify.NewWatcher() CheckError(err) go func() { for { select { case e := <-watcherForConfigFile.Event: if lastConfigModifiedTime.Add(1 * time.Second).After(time.Now()) { continue } lastConfigModifiedTime = time.Now() // log.Warn("Config '%s' modified, but NOT RELOADING YET.", e.Name) log.Warn("Config '%s' modified, now reloading (most of the) config settings.", e.Name) configWrapper.SetConfig(loadFile(configPath)) configWrapper.ConfigReloaded() break case err := <-watcherForConfigFile.Error: log.Error("Error: %+v", err) break } } }() err = watcherForConfigFile.Watch(configPath) CheckError(err) }
func startLogging(path string) { go func() { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } err = watcher.Watch(path) if err != nil { log.Fatal(err) } defer watcher.Close() for { select { case event := <-watcher.Event: if event.IsModify() { modifiedPath := event.Name checkContentChanged(modifiedPath) } case err := <-watcher.Error: log.Println("Error:", err) } } }() }
func watchConfig(fileName string, mapper *metricMapper) { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } err = watcher.WatchFlags(fileName, fsnotify.FSN_MODIFY) if err != nil { log.Fatal(err) } for { select { case ev := <-watcher.Event: log.Infof("Config file changed (%s), attempting reload", ev) err = mapper.initFromFile(fileName) if err != nil { log.Errorln("Error reloading config:", err) configLoads.WithLabelValues("failure").Inc() } else { log.Infoln("Config reloaded successfully") configLoads.WithLabelValues("success").Inc() } // Re-add the file watcher since it can get lost on some changes. E.g. // saving a file with vim results in a RENAME-MODIFY-DELETE event // sequence, after which the newly written file is no longer watched. err = watcher.WatchFlags(fileName, fsnotify.FSN_MODIFY) case err := <-watcher.Error: log.Errorln("Error watching config:", err) } } }
func main() { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } done := make(chan bool) // Process events go func() { for { select { case ev := <-watcher.Event: log.Println("event:", ev) case err := <-watcher.Error: log.Println("error:", err) } } }() err = watcher.Watch("build.log") if err != nil { log.Fatal(err) } // Hang so program doesn't exit <-done /* ... do stuff ... */ watcher.Close() }
func watch(site *Site) { // Setup the inotify watcher watcher, err := fsnotify.NewWatcher() if err != nil { fmt.Println(err) return } // Get recursive list of directories to watch for _, path := range dirs(site.Src) { if err := watcher.Watch(path); err != nil { fmt.Println(err) return } } for { select { case ev := <-watcher.Event: // Ignore changes to the _site directoy, hidden, or temp files if !strings.HasPrefix(ev.Name, site.Dest) && !isHiddenOrTemp(ev.Name) { fmt.Println("Event:", ev.Name) recompile(site) } case err := <-watcher.Error: fmt.Println("inotify error:", err) } } }
func watchForChanges(wwwRoot string, q chan bool) error { watcher, err := fsnotify.NewWatcher() if err != nil { return err } defer watcher.Close() err = filepath.Walk(wwwRoot, func(pathEntry string, info os.FileInfo, err error) error { return watcher.Watch(pathEntry) }) if err != nil { return err } for { select { case ev := <-watcher.Event: if ev.IsCreate() || ev.IsDelete() || ev.IsModify() || ev.IsRename() { log.Println("Got change event:", ev) q <- true return nil } case err := <-watcher.Error: log.Println("ERROR: inotify:", err) } } return nil }
func startMonitorFs() { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } else { reloadCfg.fsWatcher = watcher walkFn := func(path string, info os.FileInfo, err error) error { if err != nil { // TODO permisstion denyed } ignore := shouldIgnore(path) if ignore && info.IsDir() { log.Println("ignore dir", path) return filepath.SkipDir } if info.IsDir() && !ignore { err = watcher.Watch(path) if err != nil { log.Fatal(err) } else { log.Println("monitoring dir", path) } } return nil } if err := filepath.Walk(reloadCfg.root, walkFn); err != nil { log.Println(err) } } }
func start_watcher() { watcher, err := fsnotify.NewWatcher() if err != nil { fmt.Println(err) } // Process events go func() { for { select { case ev := <-watcher.Event: if !strings.Contains(ev.Name, ".kate-swp") { if ev.IsModify() { compile() } } case err := <-watcher.Error: fmt.Println("error:", err) } } }() err = watcher.Watch(".") if err != nil { fmt.Println(err) } }
func NewWatcher(paths []string) { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } go func() { for { select { case e := <-watcher.Event: fmt.Println(e) go Autobuild() case err := <-watcher.Error: log.Fatal("error:", err) } } }() for _, path := range paths { fmt.Println(path) err = watcher.Watch(path) if err != nil { log.Fatal(err) } } }
func configWatcher(fileName string) { configReader(fileName) watcher, err := fsnotify.NewWatcher() if err != nil { fmt.Println(err) return } if err := watcher.Watch(*flagconfig); err != nil { fmt.Println(err) return } for { select { case ev := <-watcher.Event: if ev.Name == fileName { if ev.IsCreate() || ev.IsModify() || ev.IsRename() { time.Sleep(200 * time.Millisecond) configReader(fileName) } } case err := <-watcher.Error: log.Println("fsnotify error:", err) } } }