...

Package yaml

import "sigs.k8s.io/kustomize/kyaml/yaml"
Overview
Index
Examples
Subdirectories

Overview ▾

Package yaml contains libraries for manipulating individual Kubernetes Resource Configuration as yaml, keeping yaml structure and comments.

Parsing Resources

Typically Resources will be initialized as collections through the kio package libraries. However it is possible to directly initialize Resources using Parse.

resource, err := yaml.Parse("apiVersion: apps/v1\nkind: Deployment")

Processing Resources

Individual Resources are manipulated using the Pipe and PipeE to apply Filter functions to transform the Resource data.

err := resource.PipeE(yaml.SetAnnotation("key", "value"))

If multiple Filter functions are provided to Pipe or PipeE, each function is applied to the result of the last function -- e.g. yaml.Lookup(...), yaml.SetField(...)

Field values may also be retrieved using Pipe.

annotationValue, err := resource.Pipe(yaml.GetAnnotation("key"))

See http://www.linfo.org/filters.html for a definition of filters.

Common Filters

There are a number of standard filter functions provided by the yaml package.

Working with annotations:

[AnnotationSetter{}, AnnotationGetter{}, AnnotationClearer{}]

Working with fields by path:

[PathMatcher{}, PathGetter{}]

Working with individual fields on Maps and Objects:

[FieldMatcher{}, FieldSetter{}, FieldGetter{}]

Working with individual elements in Sequences:

[ElementAppender{}, ElementSetter{}, ElementMatcher{}]

Writing Filters

Users may implement their own filter functions. When doing so, can be necessary to work with the RNode directly rather than through Pipe. RNode provides a number of functions for doing so. See:

[GetMeta(), Fields(), Elements(), String()]

Example

Code:

obj, err := Parse(`apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
`)
if err != nil {
    log.Fatal(err)
}

containers, err := Parse(`
- name: nginx # first container
  image: nginx
- name: nginx2 # second container
  image: nginx2
`)
if err != nil {
    log.Fatal(err)
}

node, err := obj.Pipe(
    LookupCreate(SequenceNode, "spec", "template", "spec", "containers"),
    Append(containers.YNode().Content...))
if err != nil {
    log.Fatal(err)
}

fmt.Println(node.String())
fmt.Println(obj.String())

Output:

 <nil>
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
spec:
  template:
    spec:
      containers:
      - name: nginx # first container
        image: nginx
      - name: nginx2 # second container
        image: nginx2
 <nil>

Index ▾

Constants
Variables
func ClearEmptyAnnotations(rn *RNode) error
func CopyYNode(n *yaml.Node) *yaml.Node
func DeriveSeqIndentStyle(originalYAML string) string
func ErrorIfAnyInvalidAndNonNull(kind yaml.Kind, rn ...*RNode) error
func ErrorIfInvalid(rn *RNode, kind yaml.Kind) error
func FormatNonStringStyle(node *Node, schema spec.Schema)
func GetValue(node *RNode) string
func IsCreate(kind yaml.Kind) bool
func IsEmptyMap(node *RNode) bool
func IsFoundOrError(rn *RNode, err error) bool
func IsIdxNumber(p string) bool
func IsListIndex(p string) bool
func IsMissingOrError(rn *RNode, err error) bool
func IsMissingOrNull(node *RNode) bool
func IsValueNonString(value string) bool
func IsWildcard(p string) bool
func IsYNodeEmptyDoc(n *yaml.Node) bool
func IsYNodeEmptyMap(n *yaml.Node) bool
func IsYNodeEmptySeq(n *yaml.Node) bool
func IsYNodeNilOrEmpty(n *yaml.Node) bool
func IsYNodeString(n *yaml.Node) bool
func IsYNodeTaggedNull(n *yaml.Node) bool
func IsYNodeZero(n *yaml.Node) bool
func IsYaml1_1NonString(node *Node) bool
func MarshalWithOptions(in interface{}, opts *EncoderOptions) ([]byte, error)
func NewEncoderWithOptions(w io.Writer, opts *EncoderOptions) *yaml.Encoder
func SetK8sName(value string) k8sMetaSetter
func SetK8sNamespace(value string) k8sMetaSetter
func SortedMapKeys(m map[string]string) []string
func SplitIndexNameValue(p string) (string, string, error)
func String(node *yaml.Node, opts ...string) (string, error)
func SyncMapNodesOrder(from, to *RNode)
func UpdateFile(filter Filter, path string) error
func WriteFile(node *RNode, path string) error
type AnnotationClearer
    func ClearAnnotation(key string) AnnotationClearer
    func (c AnnotationClearer) Filter(rn *RNode) (*RNode, error)
type AnnotationGetter
    func GetAnnotation(key string) AnnotationGetter
    func (g AnnotationGetter) Filter(rn *RNode) (*RNode, error)
type AnnotationSetter
    func SetAnnotation(key, value string) AnnotationSetter
    func (s AnnotationSetter) Filter(rn *RNode) (*RNode, error)
type Comments
type Decoder
type ElementAppender
    func Append(elements ...*yaml.Node) ElementAppender
    func (a ElementAppender) Filter(rn *RNode) (*RNode, error)
type ElementIndexer
    func GetElementByIndex(index int) ElementIndexer
    func (i ElementIndexer) Filter(rn *RNode) (*RNode, error)
type ElementMatcher
    func GetElementByKey(key string) ElementMatcher
    func MatchElement(field, value string) ElementMatcher
    func MatchElementList(keys []string, values []string) ElementMatcher
    func (e ElementMatcher) Filter(rn *RNode) (*RNode, error)
type ElementSetter
    func (e ElementSetter) Filter(rn *RNode) (*RNode, error)
type Encoder
type EncoderOptions
type FieldClearer
    func Clear(name string) FieldClearer
    func (c FieldClearer) Filter(rn *RNode) (*RNode, error)
type FieldMatcher
    func Get(name string) FieldMatcher
    func Match(value string) FieldMatcher
    func MatchField(name, value string) FieldMatcher
    func (f FieldMatcher) Filter(rn *RNode) (*RNode, error)
type FieldSetter
    func Set(value *RNode) FieldSetter
    func SetField(name string, value *RNode) FieldSetter
    func (s FieldSetter) Filter(rn *RNode) (*RNode, error)
type Filter
    func LookupFirstMatch(paths [][]string) Filter
    func Tee(filters ...Filter) Filter
type FilterFunc
    func (f FilterFunc) Filter(object *RNode) (*RNode, error)
type FilterMatcher
    func (t FilterMatcher) Filter(rn *RNode) (*RNode, error)
type InvalidNodeKindError
    func (e *InvalidNodeKindError) ActualNodeKind() Kind
    func (e *InvalidNodeKindError) Error() string
type IsZeroer
type Kind
type LabelSetter
    func SetLabel(key, value string) LabelSetter
    func (s LabelSetter) Filter(rn *RNode) (*RNode, error)
type MapEntrySetter
    func (s MapEntrySetter) Filter(rn *RNode) (*RNode, error)
type MapNode
    func (mn *MapNode) IsNilOrEmpty() bool
type MapNodeSlice
    func (m MapNodeSlice) Keys() []*RNode
    func (m MapNodeSlice) Values() []*RNode
type Marshaler
type MergeOptions
type MergeOptionsListIncreaseDirection
type NameMeta
type NoFieldError
    func (e NoFieldError) Error() string
type Node
type ObjectMeta
    func (in *ObjectMeta) DeepCopy() *ObjectMeta
    func (in *ObjectMeta) DeepCopyInto(out *ObjectMeta)
type Parser
    func (p Parser) Filter(_ *RNode) (*RNode, error)
type PathGetter
    func Lookup(path ...string) PathGetter
    func LookupCreate(kind yaml.Kind, path ...string) PathGetter
    func (l PathGetter) Filter(rn *RNode) (*RNode, error)
type PathMatcher
    func (p *PathMatcher) Filter(rn *RNode) (*RNode, error)
type PrefixSetter
    func (s PrefixSetter) Filter(object *RNode) (*RNode, error)
