github.com/hashicorp/packer@v1.14.3/hcl2template/function/encoding.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package function
     5  
     6  import (
     7  	"bytes"
     8  	"compress/gzip"
     9  	"encoding/base64"
    10  	"fmt"
    11  
    12  	"github.com/zclconf/go-cty/cty"
    13  	"github.com/zclconf/go-cty/cty/function"
    14  )
    15  
    16  // Base64GzipFunc constructs a function that compresses a string with gzip and then encodes the result in
    17  // Base64 encoding.
    18  var Base64GzipFunc = function.New(&function.Spec{
    19  	Params: []function.Parameter{
    20  		{
    21  			Name: "str",
    22  			Type: cty.String,
    23  		},
    24  	},
    25  	Type: function.StaticReturnType(cty.String),
    26  	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
    27  		s := args[0].AsString()
    28  
    29  		var b bytes.Buffer
    30  		gz := gzip.NewWriter(&b)
    31  		if _, err := gz.Write([]byte(s)); err != nil {
    32  			return cty.UnknownVal(cty.String), fmt.Errorf("failed to write gzip raw data: %w", err)
    33  		}
    34  		if err := gz.Flush(); err != nil {
    35  			return cty.UnknownVal(cty.String), fmt.Errorf("failed to flush gzip writer: %w", err)
    36  		}
    37  		if err := gz.Close(); err != nil {
    38  			return cty.UnknownVal(cty.String), fmt.Errorf("failed to close gzip writer: %w", err)
    39  		}
    40  		return cty.StringVal(base64.StdEncoding.EncodeToString(b.Bytes())), nil
    41  	},
    42  })
    43  
    44  // Base64Gzip compresses a string with gzip and then encodes the result in
    45  // Base64 encoding.
    46  //
    47  // Packer uses the "standard" Base64 alphabet as defined in RFC 4648 section 4.
    48  //
    49  // Strings in the Packer language are sequences of unicode characters rather
    50  // than bytes, so this function will first encode the characters from the string
    51  // as UTF-8, then apply gzip compression, and then finally apply Base64 encoding.
    52  func Base64Gzip(str cty.Value) (cty.Value, error) {
    53  	return Base64GzipFunc.Call([]cty.Value{str})
    54  }