-
Notifications
You must be signed in to change notification settings - Fork 11
/
mod.go
75 lines (62 loc) · 1.45 KB
/
mod.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
75
package main
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"path"
"strings"
"github.com/msoap/byline"
)
var goModFilename *string
func getGoModFilename() string {
if goModFilename != nil {
return *goModFilename
}
file := ""
out, err := exec.Command("go", "env", "GOMOD").Output()
if err != nil {
log.Printf("failed to load 'go env GOMOD' content: %s", err)
goModFilename = &file
return ""
}
file = strings.TrimSpace(string(out))
goModFilename = &file
return file
}
func guessAbsPathInGoMod(relPath string) (string, error) {
modFilename := getGoModFilename()
if modFilename == "" {
return "", errIsNotInGoMod
}
modFile, err := os.Open(modFilename)
if err != nil {
return "", err
}
defer func() {
if err := modFile.Close(); err != nil {
log.Printf("failed to close %s file: %s", modFilename, err)
}
}()
moduleName := ""
if err := byline.NewReader(modFile).AWKMode(func(_ string, fields []string, vars byline.AWKVars) (string, error) {
if vars.NF == 2 && fields[0] == "module" && fields[1] != "" {
moduleName = fields[1]
return "", io.EOF
}
return "", nil
}).Discard(); err != nil {
return "", err
}
if moduleName == "" {
return "", errIsNotInGoMod
}
absPath := path.Dir(modFilename) + strings.TrimPrefix(relPath, moduleName)
if stat, err := os.Stat(absPath); err != nil {
return "", err
} else if !stat.Mode().IsRegular() {
return "", fmt.Errorf("%s is not regular file", absPath)
}
return absPath, nil
}