type RNode
    func ConvertJSONToYamlNode(jsonStr string) (*RNode, error)
    func FromMap(m map[string]interface{}) (*RNode, error)
    func MakeNullNode() *RNode
    func MakePersistentNullNode(value string) *RNode
    func MustParse(value string) *RNode
    func NewListRNode(values ...string) *RNode
    func NewMapRNode(values *map[string]string) *RNode
    func NewRNode(value *yaml.Node) *RNode
    func NewScalarRNode(value string) *RNode
    func NewStringRNode(value string) *RNode
    func Parse(value string) (*RNode, error)
    func ReadFile(path string) (*RNode, error)
    func (rn *RNode) AppendToFieldPath(parts ...string)
    func (rn *RNode) Content() []*yaml.Node
    func (rn *RNode) Copy() *RNode
    func (rn *RNode) DeAnchor() (err error)
    func (rn *RNode) Document() *yaml.Node
    func (rn *RNode) Element(key, value string) *RNode
    func (rn *RNode) ElementList(keys []string, values []string) *RNode
    func (rn *RNode) ElementValues(key string) ([]string, error)
    func (rn *RNode) ElementValuesList(keys []string) ([][]string, error)
    func (rn *RNode) Elements() ([]*RNode, error)
    func (rn *RNode) Field(field string) *MapNode
    func (rn *RNode) FieldPath() []string
    func (rn *RNode) FieldRNodes() ([]*RNode, error)
    func (rn *RNode) Fields() ([]string, error)
    func (rn *RNode) GetAnnotations(annotations ...string) map[string]string
    func (rn *RNode) GetApiVersion() string
    func (rn *RNode) GetAssociativeKey() string
    func (rn *RNode) GetBinaryDataMap() map[string]string
    func (rn *RNode) GetDataMap() map[string]string
    func (rn *RNode) GetFieldValue(path string) (interface{}, error)
    func (rn *RNode) GetKind() string
    func (rn *RNode) GetLabels(labels ...string) map[string]string
    func (rn *RNode) GetMeta() (ResourceMeta, error)
    func (rn *RNode) GetName() string
    func (rn *RNode) GetNamespace() string
    func (rn *RNode) GetSlice(path string) ([]interface{}, error)
    func (rn *RNode) GetString(path string) (string, error)
    func (rn *RNode) GetValidatedDataMap(expectedKeys []string) (map[string]string, error)
    func (rn *RNode) GetValidatedMetadata() (ResourceMeta, error)
    func (rn *RNode) HasNilEntryInList() (bool, string)
    func (rn *RNode) IsAssociative() bool
    func (rn *RNode) IsNil() bool
    func (rn *RNode) IsNilOrEmpty() bool
    func (rn *RNode) IsStringValue() bool
    func (rn *RNode) IsTaggedNull() bool
    func (rn *RNode) LoadMapIntoConfigMapBinaryData(m map[string]string) error
    func (rn *RNode) LoadMapIntoConfigMapData(m map[string]string) error
    func (rn *RNode) LoadMapIntoSecretData(m map[string]string) error
    func (rn *RNode) Map() (map[string]interface{}, error)
    func (rn *RNode) MarshalJSON() ([]byte, error)
    func (rn *RNode) MatchesAnnotationSelector(selector string) (bool, error)
    func (rn *RNode) MatchesLabelSelector(selector string) (bool, error)
    func (rn *RNode) MustString() string
    func (rn *RNode) Pipe(functions ...Filter) (*RNode, error)
    func (rn *RNode) PipeE(functions ...Filter) error
    func (rn *RNode) SetAnnotations(m map[string]string) error
    func (rn *RNode) SetApiVersion(av string)
    func (rn *RNode) SetBinaryDataMap(m map[string]string)
    func (rn *RNode) SetDataMap(m map[string]string)
    func (rn *RNode) SetKind(k string)
    func (rn *RNode) SetLabels(m map[string]string) error
    func (rn *RNode) SetMapField(value *RNode, path ...string) error
    func (rn *RNode) SetName(name string) error
    func (rn *RNode) SetNamespace(ns string) error
    func (rn *RNode) SetYNode(node *yaml.Node)
    func (rn *RNode) String() (string, error)
    func (rn *RNode) UnmarshalJSON(b []byte) error
    func (rn *RNode) VisitElements(fn func(node *RNode) error) error
    func (rn *RNode) VisitFields(fn func(node *MapNode) error) error
    func (rn *RNode) YNode() *yaml.Node
type ResourceIdentifier
    func (r *ResourceIdentifier) GetAPIVersion() string
    func (r *ResourceIdentifier) GetKind() string
    func (r *ResourceIdentifier) GetName() string
    func (r *ResourceIdentifier) GetNamespace() string
type ResourceMeta
    func (in *ResourceMeta) DeepCopy() *ResourceMeta
    func (in *ResourceMeta) DeepCopyInto(out *ResourceMeta)
    func (m *ResourceMeta) GetIdentifier() ResourceIdentifier
type SequenceIndentStyle
type Style
    func GetStyle(styles ...string) Style
type SuffixSetter
    func (s SuffixSetter) Filter(object *RNode) (*RNode, error)
type TeePiper
    func (t TeePiper) Filter(rn *RNode) (*RNode, error)
type TypeError
type TypeMeta
type Unmarshaler
type ValueReplacer
    func (s ValueReplacer) Filter(object *RNode) (*RNode, error)
type YFilter
    func (y YFilter) MarshalYAML() (interface{}, error)
    func (y *YFilter) UnmarshalYAML(unmarshal func(interface{}) error) error
type YFilters
    func (y YFilters) Filters() []Filter

Package files

alias.go compatibility.go const.go datamap.go doc.go filters.go fns.go kfns.go mapnode.go match.go order.go rnode.go types.go util.go

Constants

const (
    WideSequenceStyle    SequenceIndentStyle = "wide"
    CompactSequenceStyle SequenceIndentStyle = "compact"
    DefaultIndent                            = 2
    // BareSeqNodeWrappingKey kyaml uses reader annotations to track resources, it is not possible to
    // add them to bare sequence nodes, this key is used to wrap such bare
    // sequence nodes into map node, byteio_writer unwraps it while writing back
    BareSeqNodeWrappingKey = "bareSeqNodeWrappingKey"
)
const (
    // NodeTagNull is the tag set for a yaml.Document that contains no data;
    // e.g. it isn't a Map, Slice, Document, etc
    NodeTagNull   = "!!null"
    NodeTagFloat  = "!!float"
    NodeTagString = "!!str"
    NodeTagBool   = "!!bool"
    NodeTagInt    = "!!int"
    NodeTagMap    = "!!map"
    NodeTagSeq    = "!!seq"
    NodeTagEmpty  = ""
)

Field names

const (
    AnnotationsField = "annotations"
    APIVersionField  = "apiVersion"
    KindField        = "kind"
    MetadataField    = "metadata"
    DataField        = "data"
    BinaryDataField  = "binaryData"
    NameField        = "name"
    NamespaceField   = "namespace"
    LabelsField      = "labels"
)
const (
    Trim = "Trim"
    Flow = "Flow"
)
const (
    MergeTag = "!!merge"
)

Variables

var AliasNode yaml.Kind = yaml.AliasNode

AssociativeSequenceKeys is a map of paths to sequences that have associative keys. The order sets the precedence of the merge keys -- if multiple keys are present in Resources in a list, then the FIRST key which ALL elements in the list have is used as the associative key for merging that list. Only infer name as a merge key.

var AssociativeSequenceKeys = []string{"name"}

ConventionalContainerPaths is a list of paths at which containers typically appear in workload APIs. It is intended for use with LookupFirstMatch.

var ConventionalContainerPaths = [][]string{

    {"spec", "template", "spec", "containers"},

    {"spec", "jobTemplate", "spec", "template", "spec", "containers"},

    {"spec", "containers"},

    {"template", "spec", "containers"},
}
var DocumentNode yaml.Kind = yaml.DocumentNode
var DoubleQuotedStyle yaml.Style = yaml.DoubleQuotedStyle
var ErrMissingMetadata = fmt.Errorf("missing Resource metadata")

FieldOrder indexes fields and maps them to relative precedence

var FieldOrder = func() map[string]int {

    fo := map[string]int{}
    for i, f := range fieldSortOrder {
        fo[f] = i + 1
    }
    return fo
}()

Filters is the list of serializable Pipeline Filters

var Filters = map[string]func() Filter{
    "AnnotationClearer": func() Filter { return &AnnotationClearer{} },
    "AnnotationGetter":  func() Filter { return &AnnotationGetter{} },
    "AnnotationSetter":  func() Filter { return &AnnotationSetter{} },
    "LabelSetter":       func() Filter { return &LabelSetter{} },
    "ElementAppender":   func() Filter { return &ElementAppender{} },
    "ElementMatcher":    func() Filter { return &ElementMatcher{} },
    "FieldClearer":      func() Filter { return &FieldClearer{} },
    "FilterMatcher":     func() Filter { return &FilterMatcher{} },
    "FieldMatcher":      func() Filter { return &FieldMatcher{} },
    "FieldSetter":       func() Filter { return &FieldSetter{} },
    "PathGetter":        func() Filter { return &PathGetter{} },
    "PathMatcher":       func() Filter { return &PathMatcher{} },
    "Parser":            func() Filter { return &Parser{} },
    "PrefixSetter":      func() Filter { return &PrefixSetter{} },
    "ValueReplacer":     func() Filter { return &ValueReplacer{} },
    "SuffixSetter":      func() Filter { return &SuffixSetter{} },
    "TeePiper":          func() Filter { return &TeePiper{} },
}
var FlowStyle yaml.Style = yaml.FlowStyle
var FoldedStyle yaml.Style = yaml.FoldedStyle
var LiteralStyle yaml.Style = yaml.LiteralStyle
var MappingNode yaml.Kind = yaml.MappingNode
var Marshal = func(in interface{}) ([]byte, error) {
    var buf bytes.Buffer
    err := NewEncoder(&buf).Encode(in)
    if err != nil {
        return nil, err
    }
    return buf.Bytes(), nil
}
var NewDecoder = yaml.NewDecoder
var NewEncoder = func(w io.Writer) *yaml.Encoder {
    e := yaml.NewEncoder(w)
    e.SetIndent(DefaultIndent)
    e.CompactSeqIndent()
    return e
}
var ScalarNode yaml.Kind = yaml.ScalarNode
var SequenceNode yaml.Kind = yaml.SequenceNode
var SingleQuotedStyle yaml.Style = yaml.SingleQuotedStyle
var TaggedStyle yaml.Style = yaml.TaggedStyle
var Unmarshal = yaml.Unmarshal

