55package kernel
66
77import (
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,27 @@ func GetKernelVersion() (*VersionInfo, error) {
2423
2524// getRelease uses `system_profiler SPSoftwareDataType` to get OSX kernel version
2625func getRelease () (string , error ) {
27- cmd := exec .Command ("system_profiler" , "SPSoftwareDataType" )
28- osName , err := cmd .Output ()
26+ cmd := exec .Command ("system_profiler" , "SPSoftwareDataType" , "-json" )
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+ var result struct {
33+ SPSoftwareDataType []struct {
34+ KernelVersion string `json:"kernel_version"`
35+ } `json:"SPSoftwareDataType"`
36+ }
37+ if err := json .Unmarshal (out , & result ); err != nil {
38+ return "" , fmt .Errorf ("parsing system_profiler JSON: %w" , err )
39+ }
40+ if len (result .SPSoftwareDataType ) == 0 || result .SPSoftwareDataType [0 ].KernelVersion == "" {
41+ return "" , fmt .Errorf ("kernel version is invalid" )
5242 }
5343
54- return release , nil
44+ prettyNames := strings .Fields (result .SPSoftwareDataType [0 ].KernelVersion )
45+ if len (prettyNames ) != 2 {
46+ return "" , fmt .Errorf ("kernel version needs to be 'Darwin x.x.x' " )
47+ }
48+ return prettyNames [1 ], nil
5549}
0 commit comments