github.com/oam-dev/kubevela@v1.9.11/hack/utils/common.go (about) 1 /* 2 Copyright 2021 The KubeVela Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package utils 18 19 import ( 20 "bytes" 21 "encoding/base64" 22 "fmt" 23 "io" 24 "os" 25 "strings" 26 27 helm "helm.sh/helm/v3/pkg/action" 28 "helm.sh/helm/v3/pkg/chart" 29 "helm.sh/helm/v3/pkg/chart/loader" 30 ) 31 32 // FprintZipData converts zip binary contents to a string literal. 33 // From https://github.com/rakyll/statik/blob/master/statik.go#L313 34 func FprintZipData(dest *bytes.Buffer, zipData []byte) { 35 for _, b := range zipData { 36 if b == '\n' { 37 dest.WriteString(`\n`) 38 continue 39 } 40 if b == '\\' { 41 dest.WriteString(`\\`) 42 continue 43 } 44 if b == '"' { 45 dest.WriteString(`\"`) 46 continue 47 } 48 if (b >= 32 && b <= 126) || b == '\t' { 49 dest.WriteByte(b) 50 continue 51 } 52 fmt.Fprintf(dest, "\\x%02x", b) 53 } 54 } 55 56 // GetChartSource is a helper to convert a filepath to a chart to a 57 // base64-encoded, gzipped tarball. 58 func GetChartSource(path string) (string, error) { 59 pack := helm.NewPackage() 60 packagedPath, err := pack.Run(path, nil) 61 if err != nil { 62 return "", err 63 } 64 defer os.Remove(packagedPath) 65 packaged, err := os.ReadFile(packagedPath) 66 if err != nil { 67 return "", err 68 } 69 b64Encoded := bytes.NewBuffer(nil) 70 enc := base64.NewEncoder(base64.StdEncoding, b64Encoded) 71 _, err = io.Copy(enc, bytes.NewReader(packaged)) 72 if err != nil { 73 return "", err 74 } 75 return b64Encoded.String(), nil 76 } 77 78 // LoadChart is a helper to turn a base64-encoded, gzipped tarball into a chart. 79 func LoadChart(source string) (*chart.Chart, error) { 80 dec := base64.NewDecoder(base64.StdEncoding, strings.NewReader(source)) 81 tgz := bytes.NewBuffer(nil) 82 _, err := io.Copy(tgz, dec) 83 if err != nil { 84 return nil, err 85 } 86 return loader.LoadArchive(tgz) 87 }