WhitelistedListSortApis contains the set of apis that are whitelisted for sorting list field elements

var WhitelistedListSortApis = newSet(
    "apps/v1", "apps/v1beta1", "apps/v1beta2", "batch/v1", "batch/v1beta1",
    "extensions/v1beta1", "v1", "admissionregistration.k8s.io/v1")

WhitelistedListSortFields contains json paths to list fields that should be sorted, and the field they should be sorted by

var WhitelistedListSortFields = map[string]string{
    ".spec.template.spec.containers": "name",
    ".webhooks.rules.operations":     "",
}

WhitelistedListSortKinds contains the set of kinds that are whitelisted for sorting list field elements

var WhitelistedListSortKinds = newSet(
    "CronJob", "DaemonSet", "Deployment", "Job", "ReplicaSet", "StatefulSet",
    "ValidatingWebhookConfiguration")

func ClearEmptyAnnotations

func ClearEmptyAnnotations(rn *RNode) error

ClearEmptyAnnotations clears the keys, annotations and metadata if they are empty/null

func CopyYNode

func CopyYNode(n *yaml.Node) *yaml.Node

CopyYNode returns a distinct copy of its argument. Use https://github.com/jinzhu/copier instead?

func DeriveSeqIndentStyle

func DeriveSeqIndentStyle(originalYAML string) string

DeriveSeqIndentStyle derives the sequence indentation annotation value for the resource, originalYAML is the input yaml string, the style is decided by deriving the existing sequence indentation of first sequence node

func ErrorIfAnyInvalidAndNonNull

func ErrorIfAnyInvalidAndNonNull(kind yaml.Kind, rn ...*RNode) error

func ErrorIfInvalid

func ErrorIfInvalid(rn *RNode, kind yaml.Kind) error

func FormatNonStringStyle

func FormatNonStringStyle(node *Node, schema spec.Schema)

FormatNonStringStyle makes sure that values which parse as non-string values in yaml 1.1 are correctly formatted given the Schema type.

func GetValue

func GetValue(node *RNode) string

GetValue returns underlying yaml.Node Value field

func IsCreate

func IsCreate(kind yaml.Kind) bool

IsCreate returns true if kind is specified

func IsEmptyMap

func IsEmptyMap(node *RNode) bool

IsEmptyMap returns true if the RNode is an empty node or an empty map. TODO: make this a method on RNode.

func IsFoundOrError

func IsFoundOrError(rn *RNode, err error) bool

IsFoundOrError returns true if rn is found or err is non-nil

func IsIdxNumber

func IsIdxNumber(p string) bool

IsIdxNumber returns true if p is an index number. e.g. 1

func IsListIndex

func IsListIndex(p string) bool

IsListIndex returns true if p is an index into a Val. e.g. [fieldName=fieldValue] e.g. [=primitiveValue]

func IsMissingOrError

func IsMissingOrError(rn *RNode, err error) bool

IsMissingOrError returns true if rn is NOT found or err is non-nil

func IsMissingOrNull

func IsMissingOrNull(node *RNode) bool

IsMissingOrNull is true if the RNode is nil or explicitly tagged null. TODO: make this a method on RNode.

func IsValueNonString

func IsValueNonString(value string) bool

func IsWildcard

func IsWildcard(p string) bool

IsWildcard returns true if p is matching every elements. e.g. "*"

func IsYNodeEmptyDoc

func IsYNodeEmptyDoc(n *yaml.Node) bool

IsYNodeEmptyDoc is true if the node is a Document with no content. E.g.: "---\n---"

func IsYNodeEmptyMap

func IsYNodeEmptyMap(n *yaml.Node) bool

IsYNodeEmptyMap is true if the Node is a non-nil empty map.

func IsYNodeEmptySeq

func IsYNodeEmptySeq(n *yaml.Node) bool

IsYNodeEmptySeq is true if the Node is a non-nil empty sequence.

func IsYNodeNilOrEmpty

func IsYNodeNilOrEmpty(n *yaml.Node) bool

IsYNodeNilOrEmpty is true if the Node is nil or appears empty.

func IsYNodeString

func IsYNodeString(n *yaml.Node) bool

func IsYNodeTaggedNull

func IsYNodeTaggedNull(n *yaml.Node) bool

IsYNodeTaggedNull returns true if the node is explicitly tagged Null.

func IsYNodeZero

func IsYNodeZero(n *yaml.Node) bool

IsYNodeZero is true if all the public fields in the Node are empty. Which means it's not initialized and should be omitted when marshal. The Node itself has a method IsZero but it is not released in yaml.v3. https://pkg.go.dev/gopkg.in/yaml.v3#Node.IsZero

func IsYaml1_1NonString

func IsYaml1_1NonString(node *Node) bool

IsYaml1_1NonString returns true if the value parses as a non-string value in yaml 1.1 when unquoted.

Note: yaml 1.2 uses different keywords than yaml 1.1. Example: yaml 1.2 interprets `field: on` and `field: "on"` as equivalent (both strings). However Yaml 1.1 interprets `field: on` as on being a bool and `field: "on"` as on being a string. If an input is read with `field: "on"`, and the style is changed from DoubleQuote to 0, it will change the type of the field from a string to a bool. For this reason, fields which are keywords in yaml 1.1 should never have their style changed, as it would break backwards compatibility with yaml 1.1 -- which is what is used by the Kubernetes apiserver.

func MarshalWithOptions

func MarshalWithOptions(in interface{}, opts *EncoderOptions) ([]byte, error)

MarshalWithOptions marshals the input interface with provided options

func NewEncoderWithOptions

func NewEncoderWithOptions(w io.Writer, opts *EncoderOptions) *yaml.Encoder

NewEncoderWithOptions returns the encoder with provided options

func SetK8sName

func SetK8sName(value string) k8sMetaSetter

func SetK8sNamespace

func SetK8sNamespace(value string) k8sMetaSetter

func SortedMapKeys

func SortedMapKeys(m map[string]string) []string

SortedMapKeys returns a sorted slice of keys to the given map. Writing this function never gets old.

func SplitIndexNameValue

func SplitIndexNameValue(p string) (string, string, error)

SplitIndexNameValue splits a lookup part Val index into the field name and field value to match. e.g. splits [name=nginx] into (name, nginx) e.g. splits [=-jar] into ("", -jar)

func String

func String(node *yaml.Node, opts ...string) (string, error)

String returns a string value for a Node, applying the supplied formatting options

func SyncMapNodesOrder

func SyncMapNodesOrder(from, to *RNode)

SyncMapNodesOrder sorts the map node keys in 'to' node to match the order of map node keys in 'from' node, additional keys are moved to the end

func UpdateFile

func UpdateFile(filter Filter, path string) error

UpdateFile reads the file at path, applies the filter to it, and write the result back. path must contain a exactly 1 resource (YAML).

func WriteFile

func WriteFile(node *RNode, path string) error

WriteFile writes a single Resource to a yaml file

type AnnotationClearer

AnnotationClearer removes an annotation at metadata.annotations. Returns nil if the annotation or field does not exist.

type AnnotationClearer struct {
    Kind string `yaml:"kind,omitempty"`
    Key  string `yaml:"key,omitempty"`
}

func ClearAnnotation

func ClearAnnotation(key string) AnnotationClearer

func (AnnotationClearer) Filter

func (c AnnotationClearer) Filter(rn *RNode) (*RNode, error)

type AnnotationGetter

AnnotationGetter gets an annotation at metadata.annotations. Returns nil if metadata.annotations does not exist.

type AnnotationGetter struct {
    Kind  string `yaml:"kind,omitempty"`
    Key   string `yaml:"key,omitempty"`
    Value string `yaml:"value,omitempty"`
}

func GetAnnotation

func GetAnnotation(key string) AnnotationGetter

func (AnnotationGetter) Filter

func (g AnnotationGetter) Filter(rn *RNode) (*RNode, error)

AnnotationGetter returns the annotation value. Returns "", nil if the annotation does not exist.

type AnnotationSetter

AnnotationSetter sets an annotation at metadata.annotations. Creates metadata.annotations if does not exist.

type AnnotationSetter struct {
    Kind  string `yaml:"kind,omitempty"`
    Key   string `yaml:"key,omitempty"`
    Value string `yaml:"value,omitempty"`
}

func SetAnnotation

func SetAnnotation(key, value string) AnnotationSetter

func (AnnotationSetter) Filter

func (s AnnotationSetter) Filter(rn *RNode) (*RNode, error)

type Comments

Comments struct is comment yaml comment types

type Comments struct {
    LineComment string `yaml:"lineComment,omitempty"`
    HeadComment string `yaml:"headComment,omitempty"`
    FootComment string `yaml:"footComment,omitempty"`
}

type Decoder

type Decoder = yaml.Decoder

