Merge pull request #23038 from AkihiroSuda/fixPkgDirectoryFilepathWalk
Fix filepath.Walk misusage in pkg/directory
This commit is contained in:
commit
c8ac41d83b
3 changed files with 27 additions and 2 deletions
|
@ -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)
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -11,7 +11,16 @@ import (
|
||||||
// Size walks a directory tree and returns its total size in bytes.
|
// Size walks a directory tree and returns its total size in bytes.
|
||||||
func Size(dir string) (size int64, err error) {
|
func Size(dir string) (size int64, err error) {
|
||||||
data := make(map[uint64]struct{})
|
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
|
// Ignore directory sizes
|
||||||
if fileInfo == nil {
|
if fileInfo == nil {
|
||||||
return nil
|
return nil
|
||||||
|
|
|
@ -9,7 +9,16 @@ import (
|
||||||
|
|
||||||
// Size walks a directory tree and returns its total size in bytes.
|
// Size walks a directory tree and returns its total size in bytes.
|
||||||
func Size(dir string) (size int64, err error) {
|
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
|
// Ignore directory sizes
|
||||||
if fileInfo == nil {
|
if fileInfo == nil {
|
||||||
return nil
|
return nil
|
||||||
|
|
Loading…
Reference in a new issue