github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/build/layerutils/charts/helm.go (about)

     1  // Copyright © 2021 Alibaba Group Holding Ltd.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package charts
    16  
    17  import (
    18  	"encoding/json"
    19  	"fmt"
    20  
    21  	"github.com/sealerio/sealer/build/layerutils"
    22  
    23  	"github.com/sirupsen/logrus"
    24  	"helm.sh/helm/v3/pkg/chart"
    25  	"helm.sh/helm/v3/pkg/chart/loader"
    26  	"helm.sh/helm/v3/pkg/chartutil"
    27  	"helm.sh/helm/v3/pkg/engine"
    28  )
    29  
    30  func Load(chartPath string) (*chart.Chart, error) {
    31  	return loader.LoadDir(chartPath)
    32  }
    33  
    34  func PackageHelmChart(chartPath string) (string, error) {
    35  	ch, err := Load(chartPath)
    36  	if err != nil {
    37  		return "", err
    38  	}
    39  
    40  	name, err := chartutil.Save(ch, ".")
    41  	if err != nil {
    42  		return "", err
    43  	}
    44  
    45  	return name, nil
    46  }
    47  
    48  func RenderHelmChart(chartPath string) (map[string]string, error) {
    49  	ch, err := Load(chartPath)
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  
    54  	options := chartutil.ReleaseOptions{
    55  		Name: "dryrun",
    56  	}
    57  	valuesToRender, err := chartutil.ToRenderValues(ch, nil, options, nil)
    58  	if err != nil {
    59  		return nil, fmt.Errorf("failed to render values: %v", err)
    60  	}
    61  
    62  	content, err := engine.Render(ch, valuesToRender)
    63  	if err != nil {
    64  		b, _ := json.Marshal(valuesToRender)
    65  		logrus.Debugf("values is %s", b)
    66  		return nil, fmt.Errorf("failed to render helm chart: %s", err)
    67  	}
    68  
    69  	return content, nil
    70  }
    71  
    72  func GetImageList(chartPath string) ([]string, error) {
    73  	var list []string
    74  	content, err := RenderHelmChart(chartPath)
    75  	if err != nil {
    76  		return list, fmt.Errorf("failed to render helm chart: %s", err)
    77  	}
    78  
    79  	for _, v := range content {
    80  		images := layerutils.DecodeImages(v)
    81  		if len(images) != 0 {
    82  			list = append(list, images...)
    83  		}
    84  	}
    85  
    86  	return list, nil
    87  }