-
Notifications
You must be signed in to change notification settings - Fork 42
/
module.go
87 lines (68 loc) · 1.54 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
75
76
77
78
79
80
81
82
83
84
85
86
87
package mod
import (
"fmt"
"os"
"path/filepath"
"github.com/pkg/errors"
)
var SyslModules = os.Getenv("SYSL_MODULES") != "off"
type Module struct {
Name string
Dir string
Version string
}
type Modules []*Module
var modules Modules
func (m *Modules) Add(v *Module) {
*m = append(*m, v)
}
func (m *Modules) GetByFilename(filename, ver string) *Module {
for _, mod := range *m {
if hasPathPrefix(mod.Name, filename) {
if ver != "" && mod.Version != ver {
continue
}
return mod
}
}
return nil
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func Find(name string, ver string) (*Module, error) {
if !fileExists("go.mod") {
return nil, errors.New("no go.mod file, run `go mod init` first")
}
mod := modules.GetByFilename(name, ver)
if mod != nil {
return mod, nil
}
err := goGetByFilepath(name, ver)
if err != nil {
return nil, fmt.Errorf("%s not found", name)
}
if err = modules.Load(); err != nil {
return nil, fmt.Errorf("error loading modules: %s", err.Error())
}
if modules == nil {
return nil, fmt.Errorf("modules list is empty")
}
mod = modules.GetByFilename(name, ver)
if mod == nil {
return nil, fmt.Errorf("error finding module of file %s", name)
}
return mod, nil
}
func hasPathPrefix(prefix, s string) bool {
prefix = filepath.Clean(prefix)
s = filepath.Clean(s)
if len(s) > len(prefix) {
return s[len(prefix)] == filepath.Separator && s[:len(prefix)] == prefix
}
return s == prefix
}