-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.go
67 lines (60 loc) · 1.44 KB
/
module.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"errors"
"fmt"
"go/build"
"os"
"path/filepath"
"golang.org/x/mod/modfile"
)
type moduleInfo struct {
modulePath string
moduleDir string
}
func findModuleInfo() (moduleInfo, error) {
wd, err := os.Getwd()
if err != nil {
return moduleInfo{}, fmt.Errorf("os.Getwd: %w", err)
}
moduleDir, err := findModuleDir(wd)
if err != nil {
return moduleInfo{}, fmt.Errorf("findModuleDir: %w", err)
}
b, err := os.ReadFile(filepath.Join(moduleDir, "go.mod"))
if err != nil {
return moduleInfo{}, fmt.Errorf("os.ReadFile: %w", err)
}
modulePath := modfile.ModulePath(b)
if moduleDir == "" {
return moduleInfo{}, errors.New("no module path found")
}
return moduleInfo{
modulePath: modulePath,
moduleDir: moduleDir,
}, nil
}
func findModuleDir(dir string) (string, error) {
if dir == "" {
return "", errors.New("dir not set")
}
dir = filepath.Clean(dir)
// look for enclosing go.mod
for {
f := filepath.Join(dir, "go.mod")
if fi, err := os.Stat(f); err == nil && !fi.IsDir() {
return dir, nil
}
d := filepath.Dir(dir)
if d == dir {
break
}
if d == build.Default.GOROOT {
// As a special case, don't cross GOROOT to find a go.work file.
// The standard library and commands built in go always use the vendored
// dependencies, so avoid using a most likely irrelevant go.work file.
return "", errors.New("no go.mod file found")
}
dir = d
}
return "", errors.New("no go.mod file found")
}