/
module.go
71 lines (67 loc) · 1.88 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
package helper
import (
"errors"
"fmt"
"go/build"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"strings"
)
// ResolveGoImportPath resolves directry path to go import statement path.
func ResolveGoImportPath(dir string) (string, error) {
absPath, err := filepath.Abs(dir)
if err != nil {
return "", err
}
absModuleRootPath, moduleName, err := findGoModInfo(absPath)
if err != nil {
if err != ErrGoModNotFound {
return "", err
}
// go.mod not found
absGoPath, err := filepath.Abs(build.Default.GOPATH)
if err != nil {
return "", err
}
absGoPath = filepath.Join(absGoPath, "src")
if !strings.HasPrefix(absPath, absGoPath) {
return "", fmt.Errorf("not in $GOPATH/src (%s)", absGoPath)
}
offset := len(absGoPath) + 1
return absPath[offset:], nil
}
// absPath is ${absModuleRootPath}/my/package/path/dir
// and the import path should be ${moduleName}/my/package/path/dir
return path.Join(moduleName, strings.TrimPrefix(absPath, absModuleRootPath)), nil
}
var (
moduleDefRe = regexp.MustCompile("module\\s+(\\S+)\n")
ErrGoModNotFound = errors.New("go.mod file is not found in the directory and it's parents")
)
// findGoModInfo finds go.mod file under the directory (or parent directories)
// and resturns the directory path where go.mod exists and module string declared in go.mod file.
func findGoModInfo(dir string) (string, string, error) {
gomod := filepath.Join(dir, "go.mod")
_, err := os.Stat(gomod)
if err != nil {
if os.IsNotExist(err) {
if dir == "/" {
return "", "", ErrGoModNotFound
}
return findGoModInfo(filepath.Join(dir, "..") + "/")
}
return "", "", err
}
contents, err := ioutil.ReadFile(gomod)
if err != nil {
return "", "", err
}
found := moduleDefRe.Copy().FindSubmatch(contents)
if len(found) == 0 {
return "", "", fmt.Errorf("could not find module declaration in %s", gomod)
}
return dir, string(found[1]), nil
}