forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sysgo.go
76 lines (64 loc) · 1.53 KB
/
sysgo.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
71
72
73
74
75
76
package sysutil
import (
"errors"
"regexp"
"runtime"
"strings"
)
// GoVersion get go runtime version. eg: "1.18.2"
func GoVersion() string {
return runtime.Version()[2:]
}
// GoInfo define
//
// On os by:
//
// go env GOVERSION GOOS GOARCH
// go version // "go version go1.19 darwin/amd64"
type GoInfo struct {
Version string
GoOS string
Arch string
}
// match "go version go1.19 darwin/amd64"
var goVerRegex = regexp.MustCompile(`\sgo([\d.]+)\s(\w+)/(\w+)`)
// ParseGoVersion get info by parse `go version` results.
//
// Examples:
//
// line, err := sysutil.ExecLine("go version")
// if err != nil {
// return err
// }
//
// info, err := sysutil.ParseGoVersion()
// dump.P(info)
func ParseGoVersion(line string) (*GoInfo, error) {
// eg: [" go1.19 darwin/amd64", "1.19", "darwin", "amd64"]
lines := goVerRegex.FindStringSubmatch(line)
if len(lines) != 4 {
return nil, errors.New("returns go info is not full")
}
info := &GoInfo{}
info.Version = strings.TrimPrefix(lines[1], "go")
info.GoOS = lines[2]
info.Arch = lines[3]
return info, nil
}
// OsGoInfo fetch and parse
func OsGoInfo() (*GoInfo, error) {
cmdArgs := []string{"env", "GOVERSION", "GOOS", "GOARCH"}
line, err := ExecCmd("go", cmdArgs)
if err != nil {
return nil, err
}
lines := strings.Split(strings.TrimSpace(line), "\n")
if len(lines) != len(cmdArgs)-1 {
return nil, errors.New("returns go info is not full")
}
info := &GoInfo{}
info.Version = strings.TrimPrefix(lines[0], "go")
info.GoOS = lines[1]
info.Arch = lines[2]
return info, nil
}