|
| 1 | +// SPDX-FileCopyrightText: SAP SE or an SAP affiliate company and Gardener contributors |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +package componentvector |
| 6 | + |
| 7 | +import ( |
| 8 | + "bytes" |
| 9 | + "fmt" |
| 10 | + "io" |
| 11 | + "net/http" |
| 12 | + "strings" |
| 13 | + |
| 14 | + "k8s.io/component-base/version" |
| 15 | +) |
| 16 | + |
| 17 | +const ( |
| 18 | + githubUrlPrefix = "https://github.com" |
| 19 | + glkRepository = "gardener/gardener-landscape-kit" |
| 20 | + filePath = "componentvector/components.yaml" |
| 21 | +) |
| 22 | + |
| 23 | +// GetReleaseBranchName returns the release branch name based on the current GLK version. |
| 24 | +func GetReleaseBranchName() string { |
| 25 | + glkVersion := version.Get() |
| 26 | + return fmt.Sprintf("release-v%s.%s", glkVersion.Major, glkVersion.Minor) |
| 27 | +} |
| 28 | + |
| 29 | +// GetDefaultComponentVectorFromGitHub fetches the latest default component vector file |
| 30 | +// from the release branch of the gardener-landscape-kit GitHub repository based on the current GLK version. |
| 31 | +func GetDefaultComponentVectorFromGitHub() ([]byte, error) { |
| 32 | + return getFileFromGitRepository(githubUrlPrefix+"/"+glkRepository, GetReleaseBranchName(), filePath) |
| 33 | +} |
| 34 | + |
| 35 | +func getFileFromGitRepository(repositoryUrl, branch, filePath string) ([]byte, error) { |
| 36 | + rawURL := strings.TrimSuffix(repositoryUrl, "/") |
| 37 | + |
| 38 | + if !strings.HasPrefix(rawURL, githubUrlPrefix) { |
| 39 | + return nil, fmt.Errorf("unsupported Git provider for URL: %s", rawURL) |
| 40 | + } |
| 41 | + // Convert GitHub repo URL to raw content URL if necessary. |
| 42 | + // e.g. https://github.com/org/repo -> https://raw.githubusercontent.com/org/repo/branch/path |
| 43 | + rawURL = "https://raw.githubusercontent.com" + rawURL[len(githubUrlPrefix):] + "/" + branch + "/" + filePath |
| 44 | + |
| 45 | + resp, err := http.Get(rawURL) // #nosec G107 -- This is a GET request to a constrained public GitHub URL. |
| 46 | + if err != nil { |
| 47 | + return nil, err |
| 48 | + } |
| 49 | + defer resp.Body.Close() |
| 50 | + |
| 51 | + if resp.StatusCode != http.StatusOK { |
| 52 | + return nil, fmt.Errorf("failed to fetch file from '%s': %s", rawURL, resp.Status) |
| 53 | + } |
| 54 | + |
| 55 | + buf := new(bytes.Buffer) |
| 56 | + _, err = io.Copy(buf, resp.Body) |
| 57 | + if err != nil { |
| 58 | + return nil, err |
| 59 | + } |
| 60 | + return buf.Bytes(), nil |
| 61 | +} |
0 commit comments