Skip to content

Commit 0ce241e

Browse files
committed
feat: add gomod package
1 parent 07729c4 commit 0ce241e

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

gomod/gomod.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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

Comments
 (0)