github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/pkg/parsers/kernel/kernel_darwin.go (about)

     1  // +build darwin
     2  
     3  // Package kernel provides helper function to get, parse and compare kernel
     4  // versions for different platforms.
     5  package kernel // import "github.com/demonoid81/moby/pkg/parsers/kernel"
     6  
     7  import (
     8  	"fmt"
     9  	"os/exec"
    10  	"strings"
    11  
    12  	shellwords "github.com/mattn/go-shellwords"
    13  )
    14  
    15  // GetKernelVersion gets the current kernel version.
    16  func GetKernelVersion() (*VersionInfo, error) {
    17  	release, err := getRelease()
    18  	if err != nil {
    19  		return nil, err
    20  	}
    21  
    22  	return ParseRelease(release)
    23  }
    24  
    25  // getRelease uses `system_profiler SPSoftwareDataType` to get OSX kernel version
    26  func getRelease() (string, error) {
    27  	cmd := exec.Command("system_profiler", "SPSoftwareDataType")
    28  	osName, err := cmd.Output()
    29  	if err != nil {
    30  		return "", err
    31  	}
    32  
    33  	var release string
    34  	data := strings.Split(string(osName), "\n")
    35  	for _, line := range data {
    36  		if strings.Contains(line, "Kernel Version") {
    37  			// It has the format like '      Kernel Version: Darwin 14.5.0'
    38  			content := strings.SplitN(line, ":", 2)
    39  			if len(content) != 2 {
    40  				return "", fmt.Errorf("Kernel Version is invalid")
    41  			}
    42  
    43  			prettyNames, err := shellwords.Parse(content[1])
    44  			if err != nil {
    45  				return "", fmt.Errorf("Kernel Version is invalid: %s", err.Error())
    46  			}
    47  
    48  			if len(prettyNames) != 2 {
    49  				return "", fmt.Errorf("Kernel Version needs to be 'Darwin x.x.x' ")
    50  			}
    51  			release = prettyNames[1]
    52  		}
    53  	}
    54  
    55  	return release, nil
    56  }