-
Notifications
You must be signed in to change notification settings - Fork 8
/
module.go
61 lines (57 loc) · 1.12 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
package module
import (
"bufio"
"errors"
"io"
"os"
"path/filepath"
"strings"
)
// ParseGoModuleName parse go.mod file and return module name
func ParseGoModuleName(f io.Reader) (string, error) {
var module string
reader := bufio.NewReader(f)
for {
line, _, err := reader.ReadLine()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return "", err
}
data := strings.TrimSpace(string(line))
if strings.HasPrefix(data, "module") {
module = strings.TrimSpace(strings.TrimPrefix(data, "module"))
break
}
}
if module == "" {
return "", errors.New("can not find module name")
}
return module, nil
}
// FindGoModPath go.mod file and return path of go.mod
func FindGoModPath(path string) (string, error) {
var goModPath = path
for {
ok, err := fileExists(filepath.Join(goModPath, "go.mod"))
if err != nil {
return "", err
}
if ok {
break
}
goModPath = filepath.Dir(goModPath)
}
return goModPath, nil
}
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}