From cd53ec524410020db312089f2623b1a50f30121e Mon Sep 17 00:00:00 2001 From: Akihiro Suda Date: Fri, 27 May 2016 02:47:32 +0000 Subject: [PATCH] Fix filepath.Walk misusage in pkg/directory Signed-off-by: Akihiro Suda --- pkg/directory/directory_test.go | 7 +++++++ pkg/directory/directory_unix.go | 11 ++++++++++- pkg/directory/directory_windows.go | 11 ++++++++++- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/pkg/directory/directory_test.go b/pkg/directory/directory_test.go index 4611062848..2b7a4657be 100644 --- a/pkg/directory/directory_test.go +++ b/pkg/directory/directory_test.go @@ -183,3 +183,10 @@ func TestMoveToSubdir(t *testing.T) { t.Fatalf("Results after migration do not equal list of files: expected: %v, got: %v", filesList, results) } } + +// Test a non-existing directory +func TestSizeNonExistingDirectory(t *testing.T) { + if _, err := Size("/thisdirectoryshouldnotexist/TestSizeNonExistingDirectory"); err == nil { + t.Fatalf("error is expected") + } +} diff --git a/pkg/directory/directory_unix.go b/pkg/directory/directory_unix.go index b43c79fb85..397251bdb8 100644 --- a/pkg/directory/directory_unix.go +++ b/pkg/directory/directory_unix.go @@ -11,7 +11,16 @@ import ( // Size walks a directory tree and returns its total size in bytes. func Size(dir string) (size int64, err error) { data := make(map[uint64]struct{}) - err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error { + err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, err error) error { + if err != nil { + // if dir does not exist, Size() returns the error. + // if dir/x disappeared while walking, Size() ignores dir/x. + if os.IsNotExist(err) && d != dir { + return nil + } + return err + } + // Ignore directory sizes if fileInfo == nil { return nil diff --git a/pkg/directory/directory_windows.go b/pkg/directory/directory_windows.go index 7a9f8cb68c..6fb0917c4c 100644 --- a/pkg/directory/directory_windows.go +++ b/pkg/directory/directory_windows.go @@ -9,7 +9,16 @@ import ( // Size walks a directory tree and returns its total size in bytes. func Size(dir string) (size int64, err error) { - err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error { + err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, err error) error { + if err != nil { + // if dir does not exist, Size() returns the error. + // if dir/x disappeared while walking, Size() ignores dir/x. + if os.IsNotExist(err) && d != dir { + return nil + } + return err + } + // Ignore directory sizes if fileInfo == nil { return nil