github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/convert/gitlab/yaml/conditions.go (about)

     1  package yaml
     2  
     3  import "fmt"
     4  
     5  type Conditions struct {
     6  	Refs       []string `yaml:"refs,omitempty"`
     7  	Variables  []string `yaml:"variables,omitempty"`
     8  	Changes    []string `yaml:"changes,omitempty"`
     9  	Kubernetes string   `yaml:"kubernetes,omitempty"`
    10  }
    11  
    12  func (c *Conditions) UnmarshalYAML(unmarshal func(interface{}) error) error {
    13  	var out1 []string
    14  	var out2 string
    15  	var out3 = struct {
    16  		Refs       []string `yaml:"refs"`
    17  		Variables  []string `yaml:"variables"`
    18  		Changes    []string `yaml:"changes"`
    19  		Kubernetes string   `yaml:"kubernetes"`
    20  	}{}
    21  
    22  	// Try to unmarshal to out3 struct
    23  	if err := unmarshal(&out3); err == nil {
    24  		c.Refs = out3.Refs
    25  		c.Variables = out3.Variables
    26  		c.Changes = out3.Changes
    27  		c.Kubernetes = out3.Kubernetes
    28  		return nil
    29  	}
    30  
    31  	// Try to unmarshal to out1 slice of strings
    32  	if err := unmarshal(&out1); err == nil {
    33  		c.Refs = out1
    34  		return nil
    35  	}
    36  
    37  	// Try to unmarshal to out2 single string
    38  	if err := unmarshal(&out2); err == nil {
    39  		c.Refs = []string{out2}
    40  		return nil
    41  	}
    42  
    43  	return fmt.Errorf("failed to unmarshal conditions")
    44  }
    45  
    46  func (c *Conditions) MarshalYAML() (interface{}, error) {
    47  	if len(c.Refs) > 0 && len(c.Variables) == 0 && len(c.Changes) == 0 && c.Kubernetes == "" {
    48  		return c.Refs, nil
    49  	} else {
    50  		output := make(map[string]interface{})
    51  		if len(c.Refs) > 0 {
    52  			output["refs"] = c.Refs
    53  		}
    54  		if len(c.Variables) > 0 {
    55  			output["variables"] = c.Variables
    56  		}
    57  		if len(c.Changes) > 0 {
    58  			output["changes"] = c.Changes
    59  		}
    60  		if c.Kubernetes != "" {
    61  			output["kubernetes"] = c.Kubernetes
    62  		}
    63  		return output, nil
    64  	}
    65  }