gopkg.in/ubuntu-core/snappy.v0@v0.0.0-20210902073436-25a8614f10a6/osutil/uname.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2014-2018 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 package osutil 21 22 var KernelVersion = kernelVersion 23 24 // We have to implement separate functions for the kernel version and the 25 // machine name at the moment as the utsname struct is either using int8 26 // or uint8 depending on the architecture the code is built for. As there 27 // is no easy way to generalise this implements the same code twice (other 28 // than going via unsafe.Pointer, or interfaces, which are overkill). The 29 // way to get this solved is by using []byte inside the utsname struct 30 // instead of []int8/[]uint8. See https://github.com/golang/go/issues/20753 31 // for details. 32 33 func kernelVersion() string { 34 u, err := uname() 35 if err != nil { 36 return "unknown" 37 } 38 39 // Release is more informative than Version. 40 buf := make([]byte, len(u.Release)) 41 for i, c := range u.Release { 42 if c == 0 { 43 buf = buf[:i] 44 break 45 } 46 // c can be uint8 or int8 depending on arch (see comment above) 47 buf[i] = byte(c) 48 } 49 50 return string(buf) 51 } 52 53 func MachineName() string { 54 u, err := uname() 55 if err != nil { 56 return "unknown" 57 } 58 59 buf := make([]byte, len(u.Machine)) 60 for i, c := range u.Machine { 61 if c == 0 { 62 buf = buf[:i] 63 break 64 } 65 // c can be uint8 or int8 depending on arch (see comment above) 66 buf[i] = byte(c) 67 } 68 69 return string(buf) 70 } 71 72 // MockKernelVersion replaces the function that returns the kernel version string. 73 func MockKernelVersion(version string) (restore func()) { 74 old := KernelVersion 75 KernelVersion = func() string { return version } 76 return func() { 77 KernelVersion = old 78 } 79 }