github.com/stefanmcshane/helm@v0.0.0-20221213002717-88a4a2c6e77d/pkg/storage/driver/util.go (about) 1 /* 2 Copyright The Helm 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 driver // import "github.com/stefanmcshane/helm/pkg/storage/driver" 18 19 import ( 20 "bytes" 21 "compress/gzip" 22 "encoding/base64" 23 "encoding/json" 24 "io/ioutil" 25 26 rspb "github.com/stefanmcshane/helm/pkg/release" 27 ) 28 29 var b64 = base64.StdEncoding 30 31 var magicGzip = []byte{0x1f, 0x8b, 0x08} 32 33 // encodeRelease encodes a release returning a base64 encoded 34 // gzipped string representation, or error. 35 func encodeRelease(rls *rspb.Release) (string, error) { 36 b, err := json.Marshal(rls) 37 if err != nil { 38 return "", err 39 } 40 var buf bytes.Buffer 41 w, err := gzip.NewWriterLevel(&buf, gzip.BestCompression) 42 if err != nil { 43 return "", err 44 } 45 if _, err = w.Write(b); err != nil { 46 return "", err 47 } 48 w.Close() 49 50 return b64.EncodeToString(buf.Bytes()), nil 51 } 52 53 // decodeRelease decodes the bytes of data into a release 54 // type. Data must contain a base64 encoded gzipped string of a 55 // valid release, otherwise an error is returned. 56 func decodeRelease(data string) (*rspb.Release, error) { 57 // base64 decode string 58 b, err := b64.DecodeString(data) 59 if err != nil { 60 return nil, err 61 } 62 63 // For backwards compatibility with releases that were stored before 64 // compression was introduced we skip decompression if the 65 // gzip magic header is not found 66 if len(b) > 3 && bytes.Equal(b[0:3], magicGzip) { 67 r, err := gzip.NewReader(bytes.NewReader(b)) 68 if err != nil { 69 return nil, err 70 } 71 defer r.Close() 72 b2, err := ioutil.ReadAll(r) 73 if err != nil { 74 return nil, err 75 } 76 b = b2 77 } 78 79 var rls rspb.Release 80 // unmarshal release object bytes 81 if err := json.Unmarshal(b, &rls); err != nil { 82 return nil, err 83 } 84 return &rls, nil 85 }