Skip to content

Commit

Permalink
Address TODO in PR kubernetes-sigs#4652
Browse files Browse the repository at this point in the history
  • Loading branch information
annasong20 committed Nov 7, 2022
1 parent 6ffd22a commit 08d1e96
Showing 1 changed file with 21 additions and 19 deletions.
40 changes: 21 additions & 19 deletions api/loader/fileloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,31 +299,14 @@ func (fl *fileLoader) errIfRepoCycle(newRepoSpec *git.RepoSpec) error {
// else an error. Relative paths are taken relative
// to the root.
func (fl *fileLoader) Load(path string) ([]byte, error) {
// TODO(annasong): replace check with HasRemoteFileScheme
if u, err := url.Parse(path); err == nil && (u.Scheme == "http" || u.Scheme == "https") {
if HasRemoteFileScheme(path) {
var hc *http.Client
if fl.http != nil {
hc = fl.http
} else {
hc = &http.Client{}
}
resp, err := hc.Get(path)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
_, err := git.NewRepoSpecFromURL(path)
if err == nil {
return nil, errors.Errorf("URL is a git repository")
}
return nil, fmt.Errorf("%w: status code %d (%s)", ErrHTTP, resp.StatusCode, http.StatusText(resp.StatusCode))
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
return loadURL(hc, path)
}
if !filepath.IsAbs(path) {
path = fl.root.Join(path)
Expand All @@ -335,6 +318,25 @@ func (fl *fileLoader) Load(path string) ([]byte, error) {
return fl.fSys.ReadFile(path)
}

func loadURL(hc *http.Client, path string) ([]byte, error) {
resp, err := hc.Get(path)
if err != nil {
return nil, errors.WrapPrefixf(err, "cannot GET url")
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
if _, err = git.NewRepoSpecFromURL(path); err == nil {
return nil, errors.Errorf("URL is a git repository")
}
return nil, fmt.Errorf("%w: status code %d (%s)", ErrHTTP, resp.StatusCode, http.StatusText(resp.StatusCode))
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.WrapPrefixf(err, "cannot read url content")
}
return body, nil
}

// Cleanup runs the cleaner.
func (fl *fileLoader) Cleanup() error {
return fl.cleaner()
Expand Down

0 comments on commit 08d1e96

Please sign in to comment.