type ElementAppender

ElementAppender adds all element to a SequenceNode's Content. Returns Elements[0] if len(Elements) == 1, otherwise returns nil.

type ElementAppender struct {
    Kind string `yaml:"kind,omitempty"`

    // Elem is the value to append.
    Elements []*yaml.Node `yaml:"elements,omitempty"`
}

func Append

func Append(elements ...*yaml.Node) ElementAppender

Append creates an ElementAppender

Example (AppendMap)

Code:

obj, err := Parse(`
- name: foo
- name: bar
`)
if err != nil {
    log.Fatal(err)
}
elem, err := Parse("name: baz")
if err != nil {
    log.Fatal(err)
}
node, err := obj.Pipe(Append(elem.YNode()))
if err != nil {
    log.Fatal(err)
}

// Expect the node to contain the appended element because only
// 1 element was appended
fmt.Println(node.String())
fmt.Println(obj.String())

Output:

name: baz
 <nil>
- name: foo
- name: bar
- name: baz
 <nil>

Example (AppendScalars)

Code:

obj, err := Parse(`
- a
- b
`)
if err != nil {
    log.Fatal(err)
}
_, err = obj.Pipe(Append(&Node{Value: "c", Kind: ScalarNode}))
if err != nil {
    log.Fatal(err)
}
node, err := obj.Pipe(Append(
    &Node{Value: "c", Kind: ScalarNode},
    &Node{Value: "d", Kind: ScalarNode},
))
if err != nil {
    log.Fatal(err)
}
fmt.Println(node.String())
fmt.Println(obj.String())

Output:

 <nil>
- a
- b
- c
- c
- d
 <nil>

func (ElementAppender) Filter

func (a ElementAppender) Filter(rn *RNode) (*RNode, error)

type ElementIndexer

ElementIndexer picks the element with a specified index. Index starts from 0 to len(list) - 1. a hyphen ("-") means the last index.

type ElementIndexer struct {
    Index int
}

func GetElementByIndex

func GetElementByIndex(index int) ElementIndexer

GetElementByIndex will return a Filter which can be applied to a sequence node to get the element specified by the index

func (ElementIndexer) Filter

func (i ElementIndexer) Filter(rn *RNode) (*RNode, error)

Filter implements Filter

type ElementMatcher

ElementMatcher returns the first element from a Sequence matching the specified key-value pairs. If there's no match, and no configuration error, the matcher returns nil, nil.

type ElementMatcher struct {
    Kind string `yaml:"kind,omitempty"`

    // Keys are the list of fields upon which to match this element.
    Keys []string

    // Values are the list of values upon which to match this element.
    Values []string

    // Create will create the Element if it is not found
    Create *RNode `yaml:"create,omitempty"`

    // MatchAnyValue indicates that matcher should only consider the key and ignore
    // the actual value in the list. Values must be empty when MatchAnyValue is
    // set to true.
    MatchAnyValue bool `yaml:"noValue,omitempty"`
}

func GetElementByKey

func GetElementByKey(key string) ElementMatcher

func MatchElement

func MatchElement(field, value string) ElementMatcher

func MatchElementList

func MatchElementList(keys []string, values []string) ElementMatcher

func (ElementMatcher) Filter

func (e ElementMatcher) Filter(rn *RNode) (*RNode, error)

Example

Code:

obj, err := Parse(`
- a
- b
`)
if err != nil {
    log.Fatal(err)
}
elem, err := obj.Pipe(ElementMatcher{
    Values: []string{"c"}, Create: NewScalarRNode("c"),
})
if err != nil {
    log.Fatal(err)
}

fmt.Println(elem.String())
fmt.Println(obj.String())

Output:

c
 <nil>
- a
- b
- c
 <nil>

Example (ObjectFound)

Code:

obj, err := Parse(`
- name: foo
- name: bar
- name: baz
`)
if err != nil {
    log.Fatal(err)
}
toAppend, err := Parse(`
name: baz
image: nginx
`)
if err != nil {
    log.Fatal(err)
}
elem, err := obj.Pipe(ElementMatcher{
    Keys: []string{"name"}, Values: []string{"baz"}, Create: toAppend})
if err != nil {
    log.Fatal(err)
}
fmt.Println(elem.String())
fmt.Println(obj.String())

Output:

name: baz
 <nil>
- name: foo
- name: bar
- name: baz
 <nil>

Example (ObjectNotFound)

Code:

obj, err := Parse(`
- name: foo
- name: bar
`)
if err != nil {
    log.Fatal(err)
}
toAppend, err := Parse(`
name: baz
image: nginx
`)
if err != nil {
    log.Fatal(err)
}
elem, err := obj.Pipe(ElementMatcher{
    Keys: []string{"name"}, Values: []string{"baz"}, Create: toAppend})
if err != nil {
    log.Fatal(err)
}
fmt.Println(elem.String())
fmt.Println(obj.String())

Output:

name: baz
image: nginx
 <nil>
- name: foo
- name: bar
- name: baz
  image: nginx
 <nil>

Example (PrimitiveFound)

Code:

obj, err := Parse(`
- a
- b
- c
`)
if err != nil {
    log.Fatal(err)
}
elem, err := obj.Pipe(ElementMatcher{
    Keys:   []string{""},
    Values: []string{"c"},
    Create: NewScalarRNode("c"),
})
if err != nil {
    log.Fatal(err)
}
fmt.Println(elem.String())
fmt.Println(obj.String())

Output:

c
 <nil>
- a
- b
- c
 <nil>

type ElementSetter

ElementSetter sets the value for an Element in an associative list. ElementSetter will append, replace or delete an element in an associative list. To append, user a key-value pair that doesn't exist in the sequence. this behavior is intended to handle the case that not matching element found. It's not designed for this purpose. To append an element, please use ElementAppender. To replace, set the key-value pair and a non-nil Element. To delete, set the key-value pair and leave the Element as nil. Every key must have a corresponding value.

type ElementSetter struct {
    Kind string `yaml:"kind,omitempty"`

    // Element is the new value to set -- remove the existing element if nil
    Element *Node

    // Key is a list of fields on the elements. It is used to find matching elements to
    // update / delete
    Keys []string

    // Value is a list of field values on the elements corresponding to the keys. It is
    // used to find matching elements to update / delete.
    Values []string
}

func (ElementSetter) Filter

func (e ElementSetter) Filter(rn *RNode) (*RNode, error)

type Encoder

type Encoder = yaml.Encoder

type EncoderOptions

EncoderOptions are options that can be used to configure the encoder, do not expose new options without considerable justification

type EncoderOptions struct {
    // SeqIndent is the indentation style for YAML Sequence nodes
    SeqIndent SequenceIndentStyle
}

type FieldClearer

FieldClearer removes the field or map key. Returns a RNode with the removed field or map entry.

type FieldClearer struct {
    Kind string `yaml:"kind,omitempty"`

    // Name is the name of the field or key in the map.
    Name string `yaml:"name,omitempty"`

    IfEmpty bool `yaml:"ifEmpty,omitempty"`
}

func Clear

func Clear(name string) FieldClearer

Clear returns a FieldClearer

Example

Code:

obj, err := Parse(`
kind: Deployment
metadata:
  name: app
  annotations:
    a.b.c: d.e.f
    g: h
spec:
  template: {}
`)
if err != nil {
    log.Fatal(err)
}
node, err := obj.Pipe(Clear("metadata"))
if err != nil {
    log.Fatal(err)
}
fmt.Println(node.String())
fmt.Println(obj.String())

Output:

name: app
annotations:
  a.b.c: d.e.f
  g: h
 <nil>
kind: Deployment
spec:
  template: {}
 <nil>

func (FieldClearer) Filter

func (c FieldClearer) Filter(rn *RNode) (*RNode, error)

type FieldMatcher

FieldMatcher returns the value of a named field or map entry.

type FieldMatcher struct {
    Kind string `yaml:"kind,omitempty"`

    // Name of the field to return
    Name string `yaml:"name,omitempty"`

    // YNode of the field to return.
    // Optional.  Will only need to match field name if unset.
    Value *RNode `yaml:"value,omitempty"`

    StringValue string `yaml:"stringValue,omitempty"`

    StringRegexValue string `yaml:"stringRegexValue,omitempty"`

    // Create will cause the field to be created with this value
    // if it is set.
    Create *RNode `yaml:"create,omitempty"`
}

func Get

func Get(name string) FieldMatcher

Example

Code:

obj, err := Parse(`apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
  annotations:
    a.b.c: d.e.f
    g: h
spec:
  template: {}
`)
if err != nil {
    log.Fatal(err)
}
node, err := obj.Pipe(Get("metadata"))
if err != nil {
    log.Fatal(err)
}
fmt.Println(node.String())
fmt.Println(obj.String())

Output:

name: app
annotations:
  a.b.c: d.e.f
  g: h
 <nil>
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
  annotations:
    a.b.c: d.e.f
    g: h
spec:
  template: {}
 <nil>

Example (NotFound)

Code:

obj, err := Parse(`apiVersion: apps/v1
kind: Deployment
spec:
  template: {}
`)
if err != nil {
    log.Fatal(err)
}
node, err := obj.Pipe(FieldMatcher{Name: "metadata"})
if err != nil {
    log.Fatal(err)
}
fmt.Println(node.String())
fmt.Println(obj.String())

Output:

 <nil>
apiVersion: apps/v1
kind: Deployment
spec:
  template: {}
 <nil>

func Match

func Match(value string) FieldMatcher

func MatchField

func MatchField(name, value string) FieldMatcher

func (FieldMatcher) Filter

func (f FieldMatcher) Filter(rn *RNode) (*RNode, error)

Example

Code:

obj, err := Parse(`
kind: Deployment
spec:
  template: {}
`)
if err != nil {
    log.Fatal(err)
}
value, err := Parse(`
name: app
annotations:
  a.b.c: d.e.f
  g: h
`)
if err != nil {
    log.Fatal(err)
}
elem, err := obj.Pipe(FieldMatcher{
    Name: "metadata", Value: value, Create: value})
if err != nil {
    log.Fatal(err)
}
fmt.Println(elem.String())
fmt.Println(obj.String())

Output:

name: app
annotations:
  a.b.c: d.e.f
  g: h
 <nil>
kind: Deployment
spec:
  template: {}
metadata:
  name: app
  annotations:
    a.b.c: d.e.f
    g: h
 <nil>

type FieldSetter

FieldSetter sets a field or map entry to a value.

type FieldSetter struct {
    Kind string `yaml:"kind,omitempty"`

    // Name is the name of the field or key to lookup in a MappingNode.
    // If Name is unspecified, and the input is a ScalarNode, FieldSetter will set the
    // value on the ScalarNode.
    Name string `yaml:"name,omitempty"`

    // Comments for the field
    Comments Comments `yaml:"comments,omitempty"`

    // Value is the value to set.
    // Optional if Kind is set.
    Value *RNode `yaml:"value,omitempty"`

    StringValue string `yaml:"stringValue,omitempty"`

    // OverrideStyle can be set to override the style of the existing node
    // when setting it.  Otherwise, if an existing node is found, the style is
    // retained.
    OverrideStyle bool `yaml:"overrideStyle,omitempty"`

    // AppendKeyStyle defines the style of the key when no existing node is
    // found, and a new node is appended.
    AppendKeyStyle Style `yaml:"appendKeyStyle,omitempty"`
}

func Set

func Set(value *RNode) FieldSetter

func SetField

func SetField(name string, value *RNode) FieldSetter

Example

Code:

obj, err := Parse(`apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
`)
if err != nil {
    log.Fatal(err)
}

containers, err := Parse(`
- name: nginx # first container
  image: nginx
- name: nginx2 # second container
  image: nginx2
`)
if err != nil {
    log.Fatal(err)
}

_, err = obj.Pipe(
    LookupCreate(MappingNode, "spec", "template", "spec"),
    SetField("containers", containers))
if err != nil {
    log.Fatal(err)
}

fmt.Println(obj.String())

Output:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
spec:
  template:
    spec:
      containers:
      - name: nginx # first container
        image: nginx
      - name: nginx2 # second container
        image: nginx2
 <nil>

Example (StringValue)

Code:

obj, err := Parse(`apiVersion: apps/v1
kind: Deployment
metadata:
 name: app
`)
if err != nil {
    log.Fatal(err)
}
_, err = obj.Pipe(SetField("foo", NewScalarRNode("bar")))
if err != nil {
    log.Fatal(err)
}

fmt.Println(obj.String())

Output:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
foo: bar
 <nil>

Example (StringValueOverwrite)

Code:

obj, err := Parse(`apiVersion: apps/v1
kind: Deployment
metadata:
   name: app
foo: baz
`)
if err != nil {
    // handle error
}
// set metadata.annotations.foo = bar
_, err = obj.Pipe(SetField("foo", NewScalarRNode("bar")))
if err != nil {
    // handle error
}

fmt.Println(obj.String())

Output:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
foo: bar
 <nil>

func (FieldSetter) Filter

func (s FieldSetter) Filter(rn *RNode) (*RNode, error)

type Filter

Filter defines a function to manipulate an individual RNode such as by changing its values, or returning a field.

When possible, Filters should be serializable to yaml so that they can be described declaratively as data.

Analogous to http://www.linfo.org/filters.html

type Filter interface {
    Filter(object *RNode) (*RNode, error)
}

func LookupFirstMatch

func LookupFirstMatch(paths [][]string) Filter

LookupFirstMatch returns a Filter for locating a value that may exist at one of several possible paths. For example, it can be used with ConventionalContainerPaths to find the containers field in a standard workload resource. If more than one of the paths exists in the resource, the first will be returned. If none exist, nil will be returned. If an error is encountered during lookup, it will be returned.

func Tee

func Tee(filters ...Filter) Filter

Tee calls the provided Filters, and returns its argument rather than the result of the filters. May be used to fork sub-filters from a call. e.g. locate field, set value; locate another field, set another value

Example

Code:

obj, err := Parse(`apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
`)
if err != nil {
    // handle error
}
// set metadata.annotations.foo = bar
_, err = obj.Pipe(
    Lookup("spec", "template", "spec", "containers", "[name=nginx]"),
    Tee(SetField("filter", NewListRNode("foo"))),
    SetField("args", NewListRNode("baz", "bar")))
if err != nil {
    // handle error
}

fmt.Println(obj.String())

Output:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
        filter:
        - foo
        args:
        - baz
        - bar
 <nil>

type FilterFunc

type FilterFunc func(object *RNode) (*RNode, error)

func (FilterFunc) Filter

func (f FilterFunc) Filter(object *RNode) (*RNode, error)

type FilterMatcher

type FilterMatcher struct {
    Kind string `yaml:"kind"`

    // Filters are the set of Filters run by TeePiper.
    Filters YFilters `yaml:"pipeline,omitempty"`
}

func (FilterMatcher) Filter

func (t FilterMatcher) Filter(rn *RNode) (*RNode, error)

type InvalidNodeKindError

type InvalidNodeKindError struct {
    // contains filtered or unexported fields
}

func (*InvalidNodeKindError) ActualNodeKind

func (e *InvalidNodeKindError) ActualNodeKind() Kind

func (*InvalidNodeKindError) Error

func (e *InvalidNodeKindError) Error() string

type IsZeroer

type IsZeroer = yaml.IsZeroer

type Kind

type Kind = yaml.Kind

type LabelSetter

LabelSetter sets a label at metadata.labels. Creates metadata.labels if does not exist.

type LabelSetter struct {
    Kind  string `yaml:"kind,omitempty"`
    Key   string `yaml:"key,omitempty"`
    Value string `yaml:"value,omitempty"`
}

func SetLabel

func SetLabel(key, value string) LabelSetter

func (LabelSetter) Filter

func (s LabelSetter) Filter(rn *RNode) (*RNode, error)

type MapEntrySetter

MapEntrySetter sets a map entry to a value. If it finds a key with the same value, it will override both Key and Value RNodes, including style and any other metadata. If it doesn't find the key, it will insert a new map entry. It will set the field, even if it's empty or nil, unlike the FieldSetter. This is useful for rebuilding some pre-existing RNode structure.

type MapEntrySetter struct {
    // Name is the name of the field or key to lookup in a MappingNode.
    // If Name is unspecified, it will use the Key's Value
    Name string `yaml:"name,omitempty"`

    // Value is the value to set.
    Value *RNode `yaml:"value,omitempty"`

    // Key is the map key to set.
    Key *RNode `yaml:"key,omitempty"`
}

func (MapEntrySetter) Filter

func (s MapEntrySetter) Filter(rn *RNode) (*RNode, error)

type MapNode

MapNode wraps a field key and value.

type MapNode struct {
    Key   *RNode
    Value *RNode
}

func (*MapNode) IsNilOrEmpty

func (mn *MapNode) IsNilOrEmpty() bool

IsNilOrEmpty returns true if the MapNode is nil, has no value, or has a value that appears empty.

type MapNodeSlice

type MapNodeSlice []*MapNode

func (MapNodeSlice) Keys

func (m MapNodeSlice) Keys() []*RNode

func (MapNodeSlice) Values

func (m MapNodeSlice) Values() []*RNode

type Marshaler

type Marshaler = yaml.Marshaler

type MergeOptions

MergeOptions is a struct which contains the options for merge

type MergeOptions struct {
    // ListIncreaseDirection indicates should merge function prepend the items from
    // source list to destination or append.
    ListIncreaseDirection MergeOptionsListIncreaseDirection
}

type MergeOptionsListIncreaseDirection

MergeOptionsListIncreaseDirection is the type of list growth in merge

type MergeOptionsListIncreaseDirection int
const (
    MergeOptionsListAppend MergeOptionsListIncreaseDirection = iota
    MergeOptionsListPrepend
)

type NameMeta

NameMeta contains name information.

