github.com/octohelm/cuemod@v0.9.4/pkg/cuemod/mod/mod.go (about) 1 package mod 2 3 import ( 4 "context" 5 "os" 6 "path/filepath" 7 8 "golang.org/x/mod/semver" 9 10 "github.com/octohelm/cuemod/pkg/cuemod/modfile" 11 "github.com/pkg/errors" 12 ) 13 14 type Mod struct { 15 modfile.ModFile 16 modfile.ModVersion 17 18 // Repo where module in vcs root 19 Repo string 20 // SubPath mod local sub path 21 SubPath string 22 // Dir module absolute dir 23 Dir string 24 // Root means this import path is mod root 25 Root bool 26 // Sum repo absolute dir sum 27 Sum string 28 } 29 30 func (m *Mod) ModuleRoot() string { 31 if m.SubPath != "" { 32 return filepath.Join(m.Module, m.SubPath) 33 } 34 return m.Module 35 } 36 37 func (m *Mod) String() string { 38 if m.Version == "" { 39 return m.Module + "@v0.0.0" 40 } 41 return m.Module + "@" + m.Version 42 } 43 44 func (m *Mod) LoadInfo(ctx context.Context) (bool, error) { 45 if m.Dir == "" || m.Dir[0] != '/' { 46 return false, nil 47 } 48 49 if _, err := os.Stat(m.Dir); os.IsNotExist(err) { 50 return false, errors.Wrapf(err, "%s not found", m.Dir) 51 } 52 53 exists, err := modfile.LoadModFile(m.Dir, &m.ModFile) 54 if err != nil { 55 return false, err 56 } 57 58 if exists { 59 // module name should be from module.cue 60 m.Module = m.ModFile.Module 61 m.Root = true 62 } 63 64 return exists, nil 65 } 66 67 func (m *Mod) Resolved() bool { 68 return m.Dir != "" 69 } 70 71 func (m *Mod) SetRequire(module string, modVersion modfile.ModVersion, indirect bool) { 72 if module == m.Module { 73 return 74 } 75 76 if m.Require == nil { 77 m.Require = map[string]modfile.Requirement{} 78 } 79 80 r := modfile.Requirement{} 81 82 r.ModVersion = modVersion 83 r.Indirect = indirect 84 85 if currentRequire, ok := m.Require[module]; ok { 86 // always using greater one 87 if versionGreaterThan(currentRequire.Version, r.Version) { 88 r.ModVersion = currentRequire.ModVersion 89 } 90 91 if r.Indirect { 92 r.Indirect = currentRequire.Indirect 93 } 94 } 95 96 m.Require[module] = r 97 98 if currentReplace, ok := m.Replace[modfile.VersionedPathIdentity{Path: module}]; ok { 99 if currentReplace.IsLocalReplace() || currentReplace.Import != "" { 100 return 101 } 102 103 currentReplace.Version = r.ModVersion.Version 104 m.Replace[modfile.VersionedPathIdentity{Path: module}] = currentReplace 105 } 106 } 107 108 func (m *Mod) FixVersion(repo string, version string) string { 109 if m.Require != nil { 110 if r, ok := m.Require[repo]; ok { 111 if r.VcsRef != "" && r.Version == "v0.0.0" { 112 return r.VcsRef 113 } 114 return r.Version 115 } 116 } 117 return version 118 } 119 120 func versionGreaterThan(v string, w string) bool { 121 if w == "" { 122 return false 123 } 124 return semver.Compare(v, w) > 0 125 }