Skip to content

Commit 56eb77a

Browse files
add Infer function
1 parent b44de7c commit 56eb77a

3 files changed

Lines changed: 29 additions & 9 deletions

File tree

mod.go

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ var ErrFileNotFound = fmt.Errorf(`mod: unable to find "go.mod": %w`, fs.ErrNotEx
1717

1818
// New module
1919
func New(dir string) *Module {
20-
modulePath := modulePathFromGoPath(dir)
20+
modulePath := Infer(dir)
2121
if modulePath == "" {
2222
modulePath = "change.me"
2323
}
@@ -128,13 +128,17 @@ func Abs(dir string) (absDir string, err error) {
128128
return filepath.Dir(absPath), nil
129129
}
130130

131-
// modulePathFromGoPath tries inferring the module path of directory. This only
132-
// works if you're in working within the $GOPATH
133-
func modulePathFromGoPath(path string) string {
134-
src := filepath.Join(build.Default.GOPATH, "src") + "/"
135-
if !strings.HasPrefix(path, src) {
131+
// GOPATH is the default GOPATH for the current build environment. This is
132+
// exposed for testing purposes, but should not be changed in production code.
133+
var GOPATH = build.Default.GOPATH
134+
135+
// Infer the module path from the $GOPATH. This only works if you work inside
136+
// $GOPATH otherwise returns an empty string.
137+
func Infer(dir string) string {
138+
src := filepath.Join(GOPATH, "src") + "/"
139+
if !strings.HasPrefix(dir, src) {
136140
return ""
137141
}
138-
modulePath := strings.TrimPrefix(path, src)
142+
modulePath := strings.TrimPrefix(dir, src)
139143
return modulePath
140144
}

mod_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package mod_test
22

33
import (
44
"os"
5+
"path/filepath"
56
"testing"
67

78
"github.com/livebud/mod"
@@ -34,3 +35,19 @@ func TestNew(t *testing.T) {
3435
is.Equal(dir, module.Dir())
3536
is.Equal(module.Import(), "change.me")
3637
}
38+
39+
func TestInferOutsideGoPath(t *testing.T) {
40+
dir := t.TempDir()
41+
is := is.New(t)
42+
is.Equal(mod.Infer(dir), "")
43+
}
44+
45+
func TestInferInsideGoPath(t *testing.T) {
46+
gopath := mod.GOPATH
47+
mod.GOPATH = t.TempDir()
48+
t.Cleanup(func() {
49+
mod.GOPATH = gopath
50+
})
51+
is := is.New(t)
52+
is.Equal(mod.Infer(filepath.Join(mod.GOPATH, "src", "app.com")), "app.com")
53+
}

modcache.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package mod
22

33
import (
44
"fmt"
5-
"go/build"
65
"os"
76
"path/filepath"
87

@@ -23,7 +22,7 @@ func getModCacheDir() string {
2322
modCacheDir = env
2423
return env
2524
}
26-
modCacheDir = filepath.Join(build.Default.GOPATH, "pkg", "mod")
25+
modCacheDir = filepath.Join(GOPATH, "pkg", "mod")
2726
return modCacheDir
2827
}
2928

0 commit comments

Comments
 (0)