2013-11-07 15:34:01 -05:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2013-11-21 20:18:41 -05:00
|
|
|
"syscall"
|
2013-11-07 15:34:01 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// TreeSize walks a directory tree and returns its total size in bytes.
|
|
|
|
func TreeSize(dir string) (size int64, err error) {
|
2013-11-21 20:18:41 -05:00
|
|
|
data := make(map[uint64]bool)
|
2013-11-07 15:34:01 -05:00
|
|
|
err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error {
|
2013-11-13 13:33:24 -05:00
|
|
|
// Ignore directory sizes
|
2013-11-21 20:18:41 -05:00
|
|
|
if fileInfo == nil {
|
2013-11-13 13:33:24 -05:00
|
|
|
return nil
|
|
|
|
}
|
2013-11-21 20:18:41 -05:00
|
|
|
|
|
|
|
s := fileInfo.Size()
|
|
|
|
if fileInfo.IsDir() || s == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check inode to handle hard links correctly
|
|
|
|
inode := fileInfo.Sys().(*syscall.Stat_t).Ino
|
|
|
|
if _, exists := data[inode]; exists {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
data[inode] = false
|
|
|
|
|
|
|
|
size += s
|
|
|
|
|
2013-11-07 15:34:01 -05:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|