Skip to content

Commit

Permalink
Merge pull request kubernetes#110088 from ardaguclu/standartize-valid…
Browse files Browse the repository at this point in the history
…ate-func

Set validate functions requiring no parameters for all commands
  • Loading branch information
k8s-ci-robot committed May 17, 2022
2 parents f0c47dc + 8fb423b commit 17556d4
Show file tree
Hide file tree
Showing 17 changed files with 123 additions and 108 deletions.
12 changes: 6 additions & 6 deletions staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ func NewCmdApply(baseName string, f cmdutil.Factory, ioStreams genericclioptions
Run: func(cmd *cobra.Command, args []string) {
o, err := flags.ToOptions(cmd, baseName, args)
cmdutil.CheckErr(err)
cmdutil.CheckErr(o.Validate(cmd, args))
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.Run())
},
}
Expand Down Expand Up @@ -230,6 +230,10 @@ func (flags *ApplyFlags) AddFlags(cmd *cobra.Command) {

// ToOptions converts from CLI inputs to runtime inputs
func (flags *ApplyFlags) ToOptions(cmd *cobra.Command, baseName string, args []string) (*ApplyOptions, error) {
if len(args) != 0 {
return nil, cmdutil.UsageErrorf(cmd, "Unexpected args: %v", args)
}

serverSideApply := cmdutil.GetServerSideApplyFlag(cmd)
forceConflicts := cmdutil.GetForceConflictsFlag(cmd)
dryRunStrategy, err := cmdutil.GetDryRunStrategy(cmd)
Expand Down Expand Up @@ -344,11 +348,7 @@ func (flags *ApplyFlags) ToOptions(cmd *cobra.Command, baseName string, args []s
}

// Validate verifies if ApplyOptions are valid and without conflicts.
func (o *ApplyOptions) Validate(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
return cmdutil.UsageErrorf(cmd, "Unexpected args: %v", args)
}

func (o *ApplyOptions) Validate() error {
if o.ForceConflicts && !o.ServerSideApply {
return fmt.Errorf("--force-conflicts only works with --server-side")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func NewCmdApplyViewLastApplied(f cmdutil.Factory, ioStreams genericclioptions.I
ValidArgsFunction: completion.ResourceTypeAndNameCompletionFunc(f),
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(options.Complete(cmd, f, args))
cmdutil.CheckErr(options.Validate(cmd))
cmdutil.CheckErr(options.Validate())
cmdutil.CheckErr(options.RunApplyViewLastApplied(cmd))
},
}
Expand Down Expand Up @@ -141,7 +141,7 @@ func (o *ViewLastAppliedOptions) Complete(cmd *cobra.Command, f cmdutil.Factory,
}

// Validate checks ViewLastAppliedOptions for validity.
func (o *ViewLastAppliedOptions) Validate(cmd *cobra.Command) error {
func (o *ViewLastAppliedOptions) Validate() error {
return nil
}

Expand Down
27 changes: 12 additions & 15 deletions staging/src/k8s.io/kubectl/pkg/cmd/config/get_contexts.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ type GetContextsOptions struct {
showHeaders bool
contextNames []string

outputFormat string
noHeaders bool

genericclioptions.IOStreams
}

Expand Down Expand Up @@ -73,22 +76,26 @@ func NewCmdConfigGetContexts(streams genericclioptions.IOStreams, configAccess c
Long: getContextsLong,
Example: getContextsExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(options.Validate(cmd))
cmdutil.CheckErr(options.Complete(cmd, args))
cmdutil.CheckErr(options.Validate())
cmdutil.CheckErr(options.RunGetContexts())
},
}

cmd.Flags().Bool("no-headers", false, "When using the default or custom-column output format, don't print headers (default print headers).")
cmd.Flags().StringP("output", "o", "", `Output format. One of: (name).`)
cmd.Flags().BoolVar(&options.noHeaders, "no-headers", options.noHeaders, "When using the default or custom-column output format, don't print headers (default print headers).")
cmd.Flags().StringVarP(&options.outputFormat, "output", "o", options.outputFormat, `Output format. One of: (name).`)
return cmd
}

// Complete assigns GetContextsOptions from the args.
func (o *GetContextsOptions) Complete(cmd *cobra.Command, args []string) error {
supportedOutputTypes := sets.NewString("", "name")
if !supportedOutputTypes.Has(o.outputFormat) {
return fmt.Errorf("--output %v is not available in kubectl config get-contexts; resetting to default output format", o.outputFormat)
}
o.contextNames = args
o.nameOnly = false
if cmdutil.GetFlagString(cmd, "output") == "name" {
if o.outputFormat == "name" {
o.nameOnly = true
}
o.showHeaders = true
Expand All @@ -100,17 +107,7 @@ func (o *GetContextsOptions) Complete(cmd *cobra.Command, args []string) error {
}

// Validate ensures the of output format
func (o *GetContextsOptions) Validate(cmd *cobra.Command) error {
validOutputTypes := sets.NewString("", "json", "yaml", "wide", "name", "custom-columns", "custom-columns-file", "go-template", "go-template-file", "jsonpath", "jsonpath-file")
supportedOutputTypes := sets.NewString("", "name")
outputFormat := cmdutil.GetFlagString(cmd, "output")
if !validOutputTypes.Has(outputFormat) {
return fmt.Errorf("output must be one of '' or 'name': %v", outputFormat)
}
if !supportedOutputTypes.Has(outputFormat) {
cmd.Flags().Set("output", "")
return fmt.Errorf("--output %v is not available in kubectl config get-contexts; resetting to default output format", outputFormat)
}
func (o *GetContextsOptions) Validate() error {
return nil
}

Expand Down
22 changes: 13 additions & 9 deletions staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ type CopyOptions struct {
Clientset kubernetes.Interface
ExecParentCmdName string

args []string

genericclioptions.IOStreams
}

Expand Down Expand Up @@ -149,9 +151,9 @@ func NewCmdCp(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.C
return comps, cobra.ShellCompDirectiveNoSpace
},
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd))
cmdutil.CheckErr(o.Validate(cmd, args))
cmdutil.CheckErr(o.Run(args))
cmdutil.CheckErr(o.Complete(f, cmd, args))
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.Run())
},
}
cmdutil.AddContainerVarFlags(cmd, &o.Container, o.Container)
Expand Down Expand Up @@ -198,7 +200,7 @@ func extractFileSpec(arg string) (fileSpec, error) {
}

