Skip to content

Commit ebe612e

Browse files
committed
feat(gomod): add GetGoModPath and GetModulePath
1 parent 0ce241e commit ebe612e

File tree

2 files changed

+80
-1
lines changed

2 files changed

+80
-1
lines changed

gomod/gomod.go

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@ import (
66
"encoding/json"
77
"errors"
88
"fmt"
9+
"os"
910
"os/exec"
11+
"path/filepath"
12+
"strings"
13+
14+
"golang.org/x/mod/modfile"
1015
)
1116

1217
// ModInfo Module information.
@@ -27,7 +32,7 @@ func GetModuleInfo() ([]ModInfo, error) {
2732

2833
out, err := cmd.Output()
2934
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))
3136
}
3237

3338
var infos []ModInfo
@@ -55,3 +60,40 @@ func GetModuleInfo() ([]ModInfo, error) {
5560

5661
return infos, nil
5762
}
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+
}

gomod/gomod_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package gomod
2+
3+
import (
4+
"path/filepath"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
"github.com/stretchr/testify/require"
9+
)
10+
11+
func TestGetModuleInfo(t *testing.T) {
12+
info, err := GetModuleInfo()
13+
require.NoError(t, err)
14+
15+
require.Len(t, info, 1)
16+
17+
assert.Equal(t, "github.com/ldez/grignotin", info[0].Path)
18+
assert.Equal(t, "1.22.0", info[0].GoVersion)
19+
assert.True(t, info[0].Main)
20+
}
21+
22+
func TestGetGoModPath(t *testing.T) {
23+
p, err := GetGoModPath()
24+
require.NoError(t, err)
25+
26+
abs, err := filepath.Abs("..")
27+
require.NoError(t, err)
28+
29+
assert.Equal(t, filepath.Join(abs, "go.mod"), p)
30+
}
31+
32+
func TestGetModulePath(t *testing.T) {
33+
p, err := GetModulePath()
34+
require.NoError(t, err)
35+
36+
assert.Equal(t, "github.com/ldez/grignotin", p)
37+
}

0 commit comments

Comments
 (0)