Adjust callback to support continuing or stopping at current depth
This commit is contained in:
parent
9dcf06d106
commit
3bca54655b
|
@ -155,8 +155,13 @@ func (fs *Filesystem) DirectorySize(dir string) (int64, error) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
var size int64
|
var size int64
|
||||||
err := w.Walk(dir, ctx, func(f os.FileInfo) {
|
err := w.Walk(dir, ctx, func(f os.FileInfo) bool {
|
||||||
atomic.AddInt64(&size, f.Size())
|
// Only increment the size when we're dealing with a file specifically, otherwise
|
||||||
|
// just continue digging deeper until there are no more directories to iterate over.
|
||||||
|
if !f.IsDir() {
|
||||||
|
atomic.AddInt64(&size, f.Size())
|
||||||
|
}
|
||||||
|
return true
|
||||||
})
|
})
|
||||||
|
|
||||||
return size, err
|
return size, err
|
||||||
|
|
|
@ -20,7 +20,7 @@ func (fs *Filesystem) NewWalker() *FileWalker {
|
||||||
// Iterate over all of the files and directories within a given directory. When a file is
|
// Iterate over all of the files and directories within a given directory. When a file is
|
||||||
// found the callback will be called with the file information. If a directory is encountered
|
// found the callback will be called with the file information. If a directory is encountered
|
||||||
// it will be recursively passed back through to this function.
|
// it will be recursively passed back through to this function.
|
||||||
func (fw *FileWalker) Walk(dir string, ctx context.Context, callback func (os.FileInfo)) error {
|
func (fw *FileWalker) Walk(dir string, ctx context.Context, callback func (os.FileInfo) bool) error {
|
||||||
cleaned, err := fw.SafePath(dir)
|
cleaned, err := fw.SafePath(dir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
@ -46,12 +46,20 @@ func (fw *FileWalker) Walk(dir string, ctx context.Context, callback func (os.Fi
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return ctx.Err()
|
return ctx.Err()
|
||||||
default:
|
default:
|
||||||
return fw.Walk(p, ctx, callback)
|
// If the callback returns true, go ahead and keep walking deeper. This allows
|
||||||
|
// us to programatically continue deeper into directories, or stop digging
|
||||||
|
// if that pathway knows it needs nothing else.
|
||||||
|
if callback(f) {
|
||||||
|
return fw.Walk(p, ctx, callback)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
// If this isn't a directory, go ahead and pass the file information into the
|
// If this isn't a directory, go ahead and pass the file information into the
|
||||||
// callback.
|
// callback. We don't care about the response since we won't be stepping into
|
||||||
|
// anything from here.
|
||||||
callback(f)
|
callback(f)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user