-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch.go
100 lines (87 loc) · 2.47 KB
/
fetch.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
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"github.com/kubernetes/helm/pkg/chart"
"github.com/kubernetes/helm/pkg/repo"
"github.com/spf13/cobra"
)
var untarFile bool
var untarDir string
func init() {
RootCommand.AddCommand(fetchCmd)
fetchCmd.Flags().BoolVar(&untarFile, "untar", false, "If set to true, will untar the chart after downloading it.")
fetchCmd.Flags().StringVar(&untarDir, "untardir", ".", "If untar is specified, this flag specifies where to untar the chart.")
}
var fetchCmd = &cobra.Command{
Use: "fetch [chart URL | repo/chartname]",
Short: "Download a chart from a repository and (optionally) unpack it in local directory.",
Long: "",
RunE: fetch,
}
func fetch(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return fmt.Errorf("This command needs at least one argument, url or repo/name of the chart.")
}
f, err := repo.LoadRepositoriesFile(repositoriesFile())
if err != nil {
return err
}
// get download url
u, err := mapRepoArg(args[0], f.Repositories)
if err != nil {
return err
}
resp, err := http.Get(u.String())
if err != nil {
return err
}
if resp.StatusCode != 200 {
return fmt.Errorf("Failed to fetch %s : %s", u.String(), resp.Status)
}
defer resp.Body.Close()
if untarFile {
return chart.Expand(untarDir, resp.Body)
}
p := strings.Split(u.String(), "/")
return saveChartFile(p[len(p)-1], resp.Body)
}
// mapRepoArg figures out which format the argument is given, and creates a fetchable
// url from it.
func mapRepoArg(arg string, r map[string]string) (*url.URL, error) {
// See if it's already a full URL.
u, err := url.ParseRequestURI(arg)
if err == nil {
// If it has a scheme and host and path, it's a full URL
if u.IsAbs() && len(u.Host) > 0 && len(u.Path) > 0 {
return u, nil
}
return nil, fmt.Errorf("Invalid chart url format: %s", arg)
}
// See if it's of the form: repo/path_to_chart
p := strings.Split(arg, "/")
if len(p) > 1 {
if baseURL, ok := r[p[0]]; ok {
if !strings.HasSuffix(baseURL, "/") {
baseURL = baseURL + "/"
}
return url.ParseRequestURI(baseURL + strings.Join(p[1:], "/"))
}
return nil, fmt.Errorf("No such repo: %s", p[0])
}
return nil, fmt.Errorf("Invalid chart url format: %s", arg)
}
func saveChartFile(c string, r io.Reader) error {
// Grab the chart name that we'll use for the name of the file to download to.
out, err := os.Create(c)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, r)
return err
}