github.com/caos/orbos@v1.5.14-0.20221103111702-e6cd0cea7ad4/pkg/tree/tree.go (about)

     1  package tree
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/caos/orbos/mntr"
     7  
     8  	"gopkg.in/yaml.v3"
     9  )
    10  
    11  var (
    12  	_ yaml.Marshaler   = (*Tree)(nil)
    13  	_ yaml.Unmarshaler = (*Tree)(nil)
    14  )
    15  
    16  type Tree struct {
    17  	Common   *Common `yaml:",inline"`
    18  	Original *yaml.Node
    19  	Parsed   interface{} `yaml:",inline"`
    20  }
    21  
    22  type Common struct {
    23  	Kind string `json:"kind" yaml:"kind"`
    24  	// Don't access X_Version, it is only exported for (de-)serialization. Use Version and OverwriteVersion methods instead.
    25  	X_Version string `json:"version,omitempty" yaml:"version,omitempty"`
    26  	// Don't access X_ApiVersion, it is only exported for (de-)serialization. Use Version and OverwriteVersion methods instead.
    27  	X_ApiVersion string `json:"apiVersion,omitempty" yaml:"apiVersion,omitempty"`
    28  }
    29  
    30  func NewCommon(kind, version string, isKubernetesResource bool) *Common {
    31  	c := new(Common)
    32  	c.Kind = kind
    33  	if isKubernetesResource {
    34  		c.X_ApiVersion = version
    35  		return c
    36  	}
    37  	c.X_Version = version
    38  	return c
    39  }
    40  
    41  func (c *Common) OverwriteVersion(v string) {
    42  	if c.X_ApiVersion != "" {
    43  		c.X_ApiVersion = v
    44  		return
    45  	}
    46  	c.X_Version = v
    47  }
    48  
    49  func (c *Common) Version() string {
    50  	if c.X_ApiVersion != "" {
    51  		return c.X_ApiVersion
    52  	}
    53  	return c.X_Version
    54  }
    55  
    56  func (c *Tree) UnmarshalYAML(node *yaml.Node) error {
    57  	c.Original = new(yaml.Node)
    58  	*c.Original = *node
    59  
    60  	if err := c.Original.Decode(&c.Common); err != nil {
    61  		return mntr.ToUserError(fmt.Errorf("decoding version or kind failed: kind \"%s\", err %w", c.Common.Kind, err))
    62  	}
    63  
    64  	return nil
    65  }
    66  
    67  func (c *Tree) MarshalYAML() (interface{}, error) {
    68  	return c.Parsed, nil
    69  }