utils_daemon.go 842 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. // +build daemon
  2. package utils
  3. import (
  4. "os"
  5. "path/filepath"
  6. "syscall"
  7. )
  8. // TreeSize walks a directory tree and returns its total size in bytes.
  9. func TreeSize(dir string) (size int64, err error) {
  10. data := make(map[uint64]struct{})
  11. err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error {
  12. // Ignore directory sizes
  13. if fileInfo == nil {
  14. return nil
  15. }
  16. s := fileInfo.Size()
  17. if fileInfo.IsDir() || s == 0 {
  18. return nil
  19. }
  20. // Check inode to handle hard links correctly
  21. inode := fileInfo.Sys().(*syscall.Stat_t).Ino
  22. // inode is not a uint64 on all platforms. Cast it to avoid issues.
  23. if _, exists := data[uint64(inode)]; exists {
  24. return nil
  25. }
  26. // inode is not a uint64 on all platforms. Cast it to avoid issues.
  27. data[uint64(inode)] = struct{}{}
  28. size += s
  29. return nil
  30. })
  31. return
  32. }