type NameMeta struct {
    // Name is the metadata.name field of a Resource
    Name string `json:"name,omitempty" yaml:"name,omitempty"`
    // Namespace is the metadata.namespace field of a Resource
    Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`
}

type NoFieldError

type NoFieldError struct {
    Field string
}

func (NoFieldError) Error

func (e NoFieldError) Error() string

type Node

type Node = yaml.Node

type ObjectMeta

ObjectMeta contains metadata about a Resource

type ObjectMeta struct {
    NameMeta `json:",inline" yaml:",inline"`
    // Labels is the metadata.labels field of a Resource
    Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
    // Annotations is the metadata.annotations field of a Resource.
    Annotations map[string]string `json:"annotations,omitempty" yaml:"annotations,omitempty"`
}

func (*ObjectMeta) DeepCopy

func (in *ObjectMeta) DeepCopy() *ObjectMeta

DeepCopy copies the receiver, creating a new ObjectMeta.

func (*ObjectMeta) DeepCopyInto

func (in *ObjectMeta) DeepCopyInto(out *ObjectMeta)

DeepCopyInto copies the receiver, writing into out. in must be non-nil.

type Parser

Parser parses values into configuration.

type Parser struct {
    Kind  string `yaml:"kind,omitempty"`
    Value string `yaml:"value,omitempty"`
}

func (Parser) Filter

func (p Parser) Filter(_ *RNode) (*RNode, error)

type PathGetter

PathGetter returns the RNode under Path.

type PathGetter struct {
    Kind string `yaml:"kind,omitempty"`

    // Path is a slice of parts leading to the RNode to lookup.
    // Each path part may be one of:
    // * FieldMatcher -- e.g. "spec"
    // * Map Key -- e.g. "app.k8s.io/version"
    // * List Entry -- e.g. "[name=nginx]" or "[=-jar]" or "0" or "-"
    //
    // Map Keys and Fields are equivalent.
    // See FieldMatcher for more on Fields and Map Keys.
    //
    // List Entries can be specified as map entry to match [fieldName=fieldValue]
    // or a positional index like 0 to get the element. - (unquoted hyphen) is
    // special and means the last element.
    //
    // See Elem for more on List Entries.
    //
    // Examples:
    // * spec.template.spec.container with matching name: [name=nginx]
    // * spec.template.spec.container.argument matching a value: [=-jar]
    Path []string `yaml:"path,omitempty"`

    // Create will cause missing path parts to be created as they are walked.
    //
    // * The leaf Node (final path) will be created with a Kind matching Create
    // * Intermediary Nodes will be created as either a MappingNodes or
    //   SequenceNodes as appropriate for each's Path location.
    // * If a list item is specified by a index (an offset or "-"), this item will
    //   not be created even Create is set.
    Create yaml.Kind `yaml:"create,omitempty"`

    // Style is the style to apply to created value Nodes.
    // Created key Nodes keep an unspecified Style.
    Style yaml.Style `yaml:"style,omitempty"`
}

func Lookup

func Lookup(path ...string) PathGetter

Lookup returns a PathGetter to lookup a field by its path.

Example (Element)

Code:

obj, err := Parse(`apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
  name: app
spec:
  templates:
    spec:
      containers:
      - name: nginx
        image: nginx:latest
`)
if err != nil {
    log.Fatal(err)
}
value, err := obj.Pipe(Lookup(
    "spec", "templates", "spec", "containers", "[name=nginx]"))
if err != nil {
    log.Fatal(err)
}

fmt.Println(value.String())

Output:

name: nginx
image: nginx:latest
 <nil>

Example (NotFound)

Code:

obj, err := Parse(`
kind: Deployment
metadata:
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
  name: app
`)
if err != nil {
    log.Fatal(err)
}
rs, err := obj.Pipe(Lookup("spec", "templates", "spec"))
if err != nil {
    log.Fatal(err)
}

fmt.Println(rs)
fmt.Println("---")
fmt.Println(obj.String())

Output:

 <nil>
---
kind: Deployment
metadata:
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
  name: app
 <nil>

Example (Scalar)

Code:

obj, err := Parse(`apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
  name: app
spec:
  templates:
    spec:
      containers:
      - name: nginx
        image: nginx:latest
`)
if err != nil {
    log.Fatal(err)
}
value, err := obj.Pipe(Lookup(
    "spec", "templates", "spec", "containers", "[name=nginx]", "image"))
if err != nil {
    log.Fatal(err)
}

fmt.Println(value.String())

Output:

nginx:latest
 <nil>

Example (Sequence)

Code:

obj, err := Parse(`apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
     app: java
  annotations:
    a.b.c: d.e.f
  name: app
spec:
  templates:
    spec:
      containers:
      - name: nginx
        image: nginx:latest
`)
if err != nil {
    log.Fatal(err)
}
value, err := obj.Pipe(Lookup(
    "spec", "templates", "spec", "containers"))
if err != nil {
    log.Fatal(err)
}

fmt.Println(value.String())

Output:

- name: nginx
  image: nginx:latest
 <nil>

func LookupCreate

func LookupCreate(kind yaml.Kind, path ...string) PathGetter

LookupCreate returns a PathGetter to lookup a field by its path and create it if it doesn't already exist.

Example (Element)

Code:

obj, err := Parse(`
kind: Deployment
metadata:
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
  name: app
`)
if err != nil {
    log.Fatal(err)
}
rs, err := obj.Pipe(LookupCreate(
    MappingNode, "spec", "templates", "spec", "containers", "[name=nginx]"))
if err != nil {
    log.Fatal(err)
}

fmt.Println(rs.String())
fmt.Println("---")
fmt.Println(obj.String())

Output:

name: nginx
 <nil>
---
kind: Deployment
metadata:
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
  name: app
spec:
  templates:
    spec:
      containers:
      - name: nginx
 <nil>

Example (Object)

Code:

obj, err := Parse(`
kind: Deployment
metadata:
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
  name: app
`)
if err != nil {
    log.Fatal(err)
}
rs, err := obj.Pipe(LookupCreate(
    MappingNode, "spec", "templates", "spec"))
if err != nil {
    log.Fatal(err)
}

fmt.Println(rs.String())
fmt.Println("---")
fmt.Println(obj.String())

Output:

{}
 <nil>
---
kind: Deployment
metadata:
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
  name: app
spec:
  templates:
    spec: {}
 <nil>

Example (Sequence)

Code:

obj, err := Parse(`
kind: Deployment
metadata:
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
  name: app
`)
if err != nil {
    log.Fatal(err)
}
rs, err := obj.Pipe(LookupCreate(
    SequenceNode, "spec", "templates", "spec", "containers"))
if err != nil {
    log.Fatal(err)
}

fmt.Println(rs.String())
fmt.Println("---")
fmt.Println(obj.String())

Output:

[]
 <nil>
---
kind: Deployment
metadata:
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
  name: app
spec:
  templates:
    spec:
      containers: []
 <nil>

func (PathGetter) Filter

func (l PathGetter) Filter(rn *RNode) (*RNode, error)

Example

Code:

obj, err := Parse(`
kind: Deployment
metadata:
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
  name: app
`)
if err != nil {
    log.Fatal(err)
}
rs, err := obj.Pipe(PathGetter{
    Path:   []string{"spec", "templates", "spec", "containers", "[name=nginx]", "image"},
    Create: ScalarNode,
})
if err != nil {
    log.Fatal(err)
}
rs.Document().Style = SingleQuotedStyle

fmt.Println(rs.String())
fmt.Println("---")
fmt.Println(obj.String())

Output:

''
 <nil>
---
kind: Deployment
metadata:
  labels:
    app: java
  annotations:
    a.b.c: d.e.f
  name: app
spec:
  templates:
    spec:
      containers:
      - name: nginx
        image: ''
 <nil>

type PathMatcher

PathMatcher returns all RNodes matching the path wrapped in a SequenceNode. Lists may have multiple elements matching the path, and each matching element is added to the return result. If Path points to a SequenceNode, the SequenceNode is wrapped in another SequenceNode If Path does not contain any lists, the result is still wrapped in a SequenceNode of len == 1

type PathMatcher struct {
    Kind string `yaml:"kind,omitempty"`

    // Path is a slice of parts leading to the RNode to lookup.
    // Each path part may be one of:
    // * FieldMatcher -- e.g. "spec"
    // * Map Key -- e.g. "app.k8s.io/version"
    // * List Entry -- e.g. "[name=nginx]" or "[=-jar]" or "0"
    //
    // Map Keys and Fields are equivalent.
    // See FieldMatcher for more on Fields and Map Keys.
    //
    // List Entries are specified as map entry to match [fieldName=fieldValue].
    // See Elem for more on List Entries.
    //
    // Examples:
    // * spec.template.spec.container with matching name: [name=nginx] -- match 'name': 'nginx'
    // * spec.template.spec.container.argument matching a value: [=-jar] -- match '-jar'
    Path []string `yaml:"path,omitempty"`

    // Matches is set by PathMatch to publish the matched element values for each node.
    // After running  PathMatcher.Filter, each node from the SequenceNode result may be
    // looked up in Matches to find the field values that were matched.
    Matches map[*Node][]string

    // StripComments may be set to remove the comments on the matching Nodes.
    // This is useful for if the nodes are to be printed in FlowStyle.
    StripComments bool

    // Create will cause missing path parts to be created as they are walked.
    //
    // * The leaf Node (final path) will be created with a Kind matching Create
    // * Intermediary Nodes will be created as either a MappingNodes or
    //   SequenceNodes as appropriate for each's Path location.
    // * Nodes identified by an index will only be created if the index indicates
    //   an append operation (i.e. index=len(list))
    Create yaml.Kind `yaml:"create,omitempty"`
    // contains filtered or unexported fields
}

func (*PathMatcher) Filter

func (p *PathMatcher) Filter(rn *RNode) (*RNode, error)

type PrefixSetter

type PrefixSetter struct {
    Kind string `yaml:"kind"`

    Value string `yaml:"value"`
}

func (PrefixSetter) Filter

func (s PrefixSetter) Filter(object *RNode) (*RNode, error)

type RNode

RNode provides functions for manipulating Kubernetes Resources Objects unmarshalled into *yaml.Nodes

type RNode struct {

    // Whether we should keep this node, even if otherwise we would clear it
    ShouldKeep bool

    Match []string
    // contains filtered or unexported fields
}

func ConvertJSONToYamlNode

func ConvertJSONToYamlNode(jsonStr string) (*RNode, error)

ConvertJSONToYamlNode parses input json string and returns equivalent yaml node

func FromMap

func FromMap(m map[string]interface{}) (*RNode, error)

func MakeNullNode

func MakeNullNode() *RNode

MakeNullNode returns an RNode that represents an empty document.

func MakePersistentNullNode

func MakePersistentNullNode(value string) *RNode

MakePersistentNullNode returns an RNode that should be persisted, even when merging

func MustParse

func MustParse(value string) *RNode

MustParse parses a yaml string into an *RNode and panics if there is an error

func NewListRNode

func NewListRNode(values ...string) *RNode

NewListRNode returns a new List *RNode containing the provided scalar values.

func NewMapRNode

func NewMapRNode(values *map[string]string) *RNode

NewMapRNode returns a new Map *RNode containing the provided values

func NewRNode

func NewRNode(value *yaml.Node) *RNode

NewRNode returns a new RNode pointer containing the provided Node.

func NewScalarRNode

func NewScalarRNode(value string) *RNode

NewScalarRNode returns a new Scalar *RNode containing the provided scalar value.

func NewStringRNode

func NewStringRNode(value string) *RNode

NewStringRNode returns a new Scalar *RNode containing the provided string. If the string is non-utf8, it will be base64 encoded, and the tag will indicate binary data.

func Parse

func Parse(value string) (*RNode, error)

Parse parses a yaml string into an *RNode. To parse multiple resources, consider a kio.ByteReader

func ReadFile

func ReadFile(path string) (*RNode, error)

ReadFile parses a single Resource from a yaml file. To parse multiple resources, consider a kio.ByteReader

func (*RNode) AppendToFieldPath

func (rn *RNode) AppendToFieldPath(parts ...string)

AppendToFieldPath appends a field name to the FieldPath.

func (*RNode) Content

func (rn *RNode) Content() []*yaml.Node

Content returns Node Content field.

func (*RNode) Copy

func (rn *RNode) Copy() *RNode

Copy returns a distinct copy.

func (*RNode) DeAnchor

func (rn *RNode) DeAnchor() (err error)

DeAnchor inflates all YAML aliases with their anchor values. All YAML anchor data is permanently removed (feel free to call Copy first).

func (*RNode) Document

func (rn *RNode) Document() *yaml.Node

Document returns the Node for the value.

func (*RNode) Element

func (rn *RNode) Element(key, value string) *RNode

Element returns the element in the list which contains the field matching the value. Returns nil for non-SequenceNodes or if no Element matches.

func (*RNode) ElementList

func (rn *RNode) ElementList(keys []string, values []string) *RNode

ElementList returns the element in the list in which all fields keys[i] matches all corresponding values[i]. Returns nil for non-SequenceNodes or if no Element matches.

func (*RNode) ElementValues

func (rn *RNode) ElementValues(key string) ([]string, error)

ElementValues returns a list of all observed values for a given field name in a list of elements. Returns error for non-SequenceNodes.

Example

Code:

resource, err := Parse(`
- name: foo
  args: ['run.sh']
- name: bar
  args: ['run.sh']
- name: baz
  args: ['run.sh']
`)
if err != nil {
    log.Fatal(err)
}

fmt.Println(resource.ElementValues("name"))

Output:

[foo bar baz] <nil>

func (*RNode) ElementValuesList

func (rn *RNode) ElementValuesList(keys []string) ([][]string, error)

ElementValuesList returns a list of lists, where each list is a set of values corresponding to each key in keys. Returns error for non-SequenceNodes.

func (*RNode) Elements

func (rn *RNode) Elements() ([]*RNode, error)

Elements returns the list of elements in the RNode. Returns an error for non-SequenceNodes.

Example

Code:

resource, err := Parse(`
- name: foo
  args: ['run.sh']
- name: bar
  args: ['run.sh']
- name: baz
  args: ['run.sh']
`)
if err != nil {
    log.Fatal(err)
}
elements, err := resource.Elements()
if err != nil {
    log.Fatal(err)
}
for i, e := range elements {
    fmt.Printf("Element: %d\n", i)
    fmt.Println(e.MustString())
}

Output:

Element: 0
name: foo
args: ['run.sh']

Element: 1
name: bar
args: ['run.sh']

Element: 2
name: baz
args: ['run.sh']

func (*RNode) Field

func (rn *RNode) Field(field string) *MapNode

Field returns a fieldName, fieldValue pair for MappingNodes. Returns nil for non-MappingNodes.

func (*RNode) FieldPath

func (rn *RNode) FieldPath() []string

FieldPath returns the field path from the Resource root node, to rn. Does not include list indexes.

func (*RNode) FieldRNodes

func (rn *RNode) FieldRNodes() ([]*RNode, error)

FieldRNodes returns the list of field key RNodes for a MappingNode. Returns an error for non-MappingNodes.

func (*RNode) Fields

func (rn *RNode) Fields() ([]string, error)

Fields returns the list of field names for a MappingNode. Returns an error for non-MappingNodes.

func (*RNode) GetAnnotations

func (rn *RNode) GetAnnotations(annotations ...string) map[string]string

GetAnnotations gets the metadata annotations field. If the annotations field is missing, returns an empty map. Use another method to check for missing metadata. If specific annotations are provided, then the map is restricted to only those entries with keys that match one of the specific annotations. If no annotations are provided, then the map will contain all entries.

func (*RNode) GetApiVersion

func (rn *RNode) GetApiVersion() string

GetApiVersion returns the apiversion, if it exists, else empty string.

func (*RNode) GetAssociativeKey

func (rn *RNode) GetAssociativeKey() string

GetAssociativeKey returns the AssociativeSequenceKey used to merge the elements in the SequenceNode, or "" if the list is not associative.

func (*RNode) GetBinaryDataMap

func (rn *RNode) GetBinaryDataMap() map[string]string

func (*RNode) GetDataMap

func (rn *RNode) GetDataMap() map[string]string

func (*RNode) GetFieldValue

func (rn *RNode) GetFieldValue(path string) (interface{}, error)

GetFieldValue finds period delimited fields. TODO: When doing kustomize var replacement, which is likely a a primary use of this function and the reason it returns interface{} rather than string, we do conversion from Nodes to Go types and back to nodes. We should figure out how to do replacement using raw nodes, assuming we keep the var feature in kustomize. The other end of this is: refvar.go:updateNodeValue.

func (*RNode) GetKind

func (rn *RNode) GetKind() string

GetKind returns the kind, if it exists, else empty string.

func (*RNode) GetLabels

func (rn *RNode) GetLabels(labels ...string) map[string]string

GetLabels gets the metadata labels field. If the labels field is missing, returns an empty map. Use another method to check for missing metadata. If specific labels are provided, then the map is restricted to only those entries with keys that match one of the specific labels. If no labels are provided, then the map will contain all entries.

func (*RNode) GetMeta

func (rn *RNode) GetMeta() (ResourceMeta, error)

GetMeta returns the ResourceMeta for an RNode

func (*RNode) GetName

func (rn *RNode) GetName() string

GetName returns the name, or empty string if field not found. The setter is more restrictive.

func (*RNode) GetNamespace

func (rn *RNode) GetNamespace() string

GetNamespace gets the metadata namespace field, or empty string if field not found. The setter is more restrictive.

func (*RNode) GetSlice

func (rn *RNode) GetSlice(path string) ([]interface{}, error)

GetSlice returns the contents of the slice field at the given path.

func (*RNode) GetString

func (rn *RNode) GetString(path string) (string, error)

GetString returns the contents of the string field at the given path.

func (*RNode) GetValidatedDataMap

func (rn *RNode) GetValidatedDataMap(expectedKeys []string) (map[string]string, error)

GetValidatedDataMap retrieves the data map and returns an error if the data map contains entries which are not included in the expectedKeys set.

func (*RNode) GetValidatedMetadata

func (rn *RNode) GetValidatedMetadata() (ResourceMeta, error)

GetValidatedMetadata returns metadata after subjecting it to some tests.

func (*RNode) HasNilEntryInList

func (rn *RNode) HasNilEntryInList() (bool, string)

HasNilEntryInList returns true if the RNode contains a list which has a nil item, along with the path to the missing item. TODO(broken): This doesn't do what it claims to do. (see TODO in unit test and pr 1513).

func (*RNode) IsAssociative

func (rn *RNode) IsAssociative() bool

IsAssociative returns true if the RNode contains an AssociativeSequenceKey as a field.

func (*RNode) IsNil

func (rn *RNode) IsNil() bool

IsNil is true if the node is nil, or its underlying YNode is nil.

func (*RNode) IsNilOrEmpty

func (rn *RNode) IsNilOrEmpty() bool

IsNilOrEmpty is true if the node is nil, has no YNode, or has YNode that appears empty.

func (*RNode) IsStringValue

func (rn *RNode) IsStringValue() bool

IsStringValue is true if the RNode is not nil and is scalar string node

func (*RNode) IsTaggedNull

func (rn *RNode) IsTaggedNull() bool

IsTaggedNull is true if a non-nil node is explicitly tagged Null.

func (*RNode) LoadMapIntoConfigMapBinaryData

func (rn *RNode) LoadMapIntoConfigMapBinaryData(m map[string]string) error

func (*RNode) LoadMapIntoConfigMapData

func (rn *RNode) LoadMapIntoConfigMapData(m map[string]string) error

func (*RNode) LoadMapIntoSecretData

func (rn *RNode) LoadMapIntoSecretData(m map[string]string) error

func (*RNode) Map

func (rn *RNode) Map() (map[string]interface{}, error)

func (*RNode) MarshalJSON

func (rn *RNode) MarshalJSON() ([]byte, error)

MarshalJSON creates a byte slice from the RNode.

func (*RNode) MatchesAnnotationSelector

func (rn *RNode) MatchesAnnotationSelector(selector string) (bool, error)

MatchesAnnotationSelector returns true on a selector match to annotations.

func (*RNode) MatchesLabelSelector

func (rn *RNode) MatchesLabelSelector(selector string) (bool, error)

MatchesLabelSelector returns true on a selector match to labels.

func (*RNode) MustString

func (rn *RNode) MustString() string

MustString returns string representation of the RNode or panics if there is an error

func (*RNode) Pipe

func (rn *RNode) Pipe(functions ...Filter) (*RNode, error)

Pipe sequentially invokes each Filter, and passes the result to the next Filter.

Analogous to http://www.linfo.org/pipes.html

* rn is provided as input to the first Filter. * if any Filter returns an error, immediately return the error * if any Filter returns a nil RNode, immediately return nil, nil * if all Filters succeed with non-empty results, return the final result

func (*RNode) PipeE

func (rn *RNode) PipeE(functions ...Filter) error

PipeE runs Pipe, dropping the *RNode return value. Useful for directly returning the Pipe error value from functions.

func (*RNode) SetAnnotations

func (rn *RNode) SetAnnotations(m map[string]string) error

SetAnnotations tries to set the metadata annotations field.

func (*RNode) SetApiVersion

func (rn *RNode) SetApiVersion(av string)

SetApiVersion sets the apiVersion.

func (*RNode) SetBinaryDataMap

func (rn *RNode) SetBinaryDataMap(m map[string]string)

func (*RNode) SetDataMap

func (rn *RNode) SetDataMap(m map[string]string)

func (*RNode) SetKind

func (rn *RNode) SetKind(k string)

SetKind sets the kind.

func (*RNode) SetLabels

func (rn *RNode) SetLabels(m map[string]string) error

SetLabels sets the metadata labels field.

func (*RNode) SetMapField

func (rn *RNode) SetMapField(value *RNode, path ...string) error

func (*RNode) SetName

func (rn *RNode) SetName(name string) error

SetName sets the metadata name field.

func (*RNode) SetNamespace

func (rn *RNode) SetNamespace(ns string) error

SetNamespace tries to set the metadata namespace field. If the argument is empty, the field is dropped.

func (*RNode) SetYNode

func (rn *RNode) SetYNode(node *yaml.Node)

SetYNode sets the yaml.Node value on an RNode.

func (*RNode) String

func (rn *RNode) String() (string, error)

String returns string representation of the RNode

func (*RNode) UnmarshalJSON

func (rn *RNode) UnmarshalJSON(b []byte) error

UnmarshalJSON overwrites this RNode with data from []byte.

func (*RNode) VisitElements

func (rn *RNode) VisitElements(fn func(node *RNode) error) error

VisitElements calls fn for each element in a SequenceNode. Returns an error for non-SequenceNodes

func (*RNode) VisitFields

func (rn *RNode) VisitFields(fn func(node *MapNode) error) error

VisitFields calls fn for each field in the RNode. Returns an error for non-MappingNodes.

func (*RNode) YNode

func (rn *RNode) YNode() *yaml.Node

YNode returns the yaml.Node value. If the yaml.Node value is a DocumentNode, YNode will return the DocumentNode Content entry instead of the DocumentNode.

type ResourceIdentifier

ResourceIdentifier contains the information needed to uniquely identify a resource in a cluster.

type ResourceIdentifier struct {
    TypeMeta `json:",inline" yaml:",inline"`
    NameMeta `json:",inline" yaml:",inline"`
}

func (*ResourceIdentifier) GetAPIVersion

func (r *ResourceIdentifier) GetAPIVersion() string

func (*ResourceIdentifier) GetKind

func (r *ResourceIdentifier) GetKind() string

func (*ResourceIdentifier) GetName

func (r *ResourceIdentifier) GetName() string

func (*ResourceIdentifier) GetNamespace

func (r *ResourceIdentifier) GetNamespace() string

type ResourceMeta

ResourceMeta contains the metadata for a both Resource Type and Resource.

type ResourceMeta struct {
    TypeMeta `json:",inline" yaml:",inline"`
    // ObjectMeta is the metadata field of a Resource
    ObjectMeta `json:"metadata,omitempty" yaml:"metadata,omitempty"`
}

func (*ResourceMeta) DeepCopy

func (in *ResourceMeta) DeepCopy() *ResourceMeta

DeepCopy copies the receiver, creating a new ResourceMeta.

func (*ResourceMeta) DeepCopyInto

func (in *ResourceMeta) DeepCopyInto(out *ResourceMeta)

DeepCopyInto copies the receiver, writing into out. in must be non-nil.

func (*ResourceMeta) GetIdentifier

func (m *ResourceMeta) GetIdentifier() ResourceIdentifier

GetIdentifier returns a ResourceIdentifier that includes the information needed to uniquely identify a resource in a cluster.

type SequenceIndentStyle

SeqIndentType holds the indentation style for sequence nodes

type SequenceIndentStyle string

type Style

type Style = yaml.Style

func GetStyle

func GetStyle(styles ...string) Style

TODO(pwittrock): test this

type SuffixSetter

type SuffixSetter struct {
    Kind string `yaml:"kind"`

    Value string `yaml:"value"`
}

func (SuffixSetter) Filter

func (s SuffixSetter) Filter(object *RNode) (*RNode, error)

type TeePiper

TeePiper Calls a slice of Filters and returns its input. May be used to fork sub-filters from a call. e.g. locate field, set value; locate another field, set another value

type TeePiper struct {
    Kind string `yaml:"kind,omitempty"`

    // Filters are the set of Filters run by TeePiper.
    Filters []Filter `yaml:"filters,omitempty"`
}

func (TeePiper) Filter

func (t TeePiper) Filter(rn *RNode) (*RNode, error)

type TypeError

type TypeError = yaml.TypeError

type TypeMeta

TypeMeta partially copies apimachinery/pkg/apis/meta/v1.TypeMeta No need for a direct dependence; the fields are stable.

type TypeMeta struct {
    // APIVersion is the apiVersion field of a Resource
    APIVersion string `json:"apiVersion,omitempty" yaml:"apiVersion,omitempty"`
    // Kind is the kind field of a Resource
    Kind string `json:"kind,omitempty" yaml:"kind,omitempty"`
}

type Unmarshaler

type Unmarshaler = yaml.Unmarshaler

type ValueReplacer

type ValueReplacer struct {
    Kind string `yaml:"kind"`

    StringMatch string `yaml:"stringMatch"`
    RegexMatch  string `yaml:"regexMatch"`
    Replace     string `yaml:"replace"`
    Count       int    `yaml:"count"`
}

func (ValueReplacer) Filter

func (s ValueReplacer) Filter(object *RNode) (*RNode, error)

type YFilter

YFilter wraps the Filter interface so the filter can be represented as data and can be unmarshalled into a struct from a yaml config file. This allows Pipelines to be expressed as data rather than code.

type YFilter struct {
    Filter
}

func (YFilter) MarshalYAML

func (y YFilter) MarshalYAML() (interface{}, error)

func (*YFilter) UnmarshalYAML

func (y *YFilter) UnmarshalYAML(unmarshal func(interface{}) error) error

type YFilters

type YFilters []YFilter

func (YFilters) Filters

func (y YFilters) Filters() []Filter

Subdirectories

Name Synopsis
..
merge2 Package merge2 contains libraries for merging fields from one RNode to another RNode
merge3 Package merge contains libraries for merging fields from one RNode to another RNode
schema Package schema contains libraries for working with the yaml and openapi packages.
walk