github.com/argoproj/argo-cd/v3@v3.2.1/util/lua/impacted_resource.go (about)

     1  package lua
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
     7  )
     8  
     9  // This struct represents a wrapper, that is returned from Lua custom action script, around the unstructured k8s resource + a k8s operation
    10  // that will need to be performed on this returned resource.
    11  // Currently only "create" and "patch" operations are supported for custom actions.
    12  // This replaces the traditional architecture of "Lua action returns the source resource for ArgoCD to patch".
    13  // This enables ArgoCD to create NEW resources upon custom action.
    14  // Note that the Lua code in the custom action is coupled to this type, since Lua json output is then unmarshalled to this struct.
    15  // Avoided using iota, since need the mapping of the string value the end users will write in Lua code ("create" and "patch").
    16  // TODO: maybe there is a nicer general way to marshal and unmarshal, instead of explicit iteration over the enum values.
    17  type K8SOperation string
    18  
    19  const (
    20  	CreateOperation K8SOperation = "create"
    21  	PatchOperation  K8SOperation = "patch"
    22  )
    23  
    24  type ImpactedResource struct {
    25  	UnstructuredObj *unstructured.Unstructured `json:"resource"`
    26  	K8SOperation    K8SOperation               `json:"operation"`
    27  }
    28  
    29  func (op *K8SOperation) UnmarshalJSON(data []byte) error {
    30  	switch string(data) {
    31  	case `"create"`:
    32  		*op = CreateOperation
    33  	case `"patch"`:
    34  		*op = PatchOperation
    35  	default:
    36  		return fmt.Errorf("unsupported operation: %s", data)
    37  	}
    38  	return nil
    39  }
    40  
    41  func (op K8SOperation) MarshalJSON() ([]byte, error) {
    42  	switch op {
    43  	case CreateOperation:
    44  		return []byte(`"create"`), nil
    45  	case PatchOperation:
    46  		return []byte(`"patch"`), nil
    47  	default:
    48  		return nil, fmt.Errorf("unsupported operation: %s", op)
    49  	}
    50  }