-
Notifications
You must be signed in to change notification settings - Fork 5
/
module.go
74 lines (68 loc) · 1.53 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
68
69
70
71
72
73
74
package gen
import (
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"github.com/ydnar/wasm-tools-go/internal/relpath"
"golang.org/x/mod/modfile"
)
// PackagePath returns the Go module path and optional package directory path(s)
// for the given directory path dir. Returns an error if dir or its parent directories
// do not contain a go.mod file.
func PackagePath(dir string) (string, error) {
dir, err := relpath.Abs(dir)
if err != nil {
return "", err
}
info, err := os.Stat(dir)
if err != nil {
return "", err
}
if !info.IsDir() {
return "", fmt.Errorf("not a directory: %s", dir)
}
var file string
var subdirs string
for {
// Find a go.mod file in dir
file = filepath.Join(dir, "go.mod")
info, err := os.Stat(file)
if err != nil {
if dir == "/" {
return "", errors.New("unable to locate a go.mod file")
}
// Pop up to parent dir
var rest string
dir, rest = filepath.Split(dir)
if dir == "" {
return "", errors.New("unable to locate a go.mod file")
}
dir = filepath.Clean(dir)
subdirs = path.Join(rest, subdirs)
continue
}
if info.IsDir() {
return "", fmt.Errorf("unexpected directory: %s", file)
}
break
}
// Read the go.mod file
f, err := os.Open(file)
if err != nil {
return "", fmt.Errorf("unable to open %s", file)
}
mod, err := io.ReadAll(f)
f.Close()
if err != nil {
return "", err
}
// Parse it
modpath := modfile.ModulePath(mod)
if modpath == "" {
return "", fmt.Errorf("no module path in %s", file)
}
return path.Join(modpath, subdirs), nil
}