Skip to content

Commit

Permalink
Replace call to du in getDirSize with native code
Browse files Browse the repository at this point in the history
  • Loading branch information
matbme authored and taukakao committed Jul 30, 2024
1 parent 49c823f commit 6a62354
Showing 1 changed file with 23 additions and 16 deletions.
39 changes: 23 additions & 16 deletions core/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,11 @@ package core
*/

import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"strconv"
"strings"
)

var abrootDir = "/etc/abroot"
Expand Down Expand Up @@ -128,26 +125,36 @@ func isDeviceLUKSEncrypted(devicePath string) (bool, error) {
}

// getDirSize calculates the total size of a directory recursively.
//
// FIXME: find a way to avoid using du and any other external command
func getDirSize(path string) (int64, error) {
cmd := exec.Command("du", "-s", "-b", path)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
ds, err := os.Stat(path)
if err != nil {
return 0, err
}

output := strings.Fields(out.String())
if len(output) == 0 {
return 0, errors.New("failed to get directory size")
if !ds.IsDir() {
return 0, fmt.Errorf("%s is not a directory", path)
}

size, err := strconv.ParseInt(output[0], 10, 64)
var totalSize int64 = 0

dfs := os.DirFS(path)
err = fs.WalkDir(dfs, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}

if !d.IsDir() {
fileInfo, err := d.Info()
if err != nil {
return err
}
totalSize += fileInfo.Size()
}

return nil
})
if err != nil {
return 0, err
}

return size, nil
return totalSize, nil
}

0 comments on commit 6a62354

Please sign in to comment.