kio

package
v0.1.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2020 License: Apache-2.0 Imports: 12 Imported by: 244

Documentation

Overview

Package kio contains libraries for reading and writing collections of Resources.

Reading Resources

Resources are Read using a kio.Reader function. Examples:

[kio.LocalPackageReader{}, kio.ByteReader{}]

Resources read using a LocalPackageReader will have annotations applied so they can be written back to the files they were read from.

Modifying Resources

Resources are modified using a kio.Filter. The kio.Filter accepts a collection of Resources as input, and returns a new collection as output. It is recommended to use the yaml package for manipulating individual Resources in the collection.

Writing Resources

Resources are Read using a kio.Reader function. Examples:

[kio.LocalPackageWriter{}, kio.ByteWriter{}]

ReadWriters

It is preferred to use a ReadWriter when reading and writing from / to the same source.

Building Pipelines

The preferred way to transforms a collection of Resources is to use kio.Pipeline to Read, Modify and Write the collection of Resources. Pipeline will automatically sequentially invoke the Read, Modify, Write steps, returning and error immediately on any failure.

Package kio contains low-level libraries for reading, modifying and writing Resource Configuration and packages.

Example
package main

import (
	"bytes"
	"log"
	"os"

	"sigs.k8s.io/kustomize/kyaml/kio"
	"sigs.k8s.io/kustomize/kyaml/yaml"
)

func main() {
	input := bytes.NewReader([]byte(`apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  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
---
apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  selector:
    app: nginx
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
`))

	// setAnnotationFn
	setAnnotationFn := kio.FilterFunc(func(operand []*yaml.RNode) ([]*yaml.RNode, error) {
		for i := range operand {
			resource := operand[i]
			_, err := resource.Pipe(yaml.SetAnnotation("foo", "bar"))
			if err != nil {
				return nil, err
			}
		}
		return operand, nil
	})

	err := kio.Pipeline{
		Inputs:  []kio.Reader{&kio.ByteReader{Reader: input}},
		Filters: []kio.Filter{setAnnotationFn},
		Outputs: []kio.Writer{kio.ByteWriter{Writer: os.Stdout}},
	}.Execute()
	if err != nil {
		log.Fatal(err)
	}

}
Output:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
  annotations:
    foo: 'bar'
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: nginx
  annotations:
    foo: 'bar'
spec:
  selector:
    app: nginx
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80

Index

Examples

Constants

View Source
const (
	ResourceListKind       = "ResourceList"
	ResourceListAPIVersion = "config.kubernetes.io/v1alpha1"
)

Variables

View Source
var DefaultMatch = []string{"*.yaml", "*.yml"}

Functions

This section is empty.

Types

type ByteReadWriter

type ByteReadWriter struct {
	// Reader is where ResourceNodes are decoded from.
	Reader io.Reader

	// Writer is where ResourceNodes are encoded.
	Writer io.Writer

	// OmitReaderAnnotations will configures Read to skip setting the config.kubernetes.io/index
	// annotation on Resources as they are Read.
	OmitReaderAnnotations bool

	// KeepReaderAnnotations if set will keep the Reader specific annotations when writing
	// the Resources, otherwise they will be cleared.
	KeepReaderAnnotations bool

	// Style is a style that is set on the Resource Node Document.
	Style yaml.Style

	FunctionConfig *yaml.RNode

	Results *yaml.RNode

	WrappingAPIVersion string
	WrappingKind       string
}

ByteReadWriter reads from an input and writes to an output.

func (*ByteReadWriter) Read

func (rw *ByteReadWriter) Read() ([]*yaml.RNode, error)

func (*ByteReadWriter) Write

func (rw *ByteReadWriter) Write(nodes []*yaml.RNode) error

type ByteReader

type ByteReader struct {
	// Reader is where ResourceNodes are decoded from.
	Reader io.Reader

	// OmitReaderAnnotations will configures Read to skip setting the config.kubernetes.io/index
	// annotation on Resources as they are Read.
	OmitReaderAnnotations bool

	// SetAnnotations is a map of caller specified annotations to set on resources as they are read
	// These are independent of the annotations controlled by OmitReaderAnnotations
	SetAnnotations map[string]string

	FunctionConfig *yaml.RNode

	Results *yaml.RNode

	// DisableUnwrapping prevents Resources in Lists and ResourceLists from being unwrapped
	DisableUnwrapping bool

	// WrappingAPIVersion is set by Read(), and is the apiVersion of the object that
	// the read objects were originally wrapped in.
	WrappingAPIVersion string

	// WrappingKind is set by Read(), and is the kind of the object that
	// the read objects were originally wrapped in.
	WrappingKind string
}

ByteReader decodes ResourceNodes from bytes. By default, Read will set the config.kubernetes.io/index annotation on each RNode as it is read so they can be written back in the same order.

func (*ByteReader) Read

func (r *ByteReader) Read() ([]*yaml.RNode, error)

type ByteWriter

