...

Source file src/golang.conradwood.net/go-easyops/linux/dir_size.go

Documentation: golang.conradwood.net/go-easyops/linux

     1  package linux
     2  
     3  import (
     4  	"errors"
     5  	"golang.conradwood.net/go-easyops/utils"
     6  	"os"
     7  )
     8  
     9  // if dir is the name of a directory, it will recursively calculate the size. if it is a file, it will stat it and return the filesize
    10  func DirSize(dir string) (uint64, error) {
    11  	fi, err := os.Stat(dir)
    12  	if err != nil {
    13  		if errors.Is(err, os.ErrNotExist) {
    14  			return 0, nil
    15  		}
    16  		return 0, err
    17  	}
    18  	if !fi.IsDir() {
    19  		return uint64(fi.Size()), nil
    20  	}
    21  	res := uint64(0)
    22  	utils.DirWalk(dir, func(root, relfile string) error {
    23  		fname := root + "/" + relfile
    24  		fi, err := os.Stat(fname)
    25  		if err != nil {
    26  			return err
    27  		}
    28  		res = res + uint64(fi.Size())
    29  		return nil
    30  	})
    31  	return res, nil
    32  }
    33  

View as plain text