pax_global_header00006660000000000000000000000064135256516340014524gustar00rootroot0000000000000052 comment=f5989f8deca223d590d5a130c77ea375fe9fde30 watcher-1.0.7/000077500000000000000000000000001352565163400131665ustar00rootroot00000000000000watcher-1.0.7/.travis.yml000066400000000000000000000000401352565163400152710ustar00rootroot00000000000000language: go go: - 1.7 - tipwatcher-1.0.7/LICENSE000066400000000000000000000027371352565163400142040ustar00rootroot00000000000000Copyright (c) 2016, Benjamin Radovsky. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of watcher nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. watcher-1.0.7/README.md000066400000000000000000000115741352565163400144550ustar00rootroot00000000000000# watcher [![Build Status](https://travis-ci.org/radovskyb/watcher.svg?branch=master)](https://travis-ci.org/radovskyb/watcher) `watcher` is a Go package for watching for files or directory changes (recursively or non recursively) without using filesystem events, which allows it to work cross platform consistently. `watcher` watches for changes and notifies over channels either anytime an event or an error has occurred. Events contain the `os.FileInfo` of the file or directory that the event is based on and the type of event and file or directory path. [Installation](#installation) [Features](#features) [Example](#example) [Contributing](#contributing) [Watcher Command](#command) # Update - Event.OldPath has been added [Aug 17, 2019] - Added new file filter hooks (Including a built in regexp filtering hook) [Dec 12, 2018] - Event.Path for Rename and Move events is now returned in the format of `fromPath -> toPath` #### Chmod event is not supported under windows. # Installation ```shell go get -u github.com/radovskyb/watcher/... ``` # Features - Customizable polling interval. - Filter Events. - Watch folders recursively or non-recursively. - Choose to ignore hidden files. - Choose to ignore specified files and folders. - Notifies the `os.FileInfo` of the file that the event is based on. e.g `Name`, `ModTime`, `IsDir`, etc. - Notifies the full path of the file that the event is based on or the old and new paths if the event was a `Rename` or `Move` event. - Limit amount of events that can be received per watching cycle. - List the files being watched. - Trigger custom events. # Todo - Write more tests. - Write benchmarks. # Example ```go package main import ( "fmt" "log" "time" "github.com/radovskyb/watcher" ) func main() { w := watcher.New() // SetMaxEvents to 1 to allow at most 1 event's to be received // on the Event channel per watching cycle. // // If SetMaxEvents is not set, the default is to send all events. w.SetMaxEvents(1) // Only notify rename and move events. w.FilterOps(watcher.Rename, watcher.Move) // Only files that match the regular expression during file listings // will be watched. r := regexp.MustCompile("^abc$") w.AddFilterHook(watcher.RegexFilterHook(r, false)) go func() { for { select { case event := <-w.Event: fmt.Println(event) // Print the event's info. case err := <-w.Error: log.Fatalln(err) case <-w.Closed: return } } }() // Watch this folder for changes. if err := w.Add("."); err != nil { log.Fatalln(err) } // Watch test_folder recursively for changes. if err := w.AddRecursive("../test_folder"); err != nil { log.Fatalln(err) } // Print a list of all of the files and folders currently // being watched and their paths. for path, f := range w.WatchedFiles() { fmt.Printf("%s: %s\n", path, f.Name()) } fmt.Println() // Trigger 2 events after watcher started. go func() { w.Wait() w.TriggerEvent(watcher.Create, nil) w.TriggerEvent(watcher.Remove, nil) }() // Start the watching process - it'll check for changes every 100ms. if err := w.Start(time.Millisecond * 100); err != nil { log.Fatalln(err) } } ``` # Contributing If you would ike to contribute, simply submit a pull request. # Command `watcher` comes with a simple command which is installed when using the `go get` command from above. # Usage ``` Usage of watcher: -cmd string command to run when an event occurs -dotfiles watch dot files (default true) -ignore string comma separated list of paths to ignore -interval string watcher poll interval (default "100ms") -keepalive keep alive when a cmd returns code != 0 -list list watched files on start -pipe pipe event's info to command's stdin -recursive watch folders recursively (default true) -startcmd run the command when watcher starts ``` All of the flags are optional and watcher can also be called by itself: ```shell watcher ``` (watches the current directory recursively for changes and notifies any events that occur.) A more elaborate example using the `watcher` command: ```shell watcher -dotfiles=false -recursive=false -cmd="./myscript" main.go ../ ``` In this example, `watcher` will ignore dot files and folders and won't watch any of the specified folders recursively. It will also run the script `./myscript` anytime an event occurs while watching `main.go` or any files or folders in the previous directory (`../`). Using the `pipe` and `cmd` flags together will send the event's info to the command's stdin when changes are detected. First create a file called `script.py` with the following contents: ```python import sys for line in sys.stdin: print (line + " - python") ``` Next, start watcher with the `pipe` and `cmd` flags enabled: ```shell watcher -cmd="python script.py" -pipe=true ``` Now when changes are detected, the event's info will be output from the running python script. watcher-1.0.7/cmd/000077500000000000000000000000001352565163400137315ustar00rootroot00000000000000watcher-1.0.7/cmd/watcher/000077500000000000000000000000001352565163400153665ustar00rootroot00000000000000watcher-1.0.7/cmd/watcher/README.md000066400000000000000000000032431352565163400166470ustar00rootroot00000000000000# watcher command # Installation ```shell go get -u github.com/radovskyb/watcher/... ``` # Usage ``` Usage of watcher: -cmd string command to run when an event occurs -dotfiles watch dot files (default true) -ignore string comma separated list of paths to ignore -interval string watcher poll interval (default "100ms") -keepalive keep alive when a cmd returns code != 0 -list list watched files on start -pipe pipe event's info to command's stdin -recursive watch folders recursively (default true) -startcmd run the command when watcher starts ``` All of the flags are optional and watcher can be simply called by itself: ```shell watcher ``` (watches the current directory recursively for changes and notifies for any events that occur.) A more elaborate example using the `watcher` command: ```shell watcher -dotfiles=false -recursive=false -cmd="./myscript" main.go ../ ``` In this example, `watcher` will ignore dot files and folders and won't watch any of the specified folders recursively. It will also run the script `./myscript` anytime an event occurs while watching `main.go` or any files or folders in the previous directory (`../`). Using the `pipe` and `cmd` flags together will send the event's info to the command's stdin when changes are detected. First create a file called `script.py` with the following contents: ```python import sys for line in sys.stdin: print (line + " - python") ``` Next, start watcher with the `pipe` and `cmd` flags enabled: ```shell watcher -cmd="python script.py" -pipe=true ``` Now when changes are detected, the event's info will be output from the running python script. watcher-1.0.7/cmd/watcher/main.go000066400000000000000000000074071352565163400166510ustar00rootroot00000000000000package main import ( "flag" "fmt" "log" "os" "os/exec" "os/signal" "strings" "time" "unicode" "github.com/radovskyb/watcher" ) func main() { interval := flag.String("interval", "100ms", "watcher poll interval") recursive := flag.Bool("recursive", true, "watch folders recursively") dotfiles := flag.Bool("dotfiles", true, "watch dot files") cmd := flag.String("cmd", "", "command to run when an event occurs") startcmd := flag.Bool("startcmd", false, "run the command when watcher starts") listFiles := flag.Bool("list", false, "list watched files on start") stdinPipe := flag.Bool("pipe", false, "pipe event's info to command's stdin") keepalive := flag.Bool("keepalive", false, "keep alive when a cmd returns code != 0") ignore := flag.String("ignore", "", "comma separated list of paths to ignore") flag.Parse() // Retrieve the list of files and folders. files := flag.Args() // If no files/folders were specified, watch the current directory. if len(files) == 0 { curDir, err := os.Getwd() if err != nil { log.Fatalln(err) } files = append(files, curDir) } var cmdName string var cmdArgs []string if *cmd != "" { split := strings.FieldsFunc(*cmd, unicode.IsSpace) cmdName = split[0] if len(split) > 1 { cmdArgs = split[1:] } } // Create a new Watcher with the specified options. w := watcher.New() w.IgnoreHiddenFiles(!*dotfiles) // Get any of the paths to ignore. ignoredPaths := strings.Split(*ignore, ",") for _, path := range ignoredPaths { trimmed := strings.TrimSpace(path) if trimmed == "" { continue } err := w.Ignore(trimmed) if err != nil { log.Fatalln(err) } } done := make(chan struct{}) go func() { defer close(done) for { select { case event := <-w.Event: // Print the event's info. fmt.Println(event) // Run the command if one was specified. if *cmd != "" { c := exec.Command(cmdName, cmdArgs...) if *stdinPipe { c.Stdin = strings.NewReader(event.String()) } else { c.Stdin = os.Stdin } c.Stdout = os.Stdout c.Stderr = os.Stderr if err := c.Run(); err != nil { if (c.ProcessState == nil || !c.ProcessState.Success()) && *keepalive { log.Println(err) continue } log.Fatalln(err) } } case err := <-w.Error: if err == watcher.ErrWatchedFileDeleted { fmt.Println(err) continue } log.Fatalln(err) case <-w.Closed: return } } }() // Add the files and folders specified. for _, file := range files { if *recursive { if err := w.AddRecursive(file); err != nil { log.Fatalln(err) } } else { if err := w.Add(file); err != nil { log.Fatalln(err) } } } // Print a list of all of the files and folders being watched. if *listFiles { for path, f := range w.WatchedFiles() { fmt.Printf("%s: %s\n", path, f.Name()) } fmt.Println() } fmt.Printf("Watching %d files\n", len(w.WatchedFiles())) // Parse the interval string into a time.Duration. parsedInterval, err := time.ParseDuration(*interval) if err != nil { log.Fatalln(err) } closed := make(chan struct{}) c := make(chan os.Signal) signal.Notify(c, os.Kill, os.Interrupt) go func() { <-c w.Close() <-done fmt.Println("watcher closed") close(closed) }() // Run the command before watcher starts if one was specified. go func() { if *cmd != "" && *startcmd { c := exec.Command(cmdName, cmdArgs...) c.Stdin = os.Stdin c.Stdout = os.Stdout c.Stderr = os.Stderr if err := c.Run(); err != nil { if (c.ProcessState == nil || !c.ProcessState.Success()) && *keepalive { log.Println(err) return } log.Fatalln(err) } } }() // Start the watching process. if err := w.Start(parsedInterval); err != nil { log.Fatalln(err) } <-closed } watcher-1.0.7/example/000077500000000000000000000000001352565163400146215ustar00rootroot00000000000000watcher-1.0.7/example/basics/000077500000000000000000000000001352565163400160655ustar00rootroot00000000000000watcher-1.0.7/example/basics/main.go000066400000000000000000000031111352565163400173340ustar00rootroot00000000000000package main import ( "fmt" "log" "time" "github.com/radovskyb/watcher" ) func main() { w := watcher.New() // Uncomment to use SetMaxEvents set to 1 to allow at most 1 event to be received // on the Event channel per watching cycle. // // If SetMaxEvents is not set, the default is to send all events. // w.SetMaxEvents(1) // Uncomment to only notify rename and move events. // w.FilterOps(watcher.Rename, watcher.Move) // Uncomment to filter files based on a regular expression. // // Only files that match the regular expression during file listing // will be watched. // r := regexp.MustCompile("^abc$") // w.AddFilterHook(watcher.RegexFilterHook(r, false)) go func() { for { select { case event := <-w.Event: fmt.Println(event) // Print the event's info. case err := <-w.Error: log.Fatalln(err) case <-w.Closed: return } } }() // Watch this folder for changes. if err := w.Add("."); err != nil { log.Fatalln(err) } // Watch test_folder recursively for changes. if err := w.AddRecursive("../test_folder"); err != nil { log.Fatalln(err) } // Print a list of all of the files and folders currently // being watched and their paths. for path, f := range w.WatchedFiles() { fmt.Printf("%s: %s\n", path, f.Name()) } fmt.Println() // Trigger 2 events after watcher started. go func() { w.Wait() w.TriggerEvent(watcher.Create, nil) w.TriggerEvent(watcher.Remove, nil) }() // Start the watching process - it'll check for changes every 100ms. if err := w.Start(time.Millisecond * 100); err != nil { log.Fatalln(err) } } watcher-1.0.7/example/close_watcher/000077500000000000000000000000001352565163400174435ustar00rootroot00000000000000watcher-1.0.7/example/close_watcher/main.go000066400000000000000000000015421352565163400207200ustar00rootroot00000000000000package main import ( "fmt" "log" "time" "github.com/radovskyb/watcher" ) func main() { w := watcher.New() go func() { for { select { case event := <-w.Event: fmt.Println(event) case err := <-w.Error: log.Fatalln(err) case <-w.Closed: return } } }() // Watch test_folder for changes. if err := w.Add("../test_folder"); err != nil { log.Fatalln(err) } // Print a list of all of the files and folders currently // being watched and their paths. for path, f := range w.WatchedFiles() { fmt.Printf("%s: %s\n", path, f.Name()) } fmt.Println() // Close the watcher after watcher started. go func() { w.Wait() w.Close() }() // Start the watching process - it'll check for changes every 100ms. if err := w.Start(time.Millisecond * 100); err != nil { log.Fatalln(err) } fmt.Println("watcher closed") } watcher-1.0.7/example/filter_events/000077500000000000000000000000001352565163400174725ustar00rootroot00000000000000watcher-1.0.7/example/filter_events/main.go000066400000000000000000000015461352565163400207530ustar00rootroot00000000000000package main import ( "fmt" "log" "time" "github.com/radovskyb/watcher" ) func main() { w := watcher.New() w.SetMaxEvents(1) // Only show rename and move events. w.FilterOps(watcher.Rename, watcher.Move) go func() { for { select { case event := <-w.Event: fmt.Println(event) case err := <-w.Error: log.Fatalln(err) case <-w.Closed: return } } }() // Watch test_folder recursively for changes. if err := w.AddRecursive("../test_folder"); err != nil { log.Fatalln(err) } // Print a list of all of the files and folders currently // being watched and their paths. for path, f := range w.WatchedFiles() { fmt.Printf("%s: %s\n", path, f.Name()) } fmt.Println() // Start the watching process - it'll check for changes every 100ms. if err := w.Start(time.Millisecond * 100); err != nil { log.Fatalln(err) } } watcher-1.0.7/example/ignore_files/000077500000000000000000000000001352565163400172665ustar00rootroot00000000000000watcher-1.0.7/example/ignore_files/main.go000066400000000000000000000023721352565163400205450ustar00rootroot00000000000000package main import ( "fmt" "log" "time" "github.com/radovskyb/watcher" ) func main() { w := watcher.New() go func() { for { select { case event := <-w.Event: // Print the event. fmt.Println(event) case err := <-w.Error: log.Fatalln(err) case <-w.Closed: return } } }() // Watch test_folder recursively for changes. if err := w.AddRecursive("../test_folder"); err != nil { log.Fatalln(err) } // Print a list of all of the files and folders currently // being watched and their paths. for path, f := range w.WatchedFiles() { fmt.Printf("%s: %s\n", path, f.Name()) } fmt.Println() go func() { w.Wait() // Ignore ../test_folder/test_folder_recursive and ../test_folder/.dotfile if err := w.Ignore("../test_folder/test_folder_recursive", "../test_folder/.dotfile"); err != nil { log.Fatalln(err) } // Print a list of all of the files and folders currently being watched // and their paths after adding files and folders to the ignore list. for path, f := range w.WatchedFiles() { fmt.Printf("%s: %s\n", path, f.Name()) } fmt.Println() }() // Start the watching process - it'll check for changes every 100ms. if err := w.Start(time.Millisecond * 100); err != nil { log.Fatalln(err) } } watcher-1.0.7/example/ignore_hidden_files/000077500000000000000000000000001352565163400206015ustar00rootroot00000000000000watcher-1.0.7/example/ignore_hidden_files/main.go000066400000000000000000000015711352565163400220600ustar00rootroot00000000000000package main import ( "fmt" "log" "time" "github.com/radovskyb/watcher" ) func main() { w := watcher.New() // Ignore hidden files. w.IgnoreHiddenFiles(true) go func() { for { select { case event := <-w.Event: // Print the event's info. fmt.Println(event) case err := <-w.Error: log.Fatalln(err) case <-w.Closed: return } } }() // Watch test_folder recursively for changes. // // Watcher won't add .dotfile to the watchlist. if err := w.AddRecursive("../test_folder"); err != nil { log.Fatalln(err) } // Print a list of all of the files and folders currently // being watched and their paths. for path, f := range w.WatchedFiles() { fmt.Printf("%s: %s\n", path, f.Name()) } // Start the watching process - it'll check for changes every 100ms. if err := w.Start(time.Millisecond * 100); err != nil { log.Fatalln(err) } } watcher-1.0.7/example/test_folder/000077500000000000000000000000001352565163400171335ustar00rootroot00000000000000watcher-1.0.7/example/test_folder/.dotfile000066400000000000000000000000211352565163400205530ustar00rootroot00000000000000I'm a dotfile :O watcher-1.0.7/example/test_folder/file.txt000066400000000000000000000000001352565163400206010ustar00rootroot00000000000000watcher-1.0.7/example/test_folder/test_folder_recursive/000077500000000000000000000000001352565163400235345ustar00rootroot00000000000000watcher-1.0.7/example/test_folder/test_folder_recursive/file_recursive.txt000066400000000000000000000000001352565163400272710ustar00rootroot00000000000000watcher-1.0.7/ishidden.go000066400000000000000000000002671352565163400153110ustar00rootroot00000000000000// +build !windows package watcher import ( "path/filepath" "strings" ) func isHiddenFile(path string) (bool, error) { return strings.HasPrefix(filepath.Base(path), "."), nil } watcher-1.0.7/ishidden_windows.go000066400000000000000000000005421352565163400170570ustar00rootroot00000000000000// +build windows package watcher import ( "syscall" ) func isHiddenFile(path string) (bool, error) { pointer, err := syscall.UTF16PtrFromString(path) if err != nil { return false, err } attributes, err := syscall.GetFileAttributes(pointer) if err != nil { return false, err } return attributes&syscall.FILE_ATTRIBUTE_HIDDEN != 0, nil } watcher-1.0.7/samefile.go000066400000000000000000000001751352565163400153050ustar00rootroot00000000000000// +build !windows package watcher import "os" func sameFile(fi1, fi2 os.FileInfo) bool { return os.SameFile(fi1, fi2) } watcher-1.0.7/samefile_windows.go000066400000000000000000000003411352565163400170520ustar00rootroot00000000000000// +build windows package watcher import "os" func sameFile(fi1, fi2 os.FileInfo) bool { return fi1.ModTime() == fi2.ModTime() && fi1.Size() == fi2.Size() && fi1.Mode() == fi2.Mode() && fi1.IsDir() == fi2.IsDir() } watcher-1.0.7/watcher.go000066400000000000000000000365641352565163400151700ustar00rootroot00000000000000package watcher import ( "errors" "fmt" "io/ioutil" "os" "path/filepath" "regexp" "strings" "sync" "time" ) var ( // ErrDurationTooShort occurs when calling the watcher's Start // method with a duration that's less than 1 nanosecond. ErrDurationTooShort = errors.New("error: duration is less than 1ns") // ErrWatcherRunning occurs when trying to call the watcher's // Start method and the polling cycle is still already running // from previously calling Start and not yet calling Close. ErrWatcherRunning = errors.New("error: watcher is already running") // ErrWatchedFileDeleted is an error that occurs when a file or folder that was // being watched has been deleted. ErrWatchedFileDeleted = errors.New("error: watched file or folder deleted") // ErrSkip is less of an error, but more of a way for path hooks to skip a file or // directory. ErrSkip = errors.New("error: skipping file") ) // An Op is a type that is used to describe what type // of event has occurred during the watching process. type Op uint32 // Ops const ( Create Op = iota Write Remove Rename Chmod Move ) var ops = map[Op]string{ Create: "CREATE", Write: "WRITE", Remove: "REMOVE", Rename: "RENAME", Chmod: "CHMOD", Move: "MOVE", } // String prints the string version of the Op consts func (e Op) String() string { if op, found := ops[e]; found { return op } return "???" } // An Event describes an event that is received when files or directory // changes occur. It includes the os.FileInfo of the changed file or // directory and the type of event that's occurred and the full path of the file. type Event struct { Op Path string OldPath string os.FileInfo } // String returns a string depending on what type of event occurred and the // file name associated with the event. func (e Event) String() string { if e.FileInfo == nil { return "???" } pathType := "FILE" if e.IsDir() { pathType = "DIRECTORY" } return fmt.Sprintf("%s %q %s [%s]", pathType, e.Name(), e.Op, e.Path) } // FilterFileHookFunc is a function that is called to filter files during listings. // If a file is ok to be listed, nil is returned otherwise ErrSkip is returned. type FilterFileHookFunc func(info os.FileInfo, fullPath string) error // RegexFilterHook is a function that accepts or rejects a file // for listing based on whether it's filename or full path matches // a regular expression. func RegexFilterHook(r *regexp.Regexp, useFullPath bool) FilterFileHookFunc { return func(info os.FileInfo, fullPath string) error { str := info.Name() if useFullPath { str = fullPath } // Match if r.MatchString(str) { return nil } // No match. return ErrSkip } } // Watcher describes a process that watches files for changes. type Watcher struct { Event chan Event Error chan error Closed chan struct{} close chan struct{} wg *sync.WaitGroup // mu protects the following. mu *sync.Mutex ffh []FilterFileHookFunc running bool names map[string]bool // bool for recursive or not. files map[string]os.FileInfo // map of files. ignored map[string]struct{} // ignored files or directories. ops map[Op]struct{} // Op filtering. ignoreHidden bool // ignore hidden files or not. maxEvents int // max sent events per cycle } // New creates a new Watcher. func New() *Watcher { // Set up the WaitGroup for w.Wait(). var wg sync.WaitGroup wg.Add(1) return &Watcher{ Event: make(chan Event), Error: make(chan error), Closed: make(chan struct{}), close: make(chan struct{}), mu: new(sync.Mutex), wg: &wg, files: make(map[string]os.FileInfo), ignored: make(map[string]struct{}), names: make(map[string]bool), } } // SetMaxEvents controls the maximum amount of events that are sent on // the Event channel per watching cycle. If max events is less than 1, there is // no limit, which is the default. func (w *Watcher) SetMaxEvents(delta int) { w.mu.Lock() w.maxEvents = delta w.mu.Unlock() } // AddFilterHook func (w *Watcher) AddFilterHook(f FilterFileHookFunc) { w.mu.Lock() w.ffh = append(w.ffh, f) w.mu.Unlock() } // IgnoreHiddenFiles sets the watcher to ignore any file or directory // that starts with a dot. func (w *Watcher) IgnoreHiddenFiles(ignore bool) { w.mu.Lock() w.ignoreHidden = ignore w.mu.Unlock() } // FilterOps filters which event op types should be returned // when an event occurs. func (w *Watcher) FilterOps(ops ...Op) { w.mu.Lock() w.ops = make(map[Op]struct{}) for _, op := range ops { w.ops[op] = struct{}{} } w.mu.Unlock() } // Add adds either a single file or directory to the file list. func (w *Watcher) Add(name string) (err error) { w.mu.Lock() defer w.mu.Unlock() name, err = filepath.Abs(name) if err != nil { return err } // If name is on the ignored list or if hidden files are // ignored and name is a hidden file or directory, simply return. _, ignored := w.ignored[name] isHidden, err := isHiddenFile(name) if err != nil { return err } if ignored || (w.ignoreHidden && isHidden) { return nil } // Add the directory's contents to the files list. fileList, err := w.list(name) if err != nil { return err } for k, v := range fileList { w.files[k] = v } // Add the name to the names list. w.names[name] = false return nil } func (w *Watcher) list(name string) (map[string]os.FileInfo, error) { fileList := make(map[string]os.FileInfo) // Make sure name exists. stat, err := os.Stat(name) if err != nil { return nil, err } fileList[name] = stat // If it's not a directory, just return. if !stat.IsDir() { return fileList, nil } // It's a directory. fInfoList, err := ioutil.ReadDir(name) if err != nil { return nil, err } // Add all of the files in the directory to the file list as long // as they aren't on the ignored list or are hidden files if ignoreHidden // is set to true. outer: for _, fInfo := range fInfoList { path := filepath.Join(name, fInfo.Name()) _, ignored := w.ignored[path] isHidden, err := isHiddenFile(path) if err != nil { return nil, err } if ignored || (w.ignoreHidden && isHidden) { continue } for _, f := range w.ffh { err := f(fInfo, path) if err == ErrSkip { continue outer } if err != nil { return nil, err } } fileList[path] = fInfo } return fileList, nil } // AddRecursive adds either a single file or directory recursively to the file list. func (w *Watcher) AddRecursive(name string) (err error) { w.mu.Lock() defer w.mu.Unlock() name, err = filepath.Abs(name) if err != nil { return err } fileList, err := w.listRecursive(name) if err != nil { return err } for k, v := range fileList { w.files[k] = v } // Add the name to the names list. w.names[name] = true return nil } func (w *Watcher) listRecursive(name string) (map[string]os.FileInfo, error) { fileList := make(map[string]os.FileInfo) return fileList, filepath.Walk(name, func(path string, info os.FileInfo, err error) error { if err != nil { return err } for _, f := range w.ffh { err := f(info, path) if err == ErrSkip { return nil } if err != nil { return err } } // If path is ignored and it's a directory, skip the directory. If it's // ignored and it's a single file, skip the file. _, ignored := w.ignored[path] isHidden, err := isHiddenFile(path) if err != nil { return err } if ignored || (w.ignoreHidden && isHidden) { if info.IsDir() { return filepath.SkipDir } return nil } // Add the path and it's info to the file list. fileList[path] = info return nil }) } // Remove removes either a single file or directory from the file's list. func (w *Watcher) Remove(name string) (err error) { w.mu.Lock() defer w.mu.Unlock() name, err = filepath.Abs(name) if err != nil { return err } // Remove the name from w's names list. delete(w.names, name) // If name is a single file, remove it and return. info, found := w.files[name] if !found { return nil // Doesn't exist, just return. } if !info.IsDir() { delete(w.files, name) return nil } // Delete the actual directory from w.files delete(w.files, name) // If it's a directory, delete all of it's contents from w.files. for path := range w.files { if filepath.Dir(path) == name { delete(w.files, path) } } return nil } // RemoveRecursive removes either a single file or a directory recursively from // the file's list. func (w *Watcher) RemoveRecursive(name string) (err error) { w.mu.Lock() defer w.mu.Unlock() name, err = filepath.Abs(name) if err != nil { return err } // Remove the name from w's names list. delete(w.names, name) // If name is a single file, remove it and return. info, found := w.files[name] if !found { return nil // Doesn't exist, just return. } if !info.IsDir() { delete(w.files, name) return nil } // If it's a directory, delete all of it's contents recursively // from w.files. for path := range w.files { if strings.HasPrefix(path, name) { delete(w.files, path) } } return nil } // Ignore adds paths that should be ignored. // // For files that are already added, Ignore removes them. func (w *Watcher) Ignore(paths ...string) (err error) { for _, path := range paths { path, err = filepath.Abs(path) if err != nil { return err } // Remove any of the paths that were already added. if err := w.RemoveRecursive(path); err != nil { return err } w.mu.Lock() w.ignored[path] = struct{}{} w.mu.Unlock() } return nil } // WatchedFiles returns a map of files added to a Watcher. func (w *Watcher) WatchedFiles() map[string]os.FileInfo { w.mu.Lock() defer w.mu.Unlock() files := make(map[string]os.FileInfo) for k, v := range w.files { files[k] = v } return files } // fileInfo is an implementation of os.FileInfo that can be used // as a mocked os.FileInfo when triggering an event when the specified // os.FileInfo is nil. type fileInfo struct { name string size int64 mode os.FileMode modTime time.Time sys interface{} dir bool } func (fs *fileInfo) IsDir() bool { return fs.dir } func (fs *fileInfo) ModTime() time.Time { return fs.modTime } func (fs *fileInfo) Mode() os.FileMode { return fs.mode } func (fs *fileInfo) Name() string { return fs.name } func (fs *fileInfo) Size() int64 { return fs.size } func (fs *fileInfo) Sys() interface{} { return fs.sys } // TriggerEvent is a method that can be used to trigger an event, separate to // the file watching process. func (w *Watcher) TriggerEvent(eventType Op, file os.FileInfo) { w.Wait() if file == nil { file = &fileInfo{name: "triggered event", modTime: time.Now()} } w.Event <- Event{Op: eventType, Path: "-", FileInfo: file} } func (w *Watcher) retrieveFileList() map[string]os.FileInfo { w.mu.Lock() defer w.mu.Unlock() fileList := make(map[string]os.FileInfo) var list map[string]os.FileInfo var err error for name, recursive := range w.names { if recursive { list, err = w.listRecursive(name) if err != nil { if os.IsNotExist(err) { w.mu.Unlock() if name == err.(*os.PathError).Path { w.Error <- ErrWatchedFileDeleted w.RemoveRecursive(name) } w.mu.Lock() } else { w.Error <- err } } } else { list, err = w.list(name) if err != nil { if os.IsNotExist(err) { w.mu.Unlock() if name == err.(*os.PathError).Path { w.Error <- ErrWatchedFileDeleted w.Remove(name) } w.mu.Lock() } else { w.Error <- err } } } // Add the file's to the file list. for k, v := range list { fileList[k] = v } } return fileList } // Start begins the polling cycle which repeats every specified // duration until Close is called. func (w *Watcher) Start(d time.Duration) error { // Return an error if d is less than 1 nanosecond. if d < time.Nanosecond { return ErrDurationTooShort } // Make sure the Watcher is not already running. w.mu.Lock() if w.running { w.mu.Unlock() return ErrWatcherRunning } w.running = true w.mu.Unlock() // Unblock w.Wait(). w.wg.Done() for { // done lets the inner polling cycle loop know when the // current cycle's method has finished executing. done := make(chan struct{}) // Any events that are found are first piped to evt before // being sent to the main Event channel. evt := make(chan Event) // Retrieve the file list for all watched file's and dirs. fileList := w.retrieveFileList() // cancel can be used to cancel the current event polling function. cancel := make(chan struct{}) // Look for events. go func() { w.pollEvents(fileList, evt, cancel) done <- struct{}{} }() // numEvents holds the number of events for the current cycle. numEvents := 0 inner: for { select { case <-w.close: close(cancel) close(w.Closed) return nil case event := <-evt: if len(w.ops) > 0 { // Filter Ops. _, found := w.ops[event.Op] if !found { continue } } numEvents++ if w.maxEvents > 0 && numEvents > w.maxEvents { close(cancel) break inner } w.Event <- event case <-done: // Current cycle is finished. break inner } } // Update the file's list. w.mu.Lock() w.files = fileList w.mu.Unlock() // Sleep and then continue to the next loop iteration. time.Sleep(d) } } func (w *Watcher) pollEvents(files map[string]os.FileInfo, evt chan Event, cancel chan struct{}) { w.mu.Lock() defer w.mu.Unlock() // Store create and remove events for use to check for rename events. creates := make(map[string]os.FileInfo) removes := make(map[string]os.FileInfo) // Check for removed files. for path, info := range w.files { if _, found := files[path]; !found { removes[path] = info } } // Check for created files, writes and chmods. for path, info := range files { oldInfo, found := w.files[path] if !found { // A file was created. creates[path] = info continue } if oldInfo.ModTime() != info.ModTime() { select { case <-cancel: return case evt <- Event{Write, path, path, info}: } } if oldInfo.Mode() != info.Mode() { select { case <-cancel: return case evt <- Event{Chmod, path, path, info}: } } } // Check for renames and moves. for path1, info1 := range removes { for path2, info2 := range creates { if sameFile(info1, info2) { e := Event{ Op: Move, Path: path2, OldPath: path1, FileInfo: info1, } // If they are from the same directory, it's a rename // instead of a move event. if filepath.Dir(path1) == filepath.Dir(path2) { e.Op = Rename } delete(removes, path1) delete(creates, path2) select { case <-cancel: return case evt <- e: } } } } // Send all the remaining create and remove events. for path, info := range creates { select { case <-cancel: return case evt <- Event{Create, path, "", info}: } } for path, info := range removes { select { case <-cancel: return case evt <- Event{Remove, path, path, info}: } } } // Wait blocks until the watcher is started. func (w *Watcher) Wait() { w.wg.Wait() } // Close stops a Watcher and unlocks its mutex, then sends a close signal. func (w *Watcher) Close() { w.mu.Lock() if !w.running { w.mu.Unlock() return } w.running = false w.files = make(map[string]os.FileInfo) w.names = make(map[string]bool) w.mu.Unlock() // Send a close signal to the Start method. w.close <- struct{}{} } watcher-1.0.7/watcher_test.go000066400000000000000000000521141352565163400162140ustar00rootroot00000000000000package watcher import ( "io/ioutil" "os" "path/filepath" "runtime" "sync" "testing" "time" ) // setup creates all required files and folders for // the tests and returns a function that is used as // a teardown function when the tests are done. func setup(t testing.TB) (string, func()) { testDir, err := ioutil.TempDir(".", "") if err != nil { t.Fatal(err) } err = ioutil.WriteFile(filepath.Join(testDir, "file.txt"), []byte{}, 0755) if err != nil { t.Fatal(err) } files := []string{"file_1.txt", "file_2.txt", "file_3.txt"} for _, f := range files { filePath := filepath.Join(testDir, f) if err := ioutil.WriteFile(filePath, []byte{}, 0755); err != nil { t.Fatal(err) } } err = ioutil.WriteFile(filepath.Join(testDir, ".dotfile"), []byte{}, 0755) if err != nil { t.Fatal(err) } testDirTwo := filepath.Join(testDir, "testDirTwo") err = os.Mkdir(testDirTwo, 0755) if err != nil { t.Fatal(err) } err = ioutil.WriteFile(filepath.Join(testDirTwo, "file_recursive.txt"), []byte{}, 0755) if err != nil { t.Fatal(err) } abs, err := filepath.Abs(testDir) if err != nil { os.RemoveAll(testDir) t.Fatal(err) } return abs, func() { if os.RemoveAll(testDir); err != nil { t.Fatal(err) } } } func TestEventString(t *testing.T) { e := &Event{Op: Create, Path: "/fake/path"} testCases := []struct { info os.FileInfo expected string }{ {nil, "???"}, { &fileInfo{name: "f1", dir: true}, "DIRECTORY \"f1\" CREATE [/fake/path]", }, { &fileInfo{name: "f2", dir: false}, "FILE \"f2\" CREATE [/fake/path]", }, } for _, tc := range testCases { e.FileInfo = tc.info if e.String() != tc.expected { t.Errorf("expected e.String() to be %s, got %s", tc.expected, e.String()) } } } func TestFileInfo(t *testing.T) { modTime := time.Now() fInfo := &fileInfo{ name: "finfo", size: 1, mode: os.ModeDir, modTime: modTime, sys: nil, dir: true, } // Test file info methods. if fInfo.Name() != "finfo" { t.Fatalf("expected fInfo.Name() to be 'finfo', got %s", fInfo.Name()) } if fInfo.IsDir() != true { t.Fatalf("expected fInfo.IsDir() to be true, got %t", fInfo.IsDir()) } if fInfo.Size() != 1 { t.Fatalf("expected fInfo.Size() to be 1, got %d", fInfo.Size()) } if fInfo.Sys() != nil { t.Fatalf("expected fInfo.Sys() to be nil, got %v", fInfo.Sys()) } if fInfo.ModTime() != modTime { t.Fatalf("expected fInfo.ModTime() to be %v, got %v", modTime, fInfo.ModTime()) } if fInfo.Mode() != os.ModeDir { t.Fatalf("expected fInfo.Mode() to be os.ModeDir, got %#v", fInfo.Mode()) } w := New() w.wg.Done() // Set the waitgroup to done. go func() { // Trigger an event with the file info. w.TriggerEvent(Create, fInfo) }() e := <-w.Event if e.FileInfo != fInfo { t.Fatal("expected e.FileInfo to be equal to fInfo") } } func TestWatcherAdd(t *testing.T) { testDir, teardown := setup(t) defer teardown() w := New() // Try to add a non-existing path. err := w.Add("-") if err == nil { t.Error("expected error to not be nil") } if err := w.Add(testDir); err != nil { t.Fatal(err) } if len(w.files) != 7 { t.Errorf("expected len(w.files) to be 7, got %d", len(w.files)) } // Make sure w.names contains testDir if _, found := w.names[testDir]; !found { t.Errorf("expected w.names to contain testDir") } if _, found := w.files[testDir]; !found { t.Errorf("expected to find %s", testDir) } if w.files[testDir].Name() != filepath.Base(testDir) { t.Errorf("expected w.files[%q].Name() to be %s, got %s", testDir, testDir, w.files[testDir].Name()) } dotFile := filepath.Join(testDir, ".dotfile") if _, found := w.files[dotFile]; !found { t.Errorf("expected to find %s", dotFile) } if w.files[dotFile].Name() != ".dotfile" { t.Errorf("expected w.files[%q].Name() to be .dotfile, got %s", dotFile, w.files[dotFile].Name()) } fileRecursive := filepath.Join(testDir, "testDirTwo", "file_recursive.txt") if _, found := w.files[fileRecursive]; found { t.Errorf("expected to not find %s", fileRecursive) } fileTxt := filepath.Join(testDir, "file.txt") if _, found := w.files[fileTxt]; !found { t.Errorf("expected to find %s", fileTxt) } if w.files[fileTxt].Name() != "file.txt" { t.Errorf("expected w.files[%q].Name() to be file.txt, got %s", fileTxt, w.files[fileTxt].Name()) } dirTwo := filepath.Join(testDir, "testDirTwo") if _, found := w.files[dirTwo]; !found { t.Errorf("expected to find %s directory", dirTwo) } if w.files[dirTwo].Name() != "testDirTwo" { t.Errorf("expected w.files[%q].Name() to be testDirTwo, got %s", dirTwo, w.files[dirTwo].Name()) } } func TestIgnore(t *testing.T) { testDir, teardown := setup(t) defer teardown() w := New() err := w.Add(testDir) if err != nil { t.Errorf("expected error to be nil, got %s", err) } if len(w.files) != 7 { t.Errorf("expected len(w.files) to be 7, got %d", len(w.files)) } err = w.Ignore(testDir) if err != nil { t.Errorf("expected error to be nil, got %s", err) } if len(w.files) != 0 { t.Errorf("expected len(w.files) to be 0, got %d", len(w.files)) } // Now try to add the ignored directory. err = w.Add(testDir) if err != nil { t.Errorf("expected error to be nil, got %s", err) } if len(w.files) != 0 { t.Errorf("expected len(w.files) to be 0, got %d", len(w.files)) } } func TestRemove(t *testing.T) { testDir, teardown := setup(t) defer teardown() w := New() err := w.Add(testDir) if err != nil { t.Errorf("expected error to be nil, got %s", err) } if len(w.files) != 7 { t.Errorf("expected len(w.files) to be 7, got %d", len(w.files)) } err = w.Remove(testDir) if err != nil { t.Errorf("expected error to be nil, got %s", err) } if len(w.files) != 0 { t.Errorf("expected len(w.files) to be 0, got %d", len(w.files)) } // TODO: Test remove single file. } // TODO: Test remove recursive function. func TestIgnoreHiddenFilesRecursive(t *testing.T) { // TODO: Write tests for ignore hidden on windows. if runtime.GOOS == "windows" { return } testDir, teardown := setup(t) defer teardown() w := New() w.IgnoreHiddenFiles(true) if err := w.AddRecursive(testDir); err != nil { t.Fatal(err) } if len(w.files) != 7 { t.Errorf("expected len(w.files) to be 7, got %d", len(w.files)) } // Make sure w.names contains testDir if _, found := w.names[testDir]; !found { t.Errorf("expected w.names to contain testDir") } if _, found := w.files[testDir]; !found { t.Errorf("expected to find %s", testDir) } if w.files[testDir].Name() != filepath.Base(testDir) { t.Errorf("expected w.files[%q].Name() to be %s, got %s", testDir, filepath.Base(testDir), w.files[testDir].Name()) } fileRecursive := filepath.Join(testDir, "testDirTwo", "file_recursive.txt") if _, found := w.files[fileRecursive]; !found { t.Errorf("expected to find %s", fileRecursive) } if _, found := w.files[filepath.Join(testDir, ".dotfile")]; found { t.Error("expected to not find .dotfile") } fileTxt := filepath.Join(testDir, "file.txt") if _, found := w.files[fileTxt]; !found { t.Errorf("expected to find %s", fileTxt) } if w.files[fileTxt].Name() != "file.txt" { t.Errorf("expected w.files[%q].Name() to be file.txt, got %s", fileTxt, w.files[fileTxt].Name()) } dirTwo := filepath.Join(testDir, "testDirTwo") if _, found := w.files[dirTwo]; !found { t.Errorf("expected to find %s directory", dirTwo) } if w.files[dirTwo].Name() != "testDirTwo" { t.Errorf("expected w.files[%q].Name() to be testDirTwo, got %s", dirTwo, w.files[dirTwo].Name()) } } func TestIgnoreHiddenFiles(t *testing.T) { // TODO: Write tests for ignore hidden on windows. if runtime.GOOS == "windows" { return } testDir, teardown := setup(t) defer teardown() w := New() w.IgnoreHiddenFiles(true) if err := w.Add(testDir); err != nil { t.Fatal(err) } if len(w.files) != 6 { t.Errorf("expected len(w.files) to be 6, got %d", len(w.files)) } // Make sure w.names contains testDir if _, found := w.names[testDir]; !found { t.Errorf("expected w.names to contain testDir") } if _, found := w.files[testDir]; !found { t.Errorf("expected to find %s", testDir) } if w.files[testDir].Name() != filepath.Base(testDir) { t.Errorf("expected w.files[%q].Name() to be %s, got %s", testDir, filepath.Base(testDir), w.files[testDir].Name()) } if _, found := w.files[filepath.Join(testDir, ".dotfile")]; found { t.Error("expected to not find .dotfile") } fileRecursive := filepath.Join(testDir, "testDirTwo", "file_recursive.txt") if _, found := w.files[fileRecursive]; found { t.Errorf("expected to not find %s", fileRecursive) } fileTxt := filepath.Join(testDir, "file.txt") if _, found := w.files[fileTxt]; !found { t.Errorf("expected to find %s", fileTxt) } if w.files[fileTxt].Name() != "file.txt" { t.Errorf("expected w.files[%q].Name() to be file.txt, got %s", fileTxt, w.files[fileTxt].Name()) } dirTwo := filepath.Join(testDir, "testDirTwo") if _, found := w.files[dirTwo]; !found { t.Errorf("expected to find %s directory", dirTwo) } if w.files[dirTwo].Name() != "testDirTwo" { t.Errorf("expected w.files[%q].Name() to be testDirTwo, got %s", dirTwo, w.files[dirTwo].Name()) } } func TestWatcherAddRecursive(t *testing.T) { testDir, teardown := setup(t) defer teardown() w := New() if err := w.AddRecursive(testDir); err != nil { t.Fatal(err) } // Make sure len(w.files) is 8. if len(w.files) != 8 { t.Errorf("expected 8 files, found %d", len(w.files)) } // Make sure w.names contains testDir if _, found := w.names[testDir]; !found { t.Errorf("expected w.names to contain testDir") } dirTwo := filepath.Join(testDir, "testDirTwo") if _, found := w.files[dirTwo]; !found { t.Errorf("expected to find %s directory", dirTwo) } if w.files[dirTwo].Name() != "testDirTwo" { t.Errorf("expected w.files[%q].Name() to be testDirTwo, got %s", "testDirTwo", w.files[dirTwo].Name()) } fileRecursive := filepath.Join(dirTwo, "file_recursive.txt") if _, found := w.files[fileRecursive]; !found { t.Errorf("expected to find %s directory", fileRecursive) } if w.files[fileRecursive].Name() != "file_recursive.txt" { t.Errorf("expected w.files[%q].Name() to be file_recursive.txt, got %s", fileRecursive, w.files[fileRecursive].Name()) } } func TestWatcherAddNotFound(t *testing.T) { w := New() // Make sure there is an error when adding a // non-existent file/folder. if err := w.AddRecursive("random_filename.txt"); err == nil { t.Error("expected a file not found error") } } func TestWatcherRemoveRecursive(t *testing.T) { testDir, teardown := setup(t) defer teardown() w := New() // Add the testDir to the watchlist. if err := w.AddRecursive(testDir); err != nil { t.Fatal(err) } // Make sure len(w.files) is 8. if len(w.files) != 8 { t.Errorf("expected 8 files, found %d", len(w.files)) } // Now remove the folder from the watchlist. if err := w.RemoveRecursive(testDir); err != nil { t.Error(err) } // Now check that there is nothing being watched. if len(w.files) != 0 { t.Errorf("expected len(w.files) to be 0, got %d", len(w.files)) } // Make sure len(w.names) is now 0. if len(w.names) != 0 { t.Errorf("expected len(w.names) to be empty, len(w.names): %d", len(w.names)) } } func TestListFiles(t *testing.T) { testDir, teardown := setup(t) defer teardown() w := New() w.AddRecursive(testDir) fileList := w.retrieveFileList() if fileList == nil { t.Error("expected file list to not be empty") } // Make sure fInfoTest contains the correct os.FileInfo names. fname := filepath.Join(testDir, "file.txt") if fileList[fname].Name() != "file.txt" { t.Errorf("expected fileList[%s].Name() to be file.txt, got %s", fname, fileList[fname].Name()) } // Try to call list on a file that's not a directory. fileList, err := w.list(fname) if err != nil { t.Error("expected err to be nil") } if len(fileList) != 1 { t.Errorf("expected len of file list to be 1, got %d", len(fileList)) } } func TestTriggerEvent(t *testing.T) { w := New() var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() select { case event := <-w.Event: if event.Name() != "triggered event" { t.Errorf("expected event file name to be triggered event, got %s", event.Name()) } case <-time.After(time.Millisecond * 250): t.Fatal("received no event from Event channel") } }() go func() { // Start the watching process. if err := w.Start(time.Millisecond * 100); err != nil { t.Fatal(err) } }() w.TriggerEvent(Create, nil) wg.Wait() } func TestEventAddFile(t *testing.T) { testDir, teardown := setup(t) defer teardown() w := New() w.FilterOps(Create) // Add the testDir to the watchlist. if err := w.AddRecursive(testDir); err != nil { t.Fatal(err) } files := map[string]bool{ "newfile_1.txt": false, "newfile_2.txt": false, "newfile_3.txt": false, } for f := range files { filePath := filepath.Join(testDir, f) if err := ioutil.WriteFile(filePath, []byte{}, 0755); err != nil { t.Error(err) } } var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() events := 0 for { select { case event := <-w.Event: if event.Op != Create { t.Errorf("expected event to be Create, got %s", event.Op) } files[event.Name()] = true events++ // Check Path and OldPath content newFile := filepath.Join(testDir, event.Name()) if event.Path != newFile { t.Errorf("Event.Path should be %s but got %s", newFile, event.Path) } if event.OldPath != "" { t.Errorf("Event.OldPath should be empty on create, but got %s", event.OldPath) } if events == len(files) { return } case <-time.After(time.Millisecond * 250): for f, e := range files { if !e { t.Errorf("received no event for file %s", f) } } return } } }() go func() { // Start the watching process. if err := w.Start(time.Millisecond * 100); err != nil { t.Fatal(err) } }() wg.Wait() } // TODO: TestIgnoreFiles func TestIgnoreFiles(t *testing.T) {} func TestEventDeleteFile(t *testing.T) { testDir, teardown := setup(t) defer teardown() w := New() w.FilterOps(Remove) // Add the testDir to the watchlist. if err := w.AddRecursive(testDir); err != nil { t.Fatal(err) } files := map[string]bool{ "file_1.txt": false, "file_2.txt": false, "file_3.txt": false, } for f := range files { filePath := filepath.Join(testDir, f) if err := os.Remove(filePath); err != nil { t.Error(err) } } var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() events := 0 for { select { case event := <-w.Event: if event.Op != Remove { t.Errorf("expected event to be Remove, got %s", event.Op) } files[event.Name()] = true events++ if events == len(files) { return } case <-time.After(time.Millisecond * 250): for f, e := range files { if !e { t.Errorf("received no event for file %s", f) } } return } } }() go func() { // Start the watching process. if err := w.Start(time.Millisecond * 100); err != nil { t.Fatal(err) } }() wg.Wait() } func TestEventRenameFile(t *testing.T) { testDir, teardown := setup(t) defer teardown() srcFilename := "file.txt" dstFilename := "file1.txt" w := New() w.FilterOps(Rename) // Add the testDir to the watchlist. if err := w.AddRecursive(testDir); err != nil { t.Fatal(err) } // Rename a file. if err := os.Rename( filepath.Join(testDir, srcFilename), filepath.Join(testDir, dstFilename), ); err != nil { t.Error(err) } var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() select { case event := <-w.Event: if event.Op != Rename { t.Errorf("expected event to be Rename, got %s", event.Op) } // Check Path and OldPath content oldFile := filepath.Join(testDir, srcFilename) newFile := filepath.Join(testDir, dstFilename) if event.Path != newFile { t.Errorf("Event.Path should be %s but got %s", newFile, event.Path) } if event.OldPath != oldFile { t.Errorf("Event.OldPath should %s but got %s", oldFile, event.OldPath) } case <-time.After(time.Millisecond * 250): t.Fatal("received no rename event") } }() go func() { // Start the watching process. if err := w.Start(time.Millisecond * 100); err != nil { t.Fatal(err) } }() wg.Wait() } func TestEventChmodFile(t *testing.T) { // Chmod is not supported under windows. if runtime.GOOS == "windows" { return } testDir, teardown := setup(t) defer teardown() w := New() w.FilterOps(Chmod) // Add the testDir to the watchlist. if err := w.Add(testDir); err != nil { t.Fatal(err) } files := map[string]bool{ "file_1.txt": false, "file_2.txt": false, "file_3.txt": false, } for f := range files { filePath := filepath.Join(testDir, f) if err := os.Chmod(filePath, os.ModePerm); err != nil { t.Error(err) } } var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() events := 0 for { select { case event := <-w.Event: if event.Op != Chmod { t.Errorf("expected event to be Remove, got %s", event.Op) } files[event.Name()] = true events++ if events == len(files) { return } case <-time.After(time.Millisecond * 250): for f, e := range files { if !e { t.Errorf("received no event for file %s", f) } } return } } }() go func() { // Start the watching process. if err := w.Start(time.Millisecond * 100); err != nil { t.Fatal(err) } }() wg.Wait() } func TestWatcherStartWithInvalidDuration(t *testing.T) { w := New() err := w.Start(0) if err != ErrDurationTooShort { t.Fatalf("expected ErrDurationTooShort error, got %s", err.Error()) } } func TestWatcherStartWhenAlreadyRunning(t *testing.T) { w := New() go func() { err := w.Start(time.Millisecond * 100) if err != nil { t.Fatal(err) } }() w.Wait() err := w.Start(time.Millisecond * 100) if err != ErrWatcherRunning { t.Fatalf("expected ErrWatcherRunning error, got %s", err.Error()) } } func BenchmarkEventRenameFile(b *testing.B) { testDir, teardown := setup(b) defer teardown() w := New() w.FilterOps(Rename) // Add the testDir to the watchlist. if err := w.AddRecursive(testDir); err != nil { b.Fatal(err) } go func() { // Start the watching process. if err := w.Start(time.Millisecond); err != nil { b.Fatal(err) } }() var filenameFrom = filepath.Join(testDir, "file.txt") var filenameTo = filepath.Join(testDir, "file1.txt") for i := 0; i < b.N; i++ { // Rename a file. if err := os.Rename( filenameFrom, filenameTo, ); err != nil { b.Error(err) } select { case event := <-w.Event: if event.Op != Rename { b.Errorf("expected event to be Rename, got %s", event.Op) } case <-time.After(time.Millisecond * 250): b.Fatal("received no rename event") } filenameFrom, filenameTo = filenameTo, filenameFrom } } func BenchmarkListFiles(b *testing.B) { testDir, teardown := setup(b) defer teardown() w := New() err := w.AddRecursive(testDir) if err != nil { b.Fatal(err) } for i := 0; i < b.N; i++ { fileList := w.retrieveFileList() if fileList == nil { b.Fatal("expected file list to not be empty") } } } func TestClose(t *testing.T) { testDir, teardown := setup(t) defer teardown() w := New() err := w.Add(testDir) if err != nil { t.Fatal(err) } wf := w.WatchedFiles() fileList := w.retrieveFileList() if len(wf) != len(fileList) { t.Fatalf("expected len of wf to be %d, got %d", len(fileList), len(wf)) } // Call close on the watcher even though it's not running. w.Close() wf = w.WatchedFiles() fileList = w.retrieveFileList() // Close will be a no-op so there will still be len(fileList) files. if len(wf) != len(fileList) { t.Fatalf("expected len of wf to be %d, got %d", len(fileList), len(wf)) } // Set running to true. w.running = true // Now close the watcher. go func() { // Receive from the w.close channel to avoid a deadlock. <-w.close }() w.Close() wf = w.WatchedFiles() // Close will be a no-op so there will still be len(fileList) files. if len(wf) != 0 { t.Fatalf("expected len of wf to be 0, got %d", len(wf)) } } func TestWatchedFiles(t *testing.T) { testDir, teardown := setup(t) defer teardown() w := New() err := w.Add(testDir) if err != nil { t.Fatal(err) } wf := w.WatchedFiles() fileList := w.retrieveFileList() if len(wf) != len(fileList) { t.Fatalf("expected len of wf to be %d, got %d", len(fileList), len(wf)) } for path := range fileList { if _, found := wf[path]; !found { t.Fatalf("%s not found in watched file's list", path) } } } func TestSetMaxEvents(t *testing.T) { w := New() if w.maxEvents != 0 { t.Fatalf("expected max events to be 0, got %d", w.maxEvents) } w.SetMaxEvents(3) if w.maxEvents != 3 { t.Fatalf("expected max events to be 3, got %d", w.maxEvents) } } func TestOpsString(t *testing.T) { testCases := []struct { want Op expected string }{ {Create, "CREATE"}, {Write, "WRITE"}, {Remove, "REMOVE"}, {Rename, "RENAME"}, {Chmod, "CHMOD"}, {Move, "MOVE"}, {Op(10), "???"}, } for _, tc := range testCases { if tc.want.String() != tc.expected { t.Errorf("expected %s, got %s", tc.expected, tc.want.String()) } } }