github.com/crossplane/upjet@v1.3.0/pkg/resource/extractor.go (about)

     1  // SPDX-FileCopyrightText: 2023 The Crossplane Authors <https://crossplane.io>
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package resource
     6  
     7  import (
     8  	"github.com/crossplane/crossplane-runtime/pkg/fieldpath"
     9  	xpref "github.com/crossplane/crossplane-runtime/pkg/reference"
    10  	xpresource "github.com/crossplane/crossplane-runtime/pkg/resource"
    11  )
    12  
    13  // ExtractResourceID extracts the value of `status.atProvider.id`
    14  // from a Terraformed resource. If mr is not a Terraformed
    15  // resource, returns an empty string.
    16  func ExtractResourceID() xpref.ExtractValueFn {
    17  	return func(mr xpresource.Managed) string {
    18  		tr, ok := mr.(Terraformed)
    19  		if !ok {
    20  			return ""
    21  		}
    22  		return tr.GetID()
    23  	}
    24  }
    25  
    26  // ExtractParamPath extracts the value of `sourceAttr`
    27  // from `spec.forProvider` allowing nested parameters.
    28  // If `isObservation` is set, then referenced param
    29  // is retrieved from the status, if not, it's extracted
    30  // from the spec.
    31  // An example argument to ExtractParamPath is
    32  // `key`, if `spec.forProvider.key` is to be extracted
    33  // from the referred resource.
    34  func ExtractParamPath(sourceAttr string, isObservation bool) xpref.ExtractValueFn {
    35  	return func(mr xpresource.Managed) string {
    36  		tr, ok := mr.(Terraformed)
    37  		if !ok {
    38  			return ""
    39  		}
    40  		var params map[string]any
    41  		var err error
    42  		if isObservation {
    43  			params, err = tr.GetObservation()
    44  		} else {
    45  			params, err = tr.GetParameters()
    46  		}
    47  		// TODO: we had better log the error
    48  		if err != nil {
    49  			return ""
    50  		}
    51  		paved := fieldpath.Pave(params)
    52  		v, err := paved.GetString(sourceAttr)
    53  		// TODO: we had better log the error
    54  		if err != nil {
    55  			return ""
    56  		}
    57  		return v
    58  	}
    59  }