Go library shows filesystem changes across platforms
Programming Snapshot – fsnotify
Inotify lets applications subscribe to change notifications in the filesystem. Mike Schilli uses the cross-platform fsnotify library to instruct a Go program to detect what's happening.
In a file manager, have you ever observed how newly created files by other applications immediately appear in the displayed directory and wondered how this works? As continuous querying of the filesystem is out of the question for performance reasons, these applications use the Linux filesystem's inotify interface instead.
Operating systems implement the mechanism in different ways: Linux uses inotify, the Mac uses kqueue, and Windows comes with an unpronounceable extra. Fortunately, the Go library fsnotify on GitHub abstracts this proliferation to create a simple interface. This means that programmers only need to write their applications once to cover all platforms.
No Stress
About 15 years ago, I wrote an article on this topic in my regular column [1]. At the time I used Perl, and the article relied on FUSE, a special filesystem. Today filesystem notifications are part of the standard.
In Go, the whole thing can be done without much fuss; Listing 1 shows a simple example just to get you warmed up. Figure 1 visualizes how an executable binary named watch
is created from the Go code in watch.go
, which then starts monitoring a newly created directory /tmp/test/
. In another terminal, the user now enters the commands shown in Figure 2. They first create a new file in the test directory, write data to it, change its execution privileges, and finally delete it with rm
. Figure 1 confirms that the Go program actually sees all changes in real time and logs the actions.
Listing 1
watch.go
01 package main 02 03 import ( 04 "fmt" 05 "github.com/fsnotify/fsnotify" 06 ) 07 08 func main() { 09 watcher, err := fsnotify.NewWatcher() 10 if err != nil { 11 panic(err) 12 } 13 defer watcher.Close() 14 15 go func() { 16 for { 17 select { 18 case event, ok := <-watcher.Events: 19 if !ok { 20 return 21 } 22 fmt.Printf("%+v\n", event) 23 } 24 } 25 }() 26 27 err = watcher.Add("/tmp/test") 28 if err != nil { 29 panic(err) 30 } 31 32 done := make(chan struct{}) 33 <-done 34 }
To do this, Listing 1 retrieves the library code from GitHub in line 5, creates a new watcher as the first step in the main
program, and calls defer
to tell it to shut itself down at the end of the program.
Since filesystem monitoring with fsnotify is an asynchronous process using Go channels, line 15 calls go func
to launch a goroutine, which immediately starts an infinite loop with a select
statement. The latter blocks the flow of the goroutine until messages arrive from the watcher.Events
channel, sent by the library code from fsnotify, which gets its clues directly from the operating system.
Routines and Blocking
Meanwhile, the main
program continues to flow unimpeded, and line 27 tells fsnotify via watcher.Add()
that it wants to monitor the /tmp/test/
directory. That's all there is to it in the main
program.
But since main
is supposed to continue running and listening for events in the Goroutine launched earlier; line 32 creates an unused channel just before the end in line 33. Alas, no message will ever arrive from this channel: Its only job is to block the main
program until the user cancels it by pressing Ctrl+C.
Non-Recursive
The Go library fsnotify only adds one directory to the watch list with each call to Add()
. Recursive integration of an entire file tree is supposedly on the fsnotify project's roadmap, but it doesn't work at the moment. Therefore, the application has to weave its own surveillance net by issuing recursive calls down the directory hierarchy.
For example, to track which files the Go compiler downloads or generates in the directory hierarchy below ~/go/
in the user's home directory during the work phase, Listing 2 first has to delve the depths of the directory structure using the Walk()
function from the standard filepath
package starting in line 24.
Listing 2
fswatch.go
01 package main 02 03 import ( 04 "fmt" 05 "github.com/fsnotify/fsnotify" 06 "log" 07 "os" 08 "os/user" 09 "path/filepath" 10 "strings" 11 ) 12 13 func main() { 14 cur, err := user.Current() 15 dieOnErr(err) 16 home := cur.HomeDir 17 18 watcher, err := fsnotify.NewWatcher() 19 dieOnErr(err) 20 defer watcher.Close() 21 22 watchInit(watcher) 23 24 err = filepath.Walk(filepath.Join(home, "go"), 25 func(path string, info os.FileInfo, err error) error { 26 dieOnErr(err) 27 if info.IsDir() { 28 err := watcher.Add(path) 29 dieOnErr(err) 30 } 31 return nil 32 }) 33 dieOnErr(err) 34 35 done := make(chan bool) 36 <-done 37 } 38 39 func eventAsString(event fsnotify.Event) string { 40 info, err := os.Stat(event.Name) 41 dieOnErr(err) 42 evShort := (strings.ToLower(event.Op.String()))[0:2] 43 dirParts := strings.Split(event.Name, "/") 44 pathShort := event.Name 45 if len(dirParts) > 3 { 46 pathShort = filepath.Join(dirParts[len(dirParts)-3 : len(dirParts)]...) 47 } 48 return fmt.Sprintf("%s %s %d", evShort, pathShort, info.Size()) 49 } 50 51 func watchInit(watcher *fsnotify.Watcher) { 52 go func() { 53 for { 54 select { 55 case event, ok := <-watcher.Events: 56 if !ok { 57 return 58 } 59 if event.Op&fsnotify.Rename == fsnotify.Rename || 60 event.Op&fsnotify.Remove == fsnotify.Remove { 61 continue 62 } 63 log.Printf("%s\n", eventAsString(event)) 64 info, err := os.Stat(event.Name) 65 dieOnErr(err) 66 if info.IsDir() { 67 err := watcher.Add(event.Name) 68 dieOnErr(err) 69 } 70 case err, _ := <-watcher.Errors: 71 panic(err) 72 } 73 } 74 }() 75 } 76 77 func dieOnErr(err error) { 78 if err != nil { 79 panic(err) 80 } 81 }
As a parameter, the function expects a callback function that it will call for each filesystem entry it finds with the name and the FileInfo
structure including the metadata, such as the file or directory, size in bytes, or access permissions. If an error occurred during the traversal, the err
variable is set to the corresponding error instead.
Buy this article as PDF
(incl. VAT)