|
| 1 | +// Package gomod A function to get information about module (go list). |
| 2 | +package gomod |
| 3 | + |
| 4 | +import ( |
| 5 | + "bytes" |
| 6 | + "encoding/json" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "os/exec" |
| 10 | +) |
| 11 | + |
| 12 | +// ModInfo Module information. |
| 13 | +// |
| 14 | +//nolint:tagliatelle // temporary: the next version of golangci-lint will allow configuration by package. |
| 15 | +type ModInfo struct { |
| 16 | + Path string `json:"Path"` |
| 17 | + Dir string `json:"Dir"` |
| 18 | + GoMod string `json:"GoMod"` |
| 19 | + GoVersion string `json:"GoVersion"` |
| 20 | + Main bool `json:"Main"` |
| 21 | +} |
| 22 | + |
| 23 | +// GetModuleInfo gets modules information from `go list`. |
| 24 | +func GetModuleInfo() ([]ModInfo, error) { |
| 25 | + // https://github.com/golang/go/issues/44753#issuecomment-790089020 |
| 26 | + cmd := exec.Command("go", "list", "-m", "-json") |
| 27 | + |
| 28 | + out, err := cmd.Output() |
| 29 | + if err != nil { |
| 30 | + return nil, fmt.Errorf("command go list: %w: %s", err, string(out)) |
| 31 | + } |
| 32 | + |
| 33 | + var infos []ModInfo |
| 34 | + |
| 35 | + for dec := json.NewDecoder(bytes.NewBuffer(out)); dec.More(); { |
| 36 | + var v ModInfo |
| 37 | + if err := dec.Decode(&v); err != nil { |
| 38 | + return nil, fmt.Errorf("unmarshaling error: %w: %s", err, string(out)) |
| 39 | + } |
| 40 | + |
| 41 | + if v.GoMod == "" { |
| 42 | + return nil, errors.New("working directory is not part of a module") |
| 43 | + } |
| 44 | + |
| 45 | + if !v.Main || v.Dir == "" { |
| 46 | + continue |
| 47 | + } |
| 48 | + |
| 49 | + infos = append(infos, v) |
| 50 | + } |
| 51 | + |
| 52 | + if len(infos) == 0 { |
| 53 | + return nil, errors.New("go.mod file not found") |
| 54 | + } |
| 55 | + |
| 56 | + return infos, nil |
| 57 | +} |
0 commit comments