airshipctl/pkg/k8s/kubectl/apply_options.go
Kostiantyn Kalynovskyi d588c73e38 [#20] Add kubectl apply wrapper package
The wrapper is called ApplyAdapter and is a struct, that has Apply(..)
method and some setters that allow to control kubectl apply behaviour

Addapter is expected to be used through Apply(..) function, which takes
slice of document.Document interface objects, writes them out to
temporary file system, from where they are picked up by kubectl Apply
module, and delivered to kubernetes cluster. The decision to use
temporary file system is based on the fact, that in current state
kubectl project currently only works with actual files, and ignores
io.Streams object, that is part of ApplyOptions struct, so it is
currently the only way to use it.

Change-Id: Idc5d79794149c00198f420d76cf9aa3b5264946e
2020-02-20 20:58:31 +00:00

79 lines
2.0 KiB
Go

package kubectl
import (
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/printers"
"k8s.io/kubectl/pkg/cmd/apply"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
)
// NewApplyOptions is a helper function that Creates ApplyOptions of kubectl apply module
// Values set here, are default, and do not conflict with each other, can be used if you
// need `kubectl apply` functionality without calling executing command in shell
// To function properly, you may need to specify files from where to read the resources:
// DeleteOptions.Filenames of returned object has to be set for that
func NewApplyOptions(f cmdutil.Factory, streams genericclioptions.IOStreams) (*apply.ApplyOptions, error) {
o := apply.NewApplyOptions(streams)
o.ServerSideApply = false
o.ForceConflicts = false
o.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {
o.PrintFlags.NamePrintFlags.Operation = operation
if o.DryRun {
err := o.PrintFlags.Complete("%s (dry run)")
if err != nil {
return nil, err
}
}
if o.ServerDryRun {
err := o.PrintFlags.Complete("%s (server dry run)")
if err != nil {
return nil, err
}
}
return o.PrintFlags.ToPrinter()
}
var err error
o.Recorder, err = o.RecordFlags.ToRecorder()
if err != nil {
return nil, err
}
o.DiscoveryClient, err = f.ToDiscoveryClient()
if err != nil {
return nil, err
}
dynamicClient, err := f.DynamicClient()
if err != nil {
return nil, err
}
o.DeleteOptions = o.DeleteFlags.ToOptions(dynamicClient, o.IOStreams)
// This can only fail if ToDiscoverClient() function fails
o.OpenAPISchema, err = f.OpenAPISchema()
if err != nil {
return nil, err
}
o.Validator, err = f.Validator(false)
if err != nil {
return nil, err
}
o.Builder = f.NewBuilder()
o.Mapper, err = f.ToRESTMapper()
if err != nil {
return nil, err
}
o.DynamicClient = dynamicClient
o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return nil, err
}
return o, nil
}