Skip to content

Commit

Permalink
use a less brittle go command to determine GOMOD location
Browse files Browse the repository at this point in the history
  • Loading branch information
ryancurrah committed Apr 10, 2020
1 parent e8acbed commit 04bf607
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions gomodguard.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gomodguard

import (
"bytes"
"encoding/json"
"fmt"
"go/parser"
"go/token"
Expand Down Expand Up @@ -348,21 +349,30 @@ func (p *Processor) isBlockedPackageFromModFile(pkg string) bool {
}

func loadGoModFile() ([]byte, error) {
cmd := exec.Command("go", "list", "-m", "-f", "{{.GoMod}}")
cmd := exec.Command("go", "env", "-json")
stdout, _ := cmd.StdoutPipe()
_ = cmd.Start()

goModFileLocation := ""
if stdout == nil {
return ioutil.ReadFile(goModFilename)
}

buf := new(bytes.Buffer)
_, _ = buf.ReadFrom(stdout)

goEnv := make(map[string]string)
err := json.Unmarshal(buf.Bytes(), &goEnv)
if err != nil {
return ioutil.ReadFile(goModFilename)
}

if stdout != nil {
buf := new(bytes.Buffer)
_, _ = buf.ReadFrom(stdout)
goModFileLocation = strings.TrimSpace(buf.String())
if _, ok := goEnv["GOMOD"]; !ok {
return ioutil.ReadFile(goModFilename)
}

if _, err := os.Stat(goModFileLocation); os.IsNotExist(err) {
if _, err := os.Stat(goEnv["GOMOD"]); os.IsNotExist(err) {
return ioutil.ReadFile(goModFilename)
}

return ioutil.ReadFile(goModFileLocation)
return ioutil.ReadFile(goEnv["GOMOD"])
}

0 comments on commit 04bf607

Please sign in to comment.