This repository has been archived by the owner on May 3, 2022. It is now read-only.
/
catalog.go
83 lines (68 loc) · 1.69 KB
/
catalog.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
package repo
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path/filepath"
"sync"
shippererrors "github.com/bookingcom/shipper/pkg/errors"
"github.com/bookingcom/shipper/pkg/metrics/instrumentedclient"
)
type RemoteFetcher func(url string) ([]byte, error)
func DefaultRemoteFetcher(url string) ([]byte, error) {
resp, err := instrumentedclient.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unsuccessful response code: %s (%d)", resp.Status, resp.StatusCode)
}
return ioutil.ReadAll(resp.Body)
}
type CacheFactory func(name string) (Cache, error)
func DefaultFileCacheFactory(cacheDir string) CacheFactory {
return func(name string) (Cache, error) {
return NewFilesystemCache(
filepath.Join(cacheDir, name),
0, // TODO set limit
)
}
}
type Catalog struct {
factory CacheFactory
repos map[string]*Repo
fetcher RemoteFetcher
sync.Mutex
}
func NewCatalog(factory CacheFactory, fetcher RemoteFetcher) *Catalog {
return &Catalog{
factory: factory,
repos: make(map[string]*Repo),
fetcher: fetcher,
}
}
func (c *Catalog) CreateRepoIfNotExist(repoURL string) (*Repo, error) {
if _, err := url.ParseRequestURI(repoURL); err != nil {
return nil, shippererrors.NewChartRepoInternalError(err)
}
c.Lock()
defer c.Unlock()
name := url2name(repoURL)
repo, ok := c.repos[name]
if !ok {
cache, err := c.factory(name)
if err != nil {
return nil, shippererrors.NewChartRepoInternalError(
fmt.Errorf("failed to create cache: %v", err),
)
}
repo, err = NewRepo(repoURL, cache, c.fetcher)
if err != nil {
return nil, err
}
c.repos[name] = repo
}
return repo, nil
}