forked from golangci/golangci-lint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.go
61 lines (49 loc) · 1.14 KB
/
env.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
package goutil
import (
"context"
"encoding/json"
"os"
"os/exec"
"strings"
"time"
"github.com/pkg/errors"
"github.com/golangci/golangci-lint/pkg/logutils"
)
type EnvKey string
const (
EnvGoCache EnvKey = "GOCACHE"
EnvGoRoot EnvKey = "GOROOT"
)
type Env struct {
vars map[string]string
log logutils.Log
debugf logutils.DebugFunc
}
func NewEnv(log logutils.Log) *Env {
return &Env{
vars: map[string]string{},
log: log,
debugf: logutils.Debug("env"),
}
}
func (e *Env) Discover(ctx context.Context) error {
startedAt := time.Now()
args := []string{"env", "-json"}
args = append(args, string(EnvGoCache), string(EnvGoRoot))
out, err := exec.CommandContext(ctx, "go", args...).Output()
if err != nil {
return errors.Wrap(err, "failed to run 'go env'")
}
if err = json.Unmarshal(out, &e.vars); err != nil {
return errors.Wrapf(err, "failed to parse 'go %s' json", strings.Join(args, " "))
}
e.debugf("Read go env for %s: %#v", time.Since(startedAt), e.vars)
return nil
}
func (e Env) Get(k EnvKey) string {
envValue := os.Getenv(string(k))
if envValue != "" {
return envValue
}
return e.vars[string(k)]
}