@@ -3,13 +3,14 @@ package watcher
33import (
44 "errors"
55 "fmt"
6- "io/ioutil"
76 "os"
87 "path/filepath"
98 "regexp"
109 "strings"
1110 "sync"
1211 "time"
12+
13+ "github.com/spf13/afero"
1314)
1415
1516var (
@@ -129,6 +130,7 @@ type Watcher struct {
129130 ops map [Op ]struct {} // Op filtering.
130131 ignoreHidden bool // ignore hidden files or not.
131132 maxEvents int // max sent events per cycle
133+ fs afero.Fs // filesystem to use
132134}
133135
134136// New creates a new Watcher.
@@ -147,9 +149,16 @@ func New() *Watcher {
147149 files : make (map [string ]os.FileInfo ),
148150 ignored : make (map [string ]struct {}),
149151 names : make (map [string ]bool ),
152+ fs : afero .NewOsFs (),
150153 }
151154}
152155
156+ // SetFileSystem lets you specify an alternative FS to work against.
157+ // The default is afero's OsFs which maps to the system FS.
158+ func (w * Watcher ) SetFileSystem (fs afero.Fs ) {
159+ w .fs = fs
160+ }
161+
153162// SetMaxEvents controls the maximum amount of events that are sent on
154163// the Event channel per watching cycle. If max events is less than 1, there is
155164// no limit, which is the default.
@@ -227,7 +236,7 @@ func (w *Watcher) list(name string) (map[string]os.FileInfo, error) {
227236 fileList := make (map [string ]os.FileInfo )
228237
229238 // Make sure name exists.
230- stat , err := os .Stat (name )
239+ stat , err := w . fs .Stat (name )
231240 if err != nil {
232241 return nil , err
233242 }
@@ -240,7 +249,7 @@ func (w *Watcher) list(name string) (map[string]os.FileInfo, error) {
240249 }
241250
242251 // It's a directory.
243- fInfoList , err := ioutil .ReadDir (name )
252+ fInfoList , err := afero .ReadDir (w . fs , name )
244253 if err != nil {
245254 return nil , err
246255 }
@@ -303,7 +312,7 @@ func (w *Watcher) AddRecursive(name string) (err error) {
303312func (w * Watcher ) listRecursive (name string ) (map [string ]os.FileInfo , error ) {
304313 fileList := make (map [string ]os.FileInfo )
305314
306- return fileList , filepath .Walk (name , func (path string , info os.FileInfo , err error ) error {
315+ return fileList , afero .Walk (w . fs , name , func (path string , info os.FileInfo , err error ) error {
307316 if err != nil {
308317 return err
309318 }
0 commit comments