forked from getlantern/osversion
/
osversion_linux.go
57 lines (49 loc) · 1.2 KB
/
osversion_linux.go
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
57
// +build !android
package osversion
import (
"C"
"errors"
"fmt"
"io/ioutil"
"regexp"
"syscall"
)
func GetString() (string, error) {
var uts syscall.Utsname
err := syscall.Uname(&uts)
if err != nil {
return "", errors.New(fmt.Sprintf("Error calling system function 'uname': %s", err))
}
return fmt.Sprintf("%s", int8SliceToString(uts.Release[:])), nil
}
func GetHumanReadable() (string, error) {
// Kernel version
kernel, err := GetString()
if err != nil {
return "", err
}
// Try to get the distribution info
fData, err := ioutil.ReadFile("/etc/os-release")
if err != nil {
return fmt.Sprintf("kernel: %s", kernel), nil
}
// At least Fedora, Debian, Ubuntu and Arch support this approach
// and provide the PRETTY_NAME field
reg1 := regexp.MustCompile("PRETTY_NAME=\".+\"")
reg2 := regexp.MustCompile("\".+\"")
dstrBytes := reg2.Find(reg1.Find(fData))
distribution := string(dstrBytes[1 : len(dstrBytes)-1])
return fmt.Sprintf("%s kernel: %s", distribution, kernel), nil
}
func int8SliceToString(ca []int8) string {
s := make([]byte, len(ca))
strpos := 0
for strpos < len(ca) {
if ca[strpos] == 0 {
break
}
s[strpos] = uint8(ca[strpos])
strpos++
}
return string(s[:strpos])
}