github.com/yogeshkumararora/slsa-github-generator@v1.10.1-0.20240520161934-11278bd5afb4/internal/utils/marshal.go (about)

     1  // Copyright 2022 SLSA Authors
     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 utils
    16  
    17  import (
    18  	"encoding/base64"
    19  	"encoding/json"
    20  	"fmt"
    21  )
    22  
    23  // UnmarshalList unmarshals a string into a list of strings.
    24  func UnmarshalList(arg string) ([]string, error) {
    25  	var res []string
    26  	// If argument is empty, return an empty list early,
    27  	// because `json.Unmarshal` would fail.
    28  	if arg == "" {
    29  		return res, nil
    30  	}
    31  
    32  	cs, err := base64.StdEncoding.DecodeString(arg)
    33  	if err != nil {
    34  		return res, fmt.Errorf("base64.StdEncoding.DecodeString: %w", err)
    35  	}
    36  
    37  	if err := json.Unmarshal(cs, &res); err != nil {
    38  		return []string{}, fmt.Errorf("json.Unmarshal: %w", err)
    39  	}
    40  	return res, nil
    41  }
    42  
    43  // MarshalToString marshals to a string.
    44  func MarshalToString(args interface{}) (string, error) {
    45  	jsonData, err := json.Marshal(args)
    46  	if err != nil {
    47  		return "", fmt.Errorf("json.Marshal: %w", err)
    48  	}
    49  
    50  	encoded := base64.StdEncoding.EncodeToString(jsonData)
    51  	if err != nil {
    52  		return "", fmt.Errorf("base64.StdEncoding.EncodeString: %w", err)
    53  	}
    54  	return encoded, nil
    55  }
    56  
    57  // MarshalToBytes marshals to a byte array.
    58  func MarshalToBytes(args interface{}) ([]byte, error) {
    59  	encoded, err := MarshalToString(args)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  	return []byte(encoded), nil
    64  }