|
1 | 1 | package kubernetes |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "fmt" |
| 5 | + "strings" |
| 6 | + |
4 | 7 | "helm.sh/helm/v3/pkg/chart/loader" |
| 8 | + "helm.sh/helm/v3/pkg/chartutil" |
| 9 | + "helm.sh/helm/v3/pkg/engine" |
5 | 10 | ) |
6 | 11 |
|
| 12 | +// GetManifestsFromHelm fetches the chart, loads it, and renders templates + CRDs |
7 | 13 | func GetManifestsFromHelm(url string) (string, error) { |
8 | 14 | chartLocation, err := fetchHelmChart(url, "") |
9 | 15 | if err != nil { |
10 | | - return "", ErrApplyHelmChart(err) |
| 16 | + return "", ErrApplyHelmChart(fmt.Errorf("failed to fetch helm chart: %w", err)) |
11 | 17 | } |
12 | 18 |
|
13 | 19 | chart, err := loader.Load(chartLocation) |
14 | 20 | if err != nil { |
15 | | - return "", ErrApplyHelmChart(err) |
| 21 | + return "", ErrApplyHelmChart(fmt.Errorf("failed to load chart from %s: %w", chartLocation, err)) |
| 22 | + } |
| 23 | + |
| 24 | + releaseOptions := chartutil.ReleaseOptions{ |
| 25 | + Name: "meshery-helm-release", |
| 26 | + Namespace: "default", |
| 27 | + Revision: 1, |
| 28 | + IsInstall: true, |
16 | 29 | } |
17 | | - manifests := "" |
| 30 | + |
| 31 | + caps := chartutil.DefaultCapabilities |
| 32 | + |
| 33 | + values, err := chartutil.ToRenderValues(chart, chartutil.Values{}, releaseOptions, caps) |
| 34 | + if err != nil { |
| 35 | + return "", ErrApplyHelmChart(fmt.Errorf("failed to generate render values: %w", err)) |
| 36 | + } |
| 37 | + |
| 38 | + renderedFiles, err := engine.Render(chart, values) |
| 39 | + if err != nil { |
| 40 | + return "", ErrApplyHelmChart(fmt.Errorf("failed to render chart templates: %w", err)) |
| 41 | + } |
| 42 | + |
| 43 | + var b strings.Builder |
| 44 | + |
| 45 | + // Helper to safely append separators |
| 46 | + appendSeparator := func() { |
| 47 | + if b.Len() > 0 { |
| 48 | + b.WriteString("\n---\n") |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + // Append CRDs |
18 | 53 | for _, crdobject := range chart.CRDObjects() { |
19 | | - manifests += "\n---\n" |
20 | | - manifests += string(crdobject.File.Data) |
| 54 | + appendSeparator() |
| 55 | + b.Write(crdobject.File.Data) |
| 56 | + } |
| 57 | + |
| 58 | + // Append Rendered Templates |
| 59 | + for filename, fileContent := range renderedFiles { |
| 60 | + // Filter out non-manifest files |
| 61 | + if strings.HasSuffix(filename, "NOTES.txt") { |
| 62 | + continue |
| 63 | + } |
| 64 | + if strings.TrimSpace(fileContent) == "" { |
| 65 | + continue |
| 66 | + } |
| 67 | + |
| 68 | + appendSeparator() |
| 69 | + b.WriteString(fileContent) |
21 | 70 | } |
| 71 | + |
| 72 | + manifests := b.String() |
| 73 | + |
| 74 | + if strings.TrimSpace(manifests) == "" { |
| 75 | + return "", ErrApplyHelmChart(fmt.Errorf("chart rendered empty manifests")) |
| 76 | + } |
| 77 | + |
22 | 78 | return manifests, nil |
23 | 79 | } |
0 commit comments