Refactor Disk and Memory Size Formatting with Centralized Utility Function

- Extracted common size formatting logic to a new utility function `HumanSize` in utils package
- Removed duplicate size formatting code from Disk and Memory configurations
- Updated Disk and Memory modules to use the centralized size formatting utility
- Uncommented and implemented disk usage calculation in Disk configuration
- Improved code readability and maintainability by centralizing size conversion logic
This commit is contained in:
zeaslity
2025-02-27 15:15:55 +08:00
parent 8fc55e2e28
commit b6cc5abc63
4 changed files with 70 additions and 57 deletions

View File

@@ -2,6 +2,7 @@ package config
import (
"agent-wdd/log"
"agent-wdd/utils"
"os"
"os/exec"
"strconv"
@@ -27,7 +28,7 @@ func (mem *Memory) Gather() {
if err != nil {
mem.Size = "0B"
} else {
mem.Size = formatSize(kb * 1024)
mem.Size = utils.HumanSize(kb * 1024)
}
break
}
@@ -127,26 +128,10 @@ func (swap *Swap) Gather() {
swap.Size = "0B"
} else {
swap.Open = true
swap.Size = formatSize(totalKB * 1024)
swap.Size = utils.HumanSize(totalKB * 1024)
}
}
func formatSize(bytes uint64) string {
units := []string{"B", "KB", "MB", "GB", "TB", "PB"}
var unitIndex int
size := float64(bytes)
for size >= 1024 && unitIndex < len(units)-1 {
size /= 1024
unitIndex++
}
if unitIndex == 0 {
return strconv.FormatUint(bytes, 10) + units[unitIndex]
}
return strconv.FormatFloat(size, 'f', 1, 64) + units[unitIndex]
}
func (swap *Swap) SaveConfig() {
log.Info("Saving INFO => SWAP !")