// Complete completes all the required options
func (o *CopyOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
func (o *CopyOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
if cmd.Parent() != nil {
o.ExecParentCmdName = cmd.Parent().CommandPath()
}
Expand All @@ -218,24 +220,26 @@ func (o *CopyOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
if err != nil {
return err
}

o.args = args
return nil
}

// Validate makes sure provided values for CopyOptions are valid
func (o *CopyOptions) Validate(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
func (o *CopyOptions) Validate() error {
if len(o.args) != 2 {
return fmt.Errorf("source and destination are required")
}
return nil
}

// Run performs the execution
func (o *CopyOptions) Run(args []string) error {
srcSpec, err := extractFileSpec(args[0])
func (o *CopyOptions) Run() error {
srcSpec, err := extractFileSpec(o.args[0])
if err != nil {
return err
}
destSpec, err := extractFileSpec(args[1])
destSpec, err := extractFileSpec(o.args[1])
if err != nil {
return err
}
Expand Down
11 changes: 5 additions & 6 deletions staging/src/k8s.io/kubectl/pkg/cmd/cp/cp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -659,9 +659,9 @@ func TestCopyToPod(t *testing.T) {

for name, test := range tests {
opts := NewCopyOptions(ioStreams)
opts.Complete(tf, cmd)
opts.Complete(tf, cmd, []string{test.src, fmt.Sprintf("pod-ns/pod-name:%s", test.dest)})
t.Run(name, func(t *testing.T) {
err = opts.Run([]string{test.src, fmt.Sprintf("pod-ns/pod-name:%s", test.dest)})
err = opts.Run()
//If error is NotFound error , it indicates that the
//request has been sent correctly.
//Treat this as no error.
Expand Down Expand Up @@ -723,7 +723,7 @@ func TestCopyToPodNoPreserve(t *testing.T) {
PodName: "pod-name",
File: newRemotePath("foo"),
}
opts.Complete(tf, cmd)
opts.Complete(tf, cmd, nil)

for name, test := range tests {
t.Run(name, func(t *testing.T) {
Expand Down Expand Up @@ -754,14 +754,13 @@ func TestValidate(t *testing.T) {
expectedErr: true,
},
}
tf := cmdtesting.NewTestFactory()
ioStreams, _, _, _ := genericclioptions.NewTestIOStreams()
opts := NewCopyOptions(ioStreams)
cmd := NewCmdCp(tf, ioStreams)

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := opts.Validate(cmd, test.args)
opts.args = test.args
err := opts.Validate()
if (err != nil) != test.expectedErr {
t.Errorf("expected error: %v, saw: %v, error: %v", test.expectedErr, err != nil, err)
}
Expand Down
32 changes: 16 additions & 16 deletions staging/src/k8s.io/kubectl/pkg/cmd/create/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ func NewCmdCreate(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cob
defaultRunFunc(cmd, args)
return
}
cmdutil.CheckErr(o.Complete(f, cmd))
cmdutil.CheckErr(o.ValidateArgs(cmd, args))
cmdutil.CheckErr(o.Complete(f, cmd, args))
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.RunCreate(f, cmd))
},
}
Expand Down Expand Up @@ -160,40 +160,40 @@ func NewCmdCreate(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cob
return cmd
}

// ValidateArgs makes sure there is no discrepency in command options
func (o *CreateOptions) ValidateArgs(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
return cmdutil.UsageErrorf(cmd, "Unexpected args: %v", args)
}
// Validate makes sure there is no discrepency in command options
func (o *CreateOptions) Validate() error {
if len(o.Raw) > 0 {
if o.EditBeforeCreate {
return cmdutil.UsageErrorf(cmd, "--raw and --edit are mutually exclusive")
return fmt.Errorf("--raw and --edit are mutually exclusive")
}
if len(o.FilenameOptions.Filenames) != 1 {
return cmdutil.UsageErrorf(cmd, "--raw can only use a single local file or stdin")
return fmt.Errorf("--raw can only use a single local file or stdin")
}
if strings.Index(o.FilenameOptions.Filenames[0], "http://") == 0 || strings.Index(o.FilenameOptions.Filenames[0], "https://") == 0 {
return cmdutil.UsageErrorf(cmd, "--raw cannot read from a url")
return fmt.Errorf("--raw cannot read from a url")
}
if o.FilenameOptions.Recursive {
return cmdutil.UsageErrorf(cmd, "--raw and --recursive are mutually exclusive")
return fmt.Errorf("--raw and --recursive are mutually exclusive")
}
if len(o.Selector) > 0 {
return cmdutil.UsageErrorf(cmd, "--raw and --selector (-l) are mutually exclusive")
return fmt.Errorf("--raw and --selector (-l) are mutually exclusive")
}
if len(cmdutil.GetFlagString(cmd, "output")) > 0 {
return cmdutil.UsageErrorf(cmd, "--raw and --output are mutually exclusive")
if o.PrintFlags.OutputFormat != nil && len(*o.PrintFlags.OutputFormat) > 0 {
return fmt.Errorf("--raw and --output are mutually exclusive")
}
if _, err := url.ParseRequestURI(o.Raw); err != nil {
return cmdutil.UsageErrorf(cmd, "--raw must be a valid URL path: %v", err)
return fmt.Errorf("--raw must be a valid URL path: %v", err)
}
}

return nil
}

// Complete completes all the required options
func (o *CreateOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
func (o *CreateOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
if len(args) != 0 {
return cmdutil.UsageErrorf(cmd, "Unexpected args: %v", args)
}
var err error
o.RecordFlags.Complete(cmd)
o.Recorder, err = o.RecordFlags.ToRecorder()
Expand Down
5 changes: 3 additions & 2 deletions staging/src/k8s.io/kubectl/pkg/cmd/create/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ func TestExtraArgsFail(t *testing.T) {
defer f.Cleanup()

c := NewCmdCreate(f, genericclioptions.NewTestIOStreamsDiscard())
options := CreateOptions{}
if options.ValidateArgs(c, []string{"rc"}) == nil {
ioStreams, _, _, _ := genericclioptions.NewTestIOStreams()
options := NewCreateOptions(ioStreams)
if options.Complete(f, c, []string{"rc"}) == nil {
t.Errorf("unexpected non-error")
}
}
Expand Down
4 changes: 2 additions & 2 deletions staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func NewCmdDebug(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.
Example: debugExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd, args))
cmdutil.CheckErr(o.Validate(cmd))
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.Run(f, cmd))
},
}
Expand Down Expand Up @@ -221,7 +221,7 @@ func (o *DebugOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []st
}

// Validate checks that the provided debug options are specified.
func (o *DebugOptions) Validate(cmd *cobra.Command) error {
func (o *DebugOptions) Validate() error {
// Attach
if o.Attach && o.attachChanged && len(o.Image) == 0 && len(o.Container) == 0 {
return fmt.Errorf("you must specify --container or create a new container using --image in order to attach.")
Expand Down
2 changes: 1 addition & 1 deletion staging/src/k8s.io/kubectl/pkg/cmd/debug/debug_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1538,7 +1538,7 @@ func TestCompleteAndValidate(t *testing.T) {
if gotError != nil {
return
}
gotError = opts.Validate(cmd)
gotError = opts.Validate()
},
}
cmd.SetArgs(strings.Split(tc.args, " "))
Expand Down
3 changes: 2 additions & 1 deletion staging/src/k8s.io/kubectl/pkg/cmd/describe/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ func NewCmdDescribe(parent string, f cmdutil.Factory, streams genericclioptions.
ValidArgsFunction: completion.ResourceTypeAndNameCompletionFunc(f),
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd, args))
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.Run())
},
}
Expand Down Expand Up @@ -148,7 +149,7 @@ func (o *DescribeOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args [
return nil
}

func (o *DescribeOptions) Validate(args []string) error {
func (o *DescribeOptions) Validate() error {
return nil
}

Expand Down
22 changes: 12 additions & 10 deletions staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,13 +118,6 @@ type DiffOptions struct {
pruner *pruner
}

func validateArgs(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
return cmdutil.UsageErrorf(cmd, "Unexpected args: %v", args)
}
return nil
}

func NewDiffOptions(ioStreams genericclioptions.IOStreams) *DiffOptions {
return &DiffOptions{
Diff: &DiffProgram{
Expand All @@ -143,8 +136,8 @@ func NewCmdDiff(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.C
Long: diffLong,
Example: diffExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckDiffErr(options.Complete(f, cmd))
cmdutil.CheckDiffErr(validateArgs(cmd, args))
cmdutil.CheckDiffErr(options.Complete(f, cmd, args))
cmdutil.CheckDiffErr(options.Validate())
// `kubectl diff` propagates the error code from
// diff or `KUBECTL_EXTERNAL_DIFF`. Also, we
// don't want to print an error if diff returns
Expand Down Expand Up @@ -605,7 +598,11 @@ func isConflict(err error) bool {
return err != nil && errors.IsConflict(err)
}

func (o *DiffOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
func (o *DiffOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
if len(args) != 0 {
return cmdutil.UsageErrorf(cmd, "Unexpected args: %v", args)
}

var err error

err = o.FilenameOptions.RequireFilenameOrKustomize()
Expand Down Expand Up @@ -759,6 +756,11 @@ func (o *DiffOptions) Run() error {
return differ.Run(o.Diff)
}

// Validate makes sure provided values for DiffOptions are valid
func (o *DiffOptions) Validate() error {
return nil
}

func getObjectName(obj runtime.Object) (string, error) {
gvk := obj.GetObjectKind().GroupVersionKind()
metadata, err := meta.Accessor(obj)
Expand Down

0 comments on commit 17556d4

Please sign in to comment.