Skip to content

Commit 9bdc786

Browse files
committed
storage: use -json parameter for system_profiler SPSoftwareDataType
Removes go-shellwords dependency from kernel_darwin.go Fixes: #983 Signed-off-by: Maria Glushenok <glushenokm@gmail.com>
1 parent 629dae5 commit 9bdc786

1 file changed

Lines changed: 20 additions & 24 deletions

File tree

storage/pkg/parsers/kernel/kernel_darwin.go

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,10 @@
55
package kernel
66

77
import (
8+
"encoding/json"
89
"fmt"
910
"os/exec"
1011
"strings"
11-
12-
"github.com/mattn/go-shellwords"
1312
)
1413

1514
// GetKernelVersion gets the current kernel version.
@@ -24,32 +23,29 @@ func GetKernelVersion() (*VersionInfo, error) {
2423

2524
// getRelease uses `system_profiler SPSoftwareDataType` to get OSX kernel version
2625
func getRelease() (string, error) {
27-
cmd := exec.Command("system_profiler", "SPSoftwareDataType")
28-
osName, err := cmd.Output()
26+
cmd := exec.Command("system_profiler", "-json", "SPSoftwareDataType")
27+
out, err := cmd.Output()
2928
if err != nil {
3029
return "", err
3130
}
3231

33-
var release string
34-
for line := range strings.SplitSeq(string(osName), "\n") {
35-
if strings.Contains(line, "Kernel Version") {
36-
// It has the format like ' Kernel Version: Darwin 14.5.0'
37-
_, val, ok := strings.Cut(line, ":")
38-
if !ok {
39-
return "", fmt.Errorf("kernel version is invalid")
40-
}
41-
42-
prettyNames, err := shellwords.Parse(val)
43-
if err != nil {
44-
return "", fmt.Errorf("kernel version is invalid: %w", err)
45-
}
46-
47-
if len(prettyNames) != 2 {
48-
return "", fmt.Errorf("kernel version needs to be 'Darwin x.x.x' ")
49-
}
50-
release = prettyNames[1]
51-
}
32+
// system_profiler returns other fields in addition to kernel_version.
33+
// Do not decode with RejectUnknownMembers.
34+
var result struct {
35+
SPSoftwareDataType []struct {
36+
KernelVersion string `json:"kernel_version"`
37+
} `json:"SPSoftwareDataType"`
38+
}
39+
if err := json.Unmarshal(out, &result); err != nil {
40+
return "", fmt.Errorf("parsing system_profiler JSON: %w", err)
41+
}
42+
if len(result.SPSoftwareDataType) == 0 || result.SPSoftwareDataType[0].KernelVersion == "" {
43+
return "", fmt.Errorf("kernel version is invalid")
5244
}
5345

54-
return release, nil
46+
prettyNames := strings.Fields(result.SPSoftwareDataType[0].KernelVersion)
47+
if len(prettyNames) != 2 {
48+
return "", fmt.Errorf("kernel version needs to be 'Darwin x.x.x' ")
49+
}
50+
return prettyNames[1], nil
5551
}

0 commit comments

Comments
 (0)