From 67462dcf04fe703c49fbc8514cbc3b0d6cdf1e81 Mon Sep 17 00:00:00 2001 From: Aaron Fischer Date: Thu, 21 Jul 2016 23:51:25 +0200 Subject: [PATCH] Fix the "vim swaps files" bug --- agent.go | 40 ++++++++++++++++++++++++---------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/agent.go b/agent.go index c7c8de7..7acc8cd 100644 --- a/agent.go +++ b/agent.go @@ -58,24 +58,32 @@ func watchForConfigChanges(configFile string) { // The file is changed. This is the only event we are interested // in. If the file is renamed, removed or something else, we drop // an error to the user. - if event.Op&fsnotify.Write == fsnotify.Write { - log.Println("Reload the config file ...") - // TODO: Parse the config file - // TODO: Handle errors in the config file - // TODO: Write a mapping for the mapping of the keys to the binary format the avr wants. - // TODO: Establish a connection to the device - // TODO: Transfer the new key mappings - // TODO: Close the connection? + if event.Op&fsnotify.Write == fsnotify.Write || + event.Op&fsnotify.Remove == fsnotify.Remove { + + if _, err := os.Stat(event.Name); err == nil { + log.Println("Reload the config file ...") + // TODO: Parse the config file + // TODO: Handle errors in the config file + // TODO: Write a mapping for the mapping of the keys to the binary format the avr wants. + // TODO: Establish a connection to the device + // TODO: Transfer the new key mappings + // TODO: Close the connection? + } } - // TODO: vim has a very strange behaviour to save a file. There is - // no WRITE event triggered. Instead: RENAME -> CHMOD -> REMOVE is - // called on that file and after that, this mechanism lost track of - // the file. Why is that tha case? Cant find a valid answer to that. - if event.Op&fsnotify.Rename == fsnotify.Rename || - event.Op&fsnotify.Remove == fsnotify.Remove { - log.Println("The configuration file is renamed or removed. We cant do any further changes without the config file. So create the file or rename it back and restart the agent.") - stop() + // Some editors have a feature calles "swap save" (like vim), which + // will trigger a simple WRITE event, instead it wil trigger RENAME + // -> CHMOD -> REMOVE in that order. So we lost track of the file. + // To prevent this, we add the file again, if it exist after a + // REMOVE event. + if event.Op&fsnotify.Remove == fsnotify.Remove { + if _, err := os.Stat(event.Name); err == nil { + watcher.Add(event.Name) + } else { + log.Fatal("Lost the configuration file. We stop now.") + stop() + } } case err := <-watcher.Errors: log.Println("We have the following problem with the configuration file: ", err)