-
Notifications
You must be signed in to change notification settings - Fork 2
/
source.go
105 lines (91 loc) · 1.95 KB
/
source.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
package libyear
import (
"io"
"net/http"
"net/url"
"os"
"strings"
"github.com/Masterminds/semver"
"github.com/pkg/errors"
)
type Source interface {
Read() ([]byte, error)
}
type PkgSource struct {
Pkg string
repo ModulesRepo
vcs *VCSRegistry
}
func (p *PkgSource) Read() ([]byte, error) {
path := p.Pkg
repo := p.repo
var version *semver.Version
if strings.Contains(p.Pkg, "@") {
split := strings.Split(path, "@")
if len(split) != 2 {
return nil, errors.New("invalid pkg name provided, expected version after @ char")
}
path = split[0]
if split[1] != "latest" {
var err error
version, err = semver.NewVersion(split[1])
if err != nil {
return nil, err
}
}
}
if p.vcs.IsPrivate(path) {
var err error
repo, err = p.vcs.GetHandler(path)
if err != nil {
return nil, err
}
}
if version == nil {
// .mod endpoint does not support 'latest' version literal, we need an exact semver.
latest, err := repo.GetLatestInfo(path)
if err != nil {
return nil, err
}
version = latest.Version
}
return repo.GetModFile(path, version)
}
func (p *PkgSource) SetModulesRepo(repo ModulesRepo) {
p.repo = repo
}
func (p *PkgSource) SetVCSRegistry(registry *VCSRegistry) {
p.vcs = registry
}
type URLSource struct {
HTTP http.Client
RawURL string
}
func (s URLSource) Read() ([]byte, error) {
u, err := url.Parse(s.RawURL)
if err != nil {
return nil, err
}
resp, err := s.HTTP.Get(u.String())
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
data, _ := io.ReadAll(resp.Body)
return nil, errors.Errorf(
"unexpected response status code: %d, body: %s",
resp.StatusCode, string(data))
}
return io.ReadAll(resp.Body)
}
type FileSource struct {
Path string
}
func (s FileSource) Read() ([]byte, error) {
return os.ReadFile(s.Path)
}
type StdinSource struct{}
func (s StdinSource) Read() ([]byte, error) {
return io.ReadAll(os.Stdin)
}