github.com/getong/docker@v1.13.1/pkg/parsers/kernel/kernel.go (about) 1 // +build !windows 2 3 // Package kernel provides helper function to get, parse and compare kernel 4 // versions for different platforms. 5 package kernel 6 7 import ( 8 "errors" 9 "fmt" 10 ) 11 12 // VersionInfo holds information about the kernel. 13 type VersionInfo struct { 14 Kernel int // Version of the kernel (e.g. 4.1.2-generic -> 4) 15 Major int // Major part of the kernel version (e.g. 4.1.2-generic -> 1) 16 Minor int // Minor part of the kernel version (e.g. 4.1.2-generic -> 2) 17 Flavor string // Flavor of the kernel version (e.g. 4.1.2-generic -> generic) 18 } 19 20 func (k *VersionInfo) String() string { 21 return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, k.Flavor) 22 } 23 24 // CompareKernelVersion compares two kernel.VersionInfo structs. 25 // Returns -1 if a < b, 0 if a == b, 1 it a > b 26 func CompareKernelVersion(a, b VersionInfo) int { 27 if a.Kernel < b.Kernel { 28 return -1 29 } else if a.Kernel > b.Kernel { 30 return 1 31 } 32 33 if a.Major < b.Major { 34 return -1 35 } else if a.Major > b.Major { 36 return 1 37 } 38 39 if a.Minor < b.Minor { 40 return -1 41 } else if a.Minor > b.Minor { 42 return 1 43 } 44 45 return 0 46 } 47 48 // ParseRelease parses a string and creates a VersionInfo based on it. 49 func ParseRelease(release string) (*VersionInfo, error) { 50 var ( 51 kernel, major, minor, parsed int 52 flavor, partial string 53 ) 54 55 // Ignore error from Sscanf to allow an empty flavor. Instead, just 56 // make sure we got all the version numbers. 57 parsed, _ = fmt.Sscanf(release, "%d.%d%s", &kernel, &major, &partial) 58 if parsed < 2 { 59 return nil, errors.New("Can't parse kernel version " + release) 60 } 61 62 // sometimes we have 3.12.25-gentoo, but sometimes we just have 3.12-1-amd64 63 parsed, _ = fmt.Sscanf(partial, ".%d%s", &minor, &flavor) 64 if parsed < 1 { 65 flavor = partial 66 } 67 68 return &VersionInfo{ 69 Kernel: kernel, 70 Major: major, 71 Minor: minor, 72 Flavor: flavor, 73 }, nil 74 }