github.com/chenfeining/golangci-lint@v1.0.2-0.20230730162517-14c6c67868df/pkg/goutil/env.go (about)

     1  package goutil
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"os"
     8  	"os/exec"
     9  	"strings"
    10  	"time"
    11  
    12  	"github.com/chenfeining/golangci-lint/pkg/logutils"
    13  )
    14  
    15  type EnvKey string
    16  
    17  const (
    18  	EnvGoCache EnvKey = "GOCACHE"
    19  	EnvGoRoot  EnvKey = "GOROOT"
    20  )
    21  
    22  type Env struct {
    23  	vars   map[string]string
    24  	log    logutils.Log
    25  	debugf logutils.DebugFunc
    26  }
    27  
    28  func NewEnv(log logutils.Log) *Env {
    29  	return &Env{
    30  		vars:   map[string]string{},
    31  		log:    log,
    32  		debugf: logutils.Debug(logutils.DebugKeyEnv),
    33  	}
    34  }
    35  
    36  func (e *Env) Discover(ctx context.Context) error {
    37  	startedAt := time.Now()
    38  	args := []string{"env", "-json"}
    39  	args = append(args, string(EnvGoCache), string(EnvGoRoot))
    40  	out, err := exec.CommandContext(ctx, "go", args...).Output()
    41  	if err != nil {
    42  		return fmt.Errorf("failed to run 'go env': %w", err)
    43  	}
    44  
    45  	if err = json.Unmarshal(out, &e.vars); err != nil {
    46  		return fmt.Errorf("failed to parse 'go %s' json: %w", strings.Join(args, " "), err)
    47  	}
    48  
    49  	e.debugf("Read go env for %s: %#v", time.Since(startedAt), e.vars)
    50  	return nil
    51  }
    52  
    53  func (e Env) Get(k EnvKey) string {
    54  	envValue := os.Getenv(string(k))
    55  	if envValue != "" {
    56  		return envValue
    57  	}
    58  
    59  	return e.vars[string(k)]
    60  }