/
file.go
88 lines (76 loc) · 2.02 KB
/
file.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
package gomod
import (
"path"
"sort"
"golang.org/x/mod/modfile"
"golang.org/x/mod/module"
)
type Version = module.Version
type Require = modfile.Require
type Replace = modfile.Replace
type File struct {
file *modfile.File
}
// Import returns the module's import path (e.g. github.com/livebud/bud)
func (f *File) Import(subPaths ...string) string {
modulePath := f.file.Module.Mod.Path
subPath := path.Join(subPaths...)
if modulePath == "std" {
return subPath
}
return path.Join(modulePath, subPath)
}
func (f *File) AddRequire(importPath, version string) error {
return f.file.AddRequire(importPath, version)
}
// Replace finds a replaced package within go.mod or returns nil if not found.
func (f *File) Replace(path string) *module.Version {
for _, rep := range f.file.Replace {
if rep.Old.Path == path {
return &rep.Old
}
}
return nil
}
func (f *File) AddReplace(oldPath, oldVers, newPath, newVers string) error {
return f.file.AddReplace(oldPath, oldVers, newPath, newVers)
}
// Return a list of replaces
func (f *File) Replaces() (reps []*Replace) {
reps = make([]*Replace, len(f.file.Replace))
copy(reps, f.file.Replace)
// Consistent ordering regardless of modfile formatting
sort.Slice(reps, func(i, j int) bool {
return reps[i].Old.Path < reps[j].Old.Path
})
return reps
}
// Return a list of requires
func (f *File) Requires() (reqs []*Require) {
reqs = make([]*Require, len(f.file.Require))
copy(reqs, f.file.Require)
// Consistent ordering regardless of modfile formatting
sort.Slice(reqs, func(i, j int) bool {
switch {
case reqs[i].Indirect && !reqs[j].Indirect:
return false
case !reqs[i].Indirect && reqs[j].Indirect:
return true
default:
return reqs[i].Mod.Path < reqs[j].Mod.Path
}
})
return reqs
}
// Require finds a required package within go.mod
func (f *File) Require(path string) *module.Version {
for _, req := range f.file.Require {
if req.Mod.Path == path {
return &req.Mod
}
}
return nil
}
func (f *File) Format() []byte {
return modfile.Format(f.file.Syntax)
}