Refactor: Improve formatting, update struct naming, and optimize JSON parsing.

a
1791
Sam Burba 2 months ago
parent 15c5b67917
commit 9fc28f2f22

@ -8,7 +8,6 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"os/exec"
"strings" "strings"
"unsafe" "unsafe"
@ -91,7 +90,7 @@ func getFsType(stat unix.Statfs_t) string {
return common.ByteToString(stat.Fstypename[:]) return common.ByteToString(stat.Fstypename[:])
} }
type SPNVMeDataTypeItem struct { type spnvmeDataTypeItem struct {
Name string `json:"_name"` Name string `json:"_name"`
BsdName string `json:"bsd_name"` BsdName string `json:"bsd_name"`
DetachableDrive string `json:"detachable_drive"` DetachableDrive string `json:"detachable_drive"`
@ -113,29 +112,27 @@ type SPNVMeDataTypeItem struct {
} `json:"volumes"` } `json:"volumes"`
} }
func SerialNumberWithContext(ctx context.Context, name string) (string, error) { type spnvmeDataWrapper struct {
cmd := exec.Command("system_profiler", "SPNVMeDataType", "-json") SPNVMeDataType []struct {
Items []spnvmeDataTypeItem `json:"_items"`
} `json:"SPNVMeDataType"`
}
output, err := cmd.Output() func SerialNumberWithContext(ctx context.Context, name string) (string, error) {
output, err := invoke.CommandWithContext(ctx, "system_profiler", "SPNVMeDataType", "-json")
if err != nil { if err != nil {
return "", err return "", err
} }
var temp struct { var data spnvmeDataWrapper
SPNVMeDataType []struct { if err := json.Unmarshal(output, &data); err != nil {
Items []SPNVMeDataTypeItem `json:"_items"`
} `json:"SPNVMeDataType"`
}
err = json.Unmarshal(output, &temp)
if err != nil {
return "", fmt.Errorf("failed to unmarshal JSON: %w", err) return "", fmt.Errorf("failed to unmarshal JSON: %w", err)
} }
// Extract all serial numbers into a single string // Extract all serial numbers into a single string
var serialNumbers []string var serialNumbers []string
for _, data := range temp.SPNVMeDataType { for _, spnvmeData := range data.SPNVMeDataType {
for _, item := range data.Items { for _, item := range spnvmeData.Items {
serialNumbers = append(serialNumbers, item.DeviceSerial) serialNumbers = append(serialNumbers, item.DeviceSerial)
} }
} }

Loading…
Cancel
Save