@@ -6,7 +6,12 @@ import (
6
6
"encoding/json"
7
7
"errors"
8
8
"fmt"
9
+ "os"
9
10
"os/exec"
11
+ "path/filepath"
12
+ "strings"
13
+
14
+ "golang.org/x/mod/modfile"
10
15
)
11
16
12
17
// ModInfo Module information.
@@ -27,7 +32,7 @@ func GetModuleInfo() ([]ModInfo, error) {
27
32
28
33
out , err := cmd .Output ()
29
34
if err != nil {
30
- return nil , fmt .Errorf ("command go list : %w: %s" , err , string (out ))
35
+ return nil , fmt .Errorf ("command %q : %w: %s" , strings . Join ( cmd . Args , " " ) , err , string (out ))
31
36
}
32
37
33
38
var infos []ModInfo
@@ -55,3 +60,40 @@ func GetModuleInfo() ([]ModInfo, error) {
55
60
56
61
return infos , nil
57
62
}
63
+
64
+ type goEnv struct {
65
+ GOMOD string `json:"GOMOD"` //nolint:tagliatelle // Based on en var name.
66
+ }
67
+
68
+ // GetGoModPath extracts go.mod path from "go env".
69
+ func GetGoModPath () (string , error ) {
70
+ cmd := exec .Command ("go" , "env" , "-json" , "GOMOD" )
71
+
72
+ out , err := cmd .Output ()
73
+ if err != nil {
74
+ return "" , fmt .Errorf ("command %q: %w: %s" , strings .Join (cmd .Args , " " ), err , string (out ))
75
+ }
76
+
77
+ v := & goEnv {}
78
+ err = json .NewDecoder (bytes .NewBuffer (out )).Decode (v )
79
+ if err != nil {
80
+ return "" , err
81
+ }
82
+
83
+ return v .GOMOD , nil
84
+ }
85
+
86
+ // GetModulePath extracts module path from go.mod.
87
+ func GetModulePath () (string , error ) {
88
+ p , err := GetGoModPath ()
89
+ if err != nil {
90
+ return "" , err
91
+ }
92
+
93
+ b , err := os .ReadFile (filepath .Clean (p ))
94
+ if err != nil {
95
+ return "" , fmt .Errorf ("reading go.mod: %w" , err )
96
+ }
97
+
98
+ return modfile .ModulePath (b ), nil
99
+ }
0 commit comments