-
Notifications
You must be signed in to change notification settings - Fork 3
/
mod.go
125 lines (101 loc) · 2.38 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package mod
import (
"context"
"os"
"path/filepath"
"golang.org/x/mod/semver"
"github.com/octohelm/cuemod/pkg/cuemod/modfile"
"github.com/pkg/errors"
)
type Mod struct {
modfile.ModFile
modfile.ModVersion
// Repo where module in vcs root
Repo string
// SubPath mod local sub path
SubPath string
// Dir module absolute dir
Dir string
// Root means this import path is mod root
Root bool
// Sum repo absolute dir sum
Sum string
}
func (m *Mod) ModuleRoot() string {
if m.SubPath != "" {
return filepath.Join(m.Module, m.SubPath)
}
return m.Module
}
func (m *Mod) String() string {
if m.Version == "" {
return m.Module + "@v0.0.0"
}
return m.Module + "@" + m.Version
}
func (m *Mod) LoadInfo(ctx context.Context) (bool, error) {
if m.Dir == "" || m.Dir[0] != '/' {
return false, nil
}
if _, err := os.Stat(m.Dir); os.IsNotExist(err) {
return false, errors.Wrapf(err, "%s not found", m.Dir)
}
exists, err := modfile.LoadModFile(m.Dir, &m.ModFile)
if err != nil {
return false, err
}
if exists {
// module name should be from module.cue
m.Module = m.ModFile.Module
m.Root = true
}
return exists, nil
}
func (m *Mod) Resolved() bool {
return m.Dir != ""
}
func (m *Mod) SetRequire(module string, modVersion modfile.ModVersion, indirect bool) {
if module == m.Module {
return
}
if m.Require == nil {
m.Require = map[string]modfile.Requirement{}
}
r := modfile.Requirement{}
r.ModVersion = modVersion
r.Indirect = indirect
if currentRequire, ok := m.Require[module]; ok {
// always using greater one
if versionGreaterThan(currentRequire.Version, r.Version) {
r.ModVersion = currentRequire.ModVersion
}
if r.Indirect {
r.Indirect = currentRequire.Indirect
}
}
m.Require[module] = r
if currentReplace, ok := m.Replace[modfile.VersionedPathIdentity{Path: module}]; ok {
if currentReplace.IsLocalReplace() || currentReplace.Import != "" {
return
}
currentReplace.Version = r.ModVersion.Version
m.Replace[modfile.VersionedPathIdentity{Path: module}] = currentReplace
}
}
func (m *Mod) FixVersion(repo string, version string) string {
if m.Require != nil {
if r, ok := m.Require[repo]; ok {
if r.VcsRef != "" && r.Version == "v0.0.0" {
return r.VcsRef
}
return r.Version
}
}
return version
}
func versionGreaterThan(v string, w string) bool {
if w == "" {
return false
}
return semver.Compare(v, w) > 0
}