Skip to content

Commit 9a7ee0c

Browse files
committed
修复问题
1 parent 84223f2 commit 9a7ee0c

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
//go:build !windows
2+
13
package utils
24

35
import (

internal/utils/disk_windows.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
//go:build windows
2+
3+
package utils
4+
5+
import (
6+
"fmt"
7+
"path/filepath"
8+
"strings"
9+
10+
"golang.org/x/sys/windows"
11+
)
12+
13+
// GetUsagePercent returns disk usage percentage for the drive containing the given path on Windows.
14+
func GetUsagePercent(path string) (float64, error) {
15+
volume, err := resolveVolume(path)
16+
if err != nil {
17+
return 0, err
18+
}
19+
20+
var (
21+
freeBytesAvailable uint64
22+
totalNumberOfBytes uint64
23+
totalNumberOfFree uint64
24+
)
25+
26+
if err := windows.GetDiskFreeSpaceEx(windows.StringToUTF16Ptr(volume), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFree); err != nil {
27+
return 0, err
28+
}
29+
30+
if totalNumberOfBytes == 0 {
31+
return 0, fmt.Errorf("unable to compute total disk size for %s", volume)
32+
}
33+
34+
used := totalNumberOfBytes - totalNumberOfFree
35+
usage := (float64(used) / float64(totalNumberOfBytes)) * 100.0
36+
return usage, nil
37+
}
38+
39+
func resolveVolume(path string) (string, error) {
40+
absPath, err := filepath.Abs(path)
41+
if err != nil {
42+
return "", err
43+
}
44+
45+
volume := filepath.VolumeName(absPath)
46+
if volume == "" {
47+
return "", fmt.Errorf("unable to determine volume for path %s", absPath)
48+
}
49+
50+
// Ensure the volume points to root (e.g., "C:\")
51+
if !strings.HasSuffix(volume, "\\") {
52+
volume += "\\"
53+
}
54+
55+
return volume, nil
56+
}

0 commit comments

Comments
 (0)