File: kernel_darwin.go

package info (click to toggle)
golang-github-containers-storage 1.59.1%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 4,184 kB
  • sloc: sh: 630; ansic: 389; makefile: 143; awk: 12
file content (56 lines) | stat: -rw-r--r-- 1,296 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//go:build darwin

// Package kernel provides helper function to get, parse and compare kernel
// versions for different platforms.
package kernel

import (
	"fmt"
	"os/exec"
	"strings"

	"github.com/mattn/go-shellwords"
)

// GetKernelVersion gets the current kernel version.
func GetKernelVersion() (*VersionInfo, error) {
	release, err := getRelease()
	if err != nil {
		return nil, err
	}

	return ParseRelease(release)
}

// getRelease uses `system_profiler SPSoftwareDataType` to get OSX kernel version
func getRelease() (string, error) {
	cmd := exec.Command("system_profiler", "SPSoftwareDataType")
	osName, err := cmd.Output()
	if err != nil {
		return "", err
	}

	var release string
	data := strings.Split(string(osName), "\n")
	for _, line := range data {
		if strings.Contains(line, "Kernel Version") {
			// It has the format like '      Kernel Version: Darwin 14.5.0'
			_, val, ok := strings.Cut(line, ":")
			if !ok {
				return "", fmt.Errorf("kernel version is invalid")
			}

			prettyNames, err := shellwords.Parse(val)
			if err != nil {
				return "", fmt.Errorf("kernel version is invalid: %w", err)
			}

			if len(prettyNames) != 2 {
				return "", fmt.Errorf("kernel version needs to be 'Darwin x.x.x' ")
			}
			release = prettyNames[1]
		}
	}

	return release, nil
}