From 9555debc8248b06a194e315219203714480fcb83 Mon Sep 17 00:00:00 2001 From: Di Xu Date: Sat, 24 Feb 2018 14:41:35 +0800 Subject: [PATCH] flag value bindings for kubectl apply commands --- pkg/kubectl/cmd/apply.go | 45 ++++++++++++++-------- pkg/kubectl/cmd/apply_edit_last_applied.go | 8 ++-- pkg/kubectl/cmd/apply_set_last_applied.go | 2 +- pkg/kubectl/cmd/apply_view_last_applied.go | 45 ++++++++++------------ 4 files changed, 55 insertions(+), 45 deletions(-) diff --git a/pkg/kubectl/cmd/apply.go b/pkg/kubectl/cmd/apply.go index 71486bdac48..ae585954d3c 100644 --- a/pkg/kubectl/cmd/apply.go +++ b/pkg/kubectl/cmd/apply.go @@ -59,7 +59,10 @@ type ApplyOptions struct { PruneResources []pruneResource Timeout time.Duration cmdBaseName string - all bool + All bool + Overwrite bool + OpenApiPatch bool + PruneWhitelist []string } const ( @@ -98,8 +101,17 @@ var ( warningNoLastAppliedConfigAnnotation = "Warning: %[1]s apply should be used on resource created by either %[1]s create --save-config or %[1]s apply\n" ) +func NewApplyOptions() *ApplyOptions { + return &ApplyOptions{ + Overwrite: true, + Cascade: true, + GracePeriod: -1, + OpenApiPatch: true, + } +} + func NewCmdApply(baseName string, f cmdutil.Factory, out, errOut io.Writer) *cobra.Command { - var options ApplyOptions + options := NewApplyOptions() // Store baseName for use in printing warnings / messages involving the base command name. // This is useful for downstream command that wrap this one. @@ -113,25 +125,25 @@ func NewCmdApply(baseName string, f cmdutil.Factory, out, errOut io.Writer) *cob Example: applyExample, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(validateArgs(cmd, args)) - cmdutil.CheckErr(validatePruneAll(options.Prune, options.all, options.Selector)) - cmdutil.CheckErr(RunApply(f, cmd, out, errOut, &options)) + cmdutil.CheckErr(validatePruneAll(options.Prune, options.All, options.Selector)) + cmdutil.CheckErr(RunApply(f, cmd, out, errOut, options)) }, } usage := "that contains the configuration to apply" cmdutil.AddFilenameOptionFlags(cmd, &options.FilenameOptions, usage) cmd.MarkFlagRequired("filename") - cmd.Flags().Bool("overwrite", true, "Automatically resolve conflicts between the modified and live configuration by using values from the modified configuration") - cmd.Flags().BoolVar(&options.Prune, "prune", false, "Automatically delete resource objects, including the uninitialized ones, that do not appear in the configs and are created by either apply or create --save-config. Should be used with either -l or --all.") - cmd.Flags().BoolVar(&options.Cascade, "cascade", true, "Only relevant during a prune or a force apply. If true, cascade the deletion of the resources managed by pruned or deleted resources (e.g. Pods created by a ReplicationController).") - cmd.Flags().IntVar(&options.GracePeriod, "grace-period", -1, "Only relevant during a prune or a force apply. Period of time in seconds given to pruned or deleted resources to terminate gracefully. Ignored if negative.") - cmd.Flags().BoolVar(&options.Force, "force", false, fmt.Sprintf("Delete and re-create the specified resource, when PATCH encounters conflict and has retried for %d times.", maxPatchRetry)) - cmd.Flags().DurationVar(&options.Timeout, "timeout", 0, "Only relevant during a force apply. The length of time to wait before giving up on a delete of the old resource, zero means determine a timeout from the size of the object. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h).") + cmd.Flags().BoolVar(&options.Overwrite, "overwrite", options.Overwrite, "Automatically resolve conflicts between the modified and live configuration by using values from the modified configuration") + cmd.Flags().BoolVar(&options.Prune, "prune", options.Prune, "Automatically delete resource objects, including the uninitialized ones, that do not appear in the configs and are created by either apply or create --save-config. Should be used with either -l or --all.") + cmd.Flags().BoolVar(&options.Cascade, "cascade", options.Cascade, "Only relevant during a prune or a force apply. If true, cascade the deletion of the resources managed by pruned or deleted resources (e.g. Pods created by a ReplicationController).") + cmd.Flags().IntVar(&options.GracePeriod, "grace-period", options.GracePeriod, "Only relevant during a prune or a force apply. Period of time in seconds given to pruned or deleted resources to terminate gracefully. Ignored if negative.") + cmd.Flags().BoolVar(&options.Force, "force", options.Force, fmt.Sprintf("Delete and re-create the specified resource, when PATCH encounters conflict and has retried for %d times.", maxPatchRetry)) + cmd.Flags().DurationVar(&options.Timeout, "timeout", options.Timeout, "Only relevant during a force apply. The length of time to wait before giving up on a delete of the old resource, zero means determine a timeout from the size of the object. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h).") cmdutil.AddValidateFlags(cmd) cmd.Flags().StringVarP(&options.Selector, "selector", "l", options.Selector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)") - cmd.Flags().BoolVar(&options.all, "all", options.all, "Select all resources in the namespace of the specified resource types.") - cmd.Flags().StringArray("prune-whitelist", []string{}, "Overwrite the default whitelist with for --prune") - cmd.Flags().Bool("openapi-patch", true, "If true, use openapi to calculate diff when the openapi presents and the resource can be found in the openapi spec. Otherwise, fall back to use baked-in types.") + cmd.Flags().BoolVar(&options.All, "all", options.All, "Select all resources in the namespace of the specified resource types.") + cmd.Flags().StringArrayVar(&options.PruneWhitelist, "prune-whitelist", options.PruneWhitelist, "Overwrite the default whitelist with for --prune") + cmd.Flags().BoolVar(&options.OpenApiPatch, "openapi-patch", options.OpenApiPatch, "If true, use openapi to calculate diff when the openapi presents and the resource can be found in the openapi spec. Otherwise, fall back to use baked-in types.") cmdutil.AddDryRunFlag(cmd) cmdutil.AddPrinterFlags(cmd) cmdutil.AddRecordFlag(cmd) @@ -201,7 +213,7 @@ func RunApply(f cmdutil.Factory, cmd *cobra.Command, out, errOut io.Writer, opti } var openapiSchema openapi.Resources - if cmdutil.GetFlagBool(cmd, "openapi-patch") { + if options.OpenApiPatch { openapiSchema, err = f.OpenAPISchema() if err != nil { openapiSchema = nil @@ -231,7 +243,7 @@ func RunApply(f cmdutil.Factory, cmd *cobra.Command, out, errOut io.Writer, opti } if options.Prune { - options.PruneResources, err = parsePruneResources(r.Mapper().RESTMapper, cmdutil.GetFlagStringArray(cmd, "prune-whitelist")) + options.PruneResources, err = parsePruneResources(r.Mapper().RESTMapper, options.PruneWhitelist) if err != nil { return err } @@ -312,7 +324,6 @@ func RunApply(f cmdutil.Factory, cmd *cobra.Command, out, errOut io.Writer, opti if _, ok := annotationMap[api.LastAppliedConfigAnnotation]; !ok { fmt.Fprintf(errOut, warningNoLastAppliedConfigAnnotation, options.cmdBaseName) } - overwrite := cmdutil.GetFlagBool(cmd, "overwrite") helper := resource.NewHelper(info.Client, info.Mapping) patcher := &patcher{ encoder: encoder, @@ -321,7 +332,7 @@ func RunApply(f cmdutil.Factory, cmd *cobra.Command, out, errOut io.Writer, opti helper: helper, clientFunc: f.UnstructuredClientForMapping, clientsetFunc: f.ClientSet, - overwrite: overwrite, + overwrite: options.Overwrite, backOff: clockwork.NewRealClock(), force: options.Force, cascade: options.Cascade, diff --git a/pkg/kubectl/cmd/apply_edit_last_applied.go b/pkg/kubectl/cmd/apply_edit_last_applied.go index 5fd5dd19935..6d97a551fab 100644 --- a/pkg/kubectl/cmd/apply_edit_last_applied.go +++ b/pkg/kubectl/cmd/apply_edit_last_applied.go @@ -60,7 +60,9 @@ var ( func NewCmdApplyEditLastApplied(f cmdutil.Factory, out, errOut io.Writer) *cobra.Command { options := &editor.EditOptions{ - EditMode: editor.ApplyEditMode, + EditMode: editor.ApplyEditMode, + Output: "yaml", + WindowsLineEndings: runtime.GOOS == "windows", } validArgs := cmdutil.ValidArgList(f) @@ -85,8 +87,8 @@ func NewCmdApplyEditLastApplied(f cmdutil.Factory, out, errOut io.Writer) *cobra usage := "to use to edit the resource" cmdutil.AddFilenameOptionFlags(cmd, &options.FilenameOptions, usage) - cmd.Flags().StringVarP(&options.Output, "output", "o", "yaml", "Output format. One of: yaml|json.") - cmd.Flags().BoolVar(&options.WindowsLineEndings, "windows-line-endings", runtime.GOOS == "windows", + cmd.Flags().StringVarP(&options.Output, "output", "o", options.Output, "Output format. One of: yaml|json.") + cmd.Flags().BoolVar(&options.WindowsLineEndings, "windows-line-endings", options.WindowsLineEndings, "Defaults to the line ending native to your platform.") cmdutil.AddRecordVarFlag(cmd, &options.Record) cmdutil.AddIncludeUninitializedFlag(cmd) diff --git a/pkg/kubectl/cmd/apply_set_last_applied.go b/pkg/kubectl/cmd/apply_set_last_applied.go index 5a0c565b501..5d3b2870cdc 100644 --- a/pkg/kubectl/cmd/apply_set_last_applied.go +++ b/pkg/kubectl/cmd/apply_set_last_applied.go @@ -99,7 +99,7 @@ func NewCmdApplySetLastApplied(f cmdutil.Factory, out, err io.Writer) *cobra.Com cmdutil.AddDryRunFlag(cmd) cmdutil.AddRecordFlag(cmd) cmdutil.AddPrinterFlags(cmd) - cmd.Flags().BoolVar(&options.CreateAnnotation, "create-annotation", false, "Will create 'last-applied-configuration' annotations if current objects doesn't have one") + cmd.Flags().BoolVar(&options.CreateAnnotation, "create-annotation", options.CreateAnnotation, "Will create 'last-applied-configuration' annotations if current objects doesn't have one") usage := "that contains the last-applied-configuration annotations" kubectl.AddJsonFilenameFlag(cmd, &options.FilenameOptions.Filenames, "Filename, directory, or URL to files "+usage) diff --git a/pkg/kubectl/cmd/apply_view_last_applied.go b/pkg/kubectl/cmd/apply_view_last_applied.go index b0ebb1af820..f313b61c31d 100644 --- a/pkg/kubectl/cmd/apply_view_last_applied.go +++ b/pkg/kubectl/cmd/apply_view_last_applied.go @@ -57,8 +57,16 @@ var ( kubectl apply view-last-applied -f deploy.yaml -o json`)) ) +func NewViewLastAppliedOptions(out, err io.Writer) *ViewLastAppliedOptions { + return &ViewLastAppliedOptions{ + Out: out, + ErrOut: err, + OutputFormat: "yaml", + } +} + func NewCmdApplyViewLastApplied(f cmdutil.Factory, out, err io.Writer) *cobra.Command { - options := &ViewLastAppliedOptions{Out: out, ErrOut: err} + options := NewViewLastAppliedOptions(out, err) cmd := &cobra.Command{ Use: "view-last-applied (TYPE [NAME | -l label] | TYPE/NAME | -f FILENAME)", DisableFlagsInUseLine: true, @@ -66,23 +74,22 @@ func NewCmdApplyViewLastApplied(f cmdutil.Factory, out, err io.Writer) *cobra.Co Long: applyViewLastAppliedLong, Example: applyViewLastAppliedExample, Run: func(cmd *cobra.Command, args []string) { - cmdutil.CheckErr(options.ValidateOutputArgs(cmd)) - cmdutil.CheckErr(options.Complete(f, args)) + cmdutil.CheckErr(options.Complete(cmd, f, args)) cmdutil.CheckErr(options.Validate(cmd)) - cmdutil.CheckErr(options.RunApplyViewLastApplied()) + cmdutil.CheckErr(options.RunApplyViewLastApplied(cmd)) }, } - cmd.Flags().StringP("output", "o", "", "Output format. Must be one of yaml|json") - cmd.Flags().StringVarP(&options.Selector, "selector", "l", "", "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)") - cmd.Flags().BoolVar(&options.All, "all", false, "Select all resources in the namespace of the specified resource types") + cmd.Flags().StringVarP(&options.OutputFormat, "output", "o", options.OutputFormat, "Output format. Must be one of yaml|json") + cmd.Flags().StringVarP(&options.Selector, "selector", "l", options.Selector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)") + cmd.Flags().BoolVar(&options.All, "all", options.All, "Select all resources in the namespace of the specified resource types") usage := "that contains the last-applied-configuration annotations" cmdutil.AddFilenameOptionFlags(cmd, &options.FilenameOptions, usage) return cmd } -func (o *ViewLastAppliedOptions) Complete(f cmdutil.Factory, args []string) error { +func (o *ViewLastAppliedOptions) Complete(cmd *cobra.Command, f cmdutil.Factory, args []string) error { cmdNamespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err @@ -130,7 +137,7 @@ func (o *ViewLastAppliedOptions) Validate(cmd *cobra.Command) error { return nil } -func (o *ViewLastAppliedOptions) RunApplyViewLastApplied() error { +func (o *ViewLastAppliedOptions) RunApplyViewLastApplied(cmd *cobra.Command) error { for _, str := range o.LastAppliedConfigurationList { switch o.OutputFormat { case "json": @@ -146,23 +153,13 @@ func (o *ViewLastAppliedOptions) RunApplyViewLastApplied() error { return err } fmt.Fprint(o.Out, string(yamlOutput)) + default: + return cmdutil.UsageErrorf( + cmd, + "Unexpected -o output mode: %s, the flag 'output' must be one of yaml|json", + o.OutputFormat) } } return nil } - -func (o *ViewLastAppliedOptions) ValidateOutputArgs(cmd *cobra.Command) error { - format := cmdutil.GetFlagString(cmd, "output") - switch format { - case "json": - o.OutputFormat = "json" - return nil - // If flag -o is not specified, use yaml as default - case "yaml", "": - o.OutputFormat = "yaml" - return nil - default: - return cmdutil.UsageErrorf(cmd, "Unexpected -o output mode: %s, the flag 'output' must be one of yaml|json", format) - } -}