github.com/crossplane/upjet@v1.3.0/pkg/config/canonical.go (about)

     1  // SPDX-FileCopyrightText: 2024 The Crossplane Authors <https://crossplane.io>
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package config
     6  
     7  import (
     8  	"github.com/pkg/errors"
     9  
    10  	"github.com/crossplane/upjet/pkg/resource/json"
    11  )
    12  
    13  const (
    14  	errFmtNotJSONString = "parameter at path %q with value %v is not a (JSON) string"
    15  	errFmtCanonicalize  = "failed to canonicalize the parameter at path %q"
    16  )
    17  
    18  // CanonicalizeJSONParameters returns a ConfigurationInjector that computes
    19  // and stores the canonical forms of the JSON documents for the specified list
    20  // of top-level Terraform configuration arguments. Please note that currently
    21  // only top-level configuration arguments are supported by this function.
    22  func CanonicalizeJSONParameters(tfPath ...string) ConfigurationInjector {
    23  	return func(jsonMap map[string]any, tfMap map[string]any) error {
    24  		for _, param := range tfPath {
    25  			p, ok := tfMap[param]
    26  			if !ok {
    27  				continue
    28  			}
    29  			s, ok := p.(string)
    30  			if !ok {
    31  				return errors.Errorf(errFmtNotJSONString, param, p)
    32  			}
    33  			if s == "" {
    34  				continue
    35  			}
    36  			cJSON, err := json.Canonicalize(s)
    37  			if err != nil {
    38  				return errors.Wrapf(err, errFmtCanonicalize, param)
    39  			}
    40  			tfMap[param] = cJSON
    41  		}
    42  		return nil
    43  	}
    44  }