diff --git a/du/diskusage.go b/du/diskusage.go index 27556ad..6fcc42a 100644 --- a/du/diskusage.go +++ b/du/diskusage.go @@ -1,21 +1,33 @@ +//go:build !windows // +build !windows package du -import "syscall" +import ( + "golang.org/x/sys/unix" +) // DiskUsage contains usage data and provides user-friendly access methods type DiskUsage struct { - stat *syscall.Statfs_t + stat *unix.Statfs_t } // NewDiskUsages returns an object holding the disk usage of volumePath // or nil in case of error (invalid path, etc) func NewDiskUsage(volumePath string) *DiskUsage { + du, _ := NewDiskUsageOrError(volumePath) + return du +} - var stat syscall.Statfs_t - syscall.Statfs(volumePath, &stat) - return &DiskUsage{&stat} +// NewDiskUsagesOrError returns an object holding the disk usage of volumePath +// or any error (invalid path, etc) +func NewDiskUsageOrError(volumePath string) (*DiskUsage, error) { + stat := unix.Statfs_t{} + err := unix.Statfs(volumePath, &stat) + if err != nil { + return nil, err + } + return &DiskUsage{&stat}, nil } // Free returns total free bytes on file system diff --git a/du/diskusage_windows.go b/du/diskusage_windows.go index ee14f40..702eea8 100644 --- a/du/diskusage_windows.go +++ b/du/diskusage_windows.go @@ -1,8 +1,9 @@ package du import ( - "syscall" "unsafe" + + "golang.org/x/sys/windows" ) type DiskUsage struct { @@ -14,19 +15,30 @@ type DiskUsage struct { // NewDiskUsages returns an object holding the disk usage of volumePath // or nil in case of error (invalid path, etc) func NewDiskUsage(volumePath string) *DiskUsage { + du, _ := NewDiskUsageOrError(volumePath) + return du +} - h := syscall.MustLoadDLL("kernel32.dll") +// NewDiskUsagesOrError returns an object holding the disk usage of volumePath +// or any error (invalid path, etc) +func NewDiskUsageOrError(volumePath string) (*DiskUsage, error) { + h := windows.MustLoadDLL("kernel32.dll") c := h.MustFindProc("GetDiskFreeSpaceExW") du := &DiskUsage{} - c.Call( - uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(volumePath))), + r1, _, err := c.Call( + uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(volumePath))), uintptr(unsafe.Pointer(&du.freeBytes)), uintptr(unsafe.Pointer(&du.totalBytes)), uintptr(unsafe.Pointer(&du.availBytes))) - return du + // If the function fails, the return value is zero (0) + if r1 == 0 { + return nil, err + } + + return du, nil } // Free returns total free bytes on file system