-
Notifications
You must be signed in to change notification settings - Fork 17
/
os_linux.go
70 lines (64 loc) · 1.57 KB
/
os_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
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package os
import (
"errors"
"io/ioutil"
"strings"
"sync"
)
var (
// osReleaseFile is the name of the file that is read in order to determine
// the linux type release version.
osReleaseFile = "/etc/os-release"
osOnce sync.Once
os OSType // filled in by the first call to hostOS
)
func hostOS() OSType {
osOnce.Do(func() {
var err error
os, err = updateOS(osReleaseFile)
if err != nil {
panic("unable to read " + osReleaseFile + ": " + err.Error())
}
})
return os
}
func updateOS(f string) (OSType, error) {
values, err := ReadOSRelease(f)
if err != nil {
return Unknown, err
}
switch values["ID"] {
case strings.ToLower(Ubuntu.String()):
return Ubuntu, nil
case strings.ToLower(CentOS.String()):
return CentOS, nil
case strings.ToLower(OpenSUSE.String()):
return OpenSUSE, nil
default:
return GenericLinux, nil
}
}
// ReadOSRelease parses the information in the os-release file.
//
// See http://www.freedesktop.org/software/systemd/man/os-release.html.
func ReadOSRelease(f string) (map[string]string, error) {
contents, err := ioutil.ReadFile(f)
if err != nil {
return nil, err
}
values := make(map[string]string)
releaseDetails := strings.Split(string(contents), "\n")
for _, val := range releaseDetails {
c := strings.SplitN(val, "=", 2)
if len(c) != 2 {
continue
}
values[c[0]] = strings.Trim(c[1], "\t '\"")
}
if _, ok := values["ID"]; !ok {
return nil, errors.New("OS release file is missing ID")
}
return values, nil
}