type ByteWriter struct {
	// Writer is where ResourceNodes are encoded.
	Writer io.Writer

	// KeepReaderAnnotations if set will keep the Reader specific annotations when writing
	// the Resources, otherwise they will be cleared.
	KeepReaderAnnotations bool

	// ClearAnnotations is a list of annotations to clear when writing the Resources.
	ClearAnnotations []string

	// Style is a style that is set on the Resource Node Document.
	Style yaml.Style

	// FunctionConfig is the function config for an ResourceList.  If non-nil
	// wrap the results in an ResourceList.
	FunctionConfig *yaml.RNode

	Results *yaml.RNode

	// WrappingKind if set will cause ByteWriter to wrap the Resources in
	// an 'items' field in this kind.  e.g. if WrappingKind is 'List',
	// ByteWriter will wrap the Resources in a List .items field.
	WrappingKind string

	// WrappingAPIVersion is the apiVersion for WrappingKind
	WrappingAPIVersion string

	// Sort if set, will cause ByteWriter to sort the the nodes before writing them.
	Sort bool
}

Writer writes ResourceNodes to bytes.

func (ByteWriter) Write

func (w ByteWriter) Write(nodes []*yaml.RNode) error

type Filter

type Filter interface {
	Filter([]*yaml.RNode) ([]*yaml.RNode, error)
}

Filter modifies a collection of Resource Configuration by returning the modified slice. When possible, Filters should be serializable to yaml so that they can be described as either data or code.

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

func FilterAll

func FilterAll(filter yaml.Filter) Filter

FilterAll runs the yaml.Filter against all inputs

type FilterFunc

type FilterFunc func([]*yaml.RNode) ([]*yaml.RNode, error)

FilterFunc implements a Filter as a function.

func (FilterFunc) Filter

func (fn FilterFunc) Filter(o []*yaml.RNode) ([]*yaml.RNode, error)

type LocalPackageReadWriter

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

	KeepReaderAnnotations bool `yaml:"keepReaderAnnotations,omitempty"`

	// PackagePath is the path to the package directory.
	PackagePath string `yaml:"path,omitempty"`

	// PackageFileName is the name of file containing package metadata.
	// It will be used to identify package.
	PackageFileName string `yaml:"packageFileName,omitempty"`

	// MatchFilesGlob configures Read to only read Resources from files matching any of the
	// provided patterns.
	// Defaults to ["*.yaml", "*.yml"] if empty.  To match all files specify ["*"].
	MatchFilesGlob []string `yaml:"matchFilesGlob,omitempty"`

	// IncludeSubpackages will configure Read to read Resources from subpackages.
	// Subpackages are identified by presence of PackageFileName.
	IncludeSubpackages bool `yaml:"includeSubpackages,omitempty"`

	// ErrorIfNonResources will configure Read to throw an error if yaml missing missing
	// apiVersion or kind is read.
	ErrorIfNonResources bool `yaml:"errorIfNonResources,omitempty"`

	// OmitReaderAnnotations will cause the reader to skip annotating Resources with the file
	// path and mode.
	OmitReaderAnnotations bool `yaml:"omitReaderAnnotations,omitempty"`

	// SetAnnotations are annotations to set on the Resources as they are read.
	SetAnnotations map[string]string `yaml:"setAnnotations,omitempty"`

	// NoDeleteFiles if set to true, LocalPackageReadWriter won't delete any files
	NoDeleteFiles bool `yaml:"noDeleteFiles,omitempty"`
	// contains filtered or unexported fields
}

LocalPackageReadWriter reads and writes Resources from / to a local directory. When writing, LocalPackageReadWriter will delete files if all of the Resources from that file have been removed from the output.

func (*LocalPackageReadWriter) Read

func (r *LocalPackageReadWriter) Read() ([]*yaml.RNode, error)

func (*LocalPackageReadWriter) Write

func (r *LocalPackageReadWriter) Write(nodes []*yaml.RNode) error

type LocalPackageReader

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

	// PackagePath is the path to the package directory.
	PackagePath string `yaml:"path,omitempty"`

	// PackageFileName is the name of file containing package metadata.
	// It will be used to identify package.
	PackageFileName string `yaml:"packageFileName,omitempty"`

	// MatchFilesGlob configures Read to only read Resources from files matching any of the
	// provided patterns.
	// Defaults to ["*.yaml", "*.yml"] if empty.  To match all files specify ["*"].
	MatchFilesGlob []string `yaml:"matchFilesGlob,omitempty"`

	// IncludeSubpackages will configure Read to read Resources from subpackages.
	// Subpackages are identified by presence of PackageFileName.
	IncludeSubpackages bool `yaml:"includeSubpackages,omitempty"`

	// ErrorIfNonResources will configure Read to throw an error if yaml missing missing
	// apiVersion or kind is read.
	ErrorIfNonResources bool `yaml:"errorIfNonResources,omitempty"`

	// OmitReaderAnnotations will cause the reader to skip annotating Resources with the file
	// path and mode.
	OmitReaderAnnotations bool `yaml:"omitReaderAnnotations,omitempty"`

	// SetAnnotations are annotations to set on the Resources as they are read.
	SetAnnotations map[string]string `yaml:"setAnnotations,omitempty"`
}

LocalPackageReader reads ResourceNodes from a local package.

func (LocalPackageReader) Read

func (r LocalPackageReader) Read() ([]*yaml.RNode, error)

Read reads the Resources.

func (*LocalPackageReader) ShouldSkipDir added in v0.1.6

func (r *LocalPackageReader) ShouldSkipDir(path string) error

ShouldSkipDir returns a filepath.SkipDir if the directory should be skipped

func (*LocalPackageReader) ShouldSkipFile added in v0.1.6

func (r *LocalPackageReader) ShouldSkipFile(info os.FileInfo) (bool, error)

ShouldSkipFile returns true if the file should be skipped

type LocalPackageWriter

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

	// PackagePath is the path to the package directory.
	PackagePath string `yaml:"path,omitempty"`

	// KeepReaderAnnotations if set will retain the annotations set by LocalPackageReader
	KeepReaderAnnotations bool `yaml:"keepReaderAnnotations,omitempty"`

	// ClearAnnotations will clear annotations before writing the resources
	ClearAnnotations []string `yaml:"clearAnnotations,omitempty"`
}

LocalPackageWriter writes ResourceNodes to a filesystem

func (LocalPackageWriter) Write

func (r LocalPackageWriter) Write(nodes []*yaml.RNode) error

type PackageBuffer

type PackageBuffer struct {
	Nodes []*yaml.RNode
}

PackageBuffer implements Reader and Writer, storing Resources in a local field.

func (*PackageBuffer) Read

func (r *PackageBuffer) Read() ([]*yaml.RNode, error)

func (*PackageBuffer) Write

func (r *PackageBuffer) Write(nodes []*yaml.RNode) error

type Pipeline

type Pipeline struct {
	// Inputs provide sources for Resource Configuration to be read.
	Inputs []Reader `yaml:"inputs,omitempty"`

	// Filters are transformations applied to the Resource Configuration.
	// They are applied in the order they are specified.
	// Analogous to http://www.linfo.org/filters.html
	Filters []Filter `yaml:"filters,omitempty"`

	// Outputs are where the transformed Resource Configuration is written.
	Outputs []Writer `yaml:"outputs,omitempty"`
}

Pipeline reads Resource Configuration from a set of Inputs, applies some transformation filters, and writes the results to a set of Outputs.

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

func (Pipeline) Execute

func (p Pipeline) Execute() error

Execute executes each step in the sequence, returning immediately after encountering any error as part of the Pipeline.

type Reader

type Reader interface {
	Read() ([]*yaml.RNode, error)
}

Reader reads ResourceNodes. Analogous to io.Reader.

type ReaderWriter

type ReaderWriter interface {
	Reader
	Writer
}

ReaderWriter implements both Reader and Writer interfaces

type ResourceNodeSlice

type ResourceNodeSlice []*yaml.RNode

ResourceNodeSlice is a collection of ResourceNodes. While ResourceNodeSlice has no inherent constraints on ordering or uniqueness, specific Readers, Filters or Writers may have constraints.

func (ResourceNodeSlice) Read

func (o ResourceNodeSlice) Read() ([]*yaml.RNode, error)

type TreeStructure

type TreeStructure string
const (
	// TreeStructurePackage configures TreeWriter to generate the tree structure off of the
	// Resources packages.
	TreeStructurePackage TreeStructure = "directory"

	// TreeStructureOwners configures TreeWriter to generate the tree structure off of the
	// Resource owners.
	TreeStructureGraph TreeStructure = "owners"
)

type TreeWriter

type TreeWriter struct {
	Writer    io.Writer
	Root      string
	Fields    []TreeWriterField
	Structure TreeStructure
}

TreeWriter prints the package structured as a tree. TODO(pwittrock): test this package better. it is lower-risk since it is only used for printing rather than updating or editing.

func (TreeWriter) Write

func (p TreeWriter) Write(nodes []*yaml.RNode) error

Write writes the ascii tree to p.Writer

type TreeWriterField

type TreeWriterField struct {
	yaml.PathMatcher
	Name    string
	SubName string
}

TreeWriterField configures a Resource field to be included in the tree

type Writer

type Writer interface {
	Write([]*yaml.RNode) error
}

Writer writes ResourceNodes. Analogous to io.Writer.

type WriterFunc

type WriterFunc func([]*yaml.RNode) error

WriterFunc implements a Writer as a function.

func (WriterFunc) Write

func (fn WriterFunc) Write(o []*yaml.RNode) error

Directories

Path Synopsis
Package yamlfmt contains libraries for formatting yaml files containing Kubernetes Resource configuration.
Package yamlfmt contains libraries for formatting yaml files containing Kubernetes Resource configuration.
testyaml
Package testyaml contains test data and libraries for formatting Kubernetes configuration
Package testyaml contains test data and libraries for formatting Kubernetes configuration

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL