Skip to content

Commit

Permalink
Merge pull request #125072 from brianpursley/create-fix-validation
Browse files Browse the repository at this point in the history
Fix validation of -f or -k flag in kubectl create command to be consistent with other commands
  • Loading branch information
k8s-ci-robot committed May 23, 2024
2 parents 073ce0e + 4fddd6a commit c9a1a0a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
12 changes: 5 additions & 7 deletions staging/src/k8s.io/kubectl/pkg/cmd/create/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,6 @@ func NewCmdCreate(f cmdutil.Factory, ioStreams genericiooptions.IOStreams) *cobr
Long: createLong,
Example: createExample,
Run: func(cmd *cobra.Command, args []string) {
if cmdutil.IsFilenameSliceEmpty(o.FilenameOptions.Filenames, o.FilenameOptions.Kustomize) {
ioStreams.ErrOut.Write([]byte("Error: must specify one of -f and -k\n\n"))
defaultRunFunc := cmdutil.DefaultSubCommandRun(ioStreams.ErrOut)
defaultRunFunc(cmd, args)
return
}
cmdutil.CheckErr(o.Complete(f, cmd, args))
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.RunCreate(f, cmd))
Expand Down Expand Up @@ -159,8 +153,12 @@ func NewCmdCreate(f cmdutil.Factory, ioStreams genericiooptions.IOStreams) *cobr
return cmd
}

// Validate makes sure there is no discrepency in command options
// Validate makes sure there is no discrepancy in command options
func (o *CreateOptions) Validate() error {
if err := o.FilenameOptions.RequireFilenameOrKustomize(); err != nil {
return err
}

if len(o.Raw) > 0 {
if o.EditBeforeCreate {
return fmt.Errorf("--raw and --edit are mutually exclusive")
Expand Down
33 changes: 33 additions & 0 deletions staging/src/k8s.io/kubectl/pkg/cmd/create/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/rest/fake"
cmdtesting "k8s.io/kubectl/pkg/cmd/testing"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"k8s.io/kubectl/pkg/scheme"
)

Expand Down Expand Up @@ -150,3 +151,35 @@ func TestCreateDirectory(t *testing.T) {
t.Errorf("unexpected output: %s", buf.String())
}
}

func TestMissingFilenameError(t *testing.T) {
var errStr string
var exitCode int
cmdutil.BehaviorOnFatal(func(str string, code int) {
if errStr == "" {
errStr = str
exitCode = code
}
})

tf := cmdtesting.NewTestFactory().WithNamespace("test")
defer tf.Cleanup()

ioStreams, _, buf, _ := genericiooptions.NewTestIOStreams()
cmd := NewCmdCreate(tf, ioStreams)
cmd.Run(cmd, []string{})

if buf.Len() > 0 {
t.Errorf("unexpected output: %s", buf.String())
}

if len(errStr) == 0 {
t.Errorf("unexpected non-error")
} else if errStr != "error: must specify one of -f and -k" {
t.Errorf("unexpected error: %s", errStr)
}

if exitCode != 1 {
t.Errorf("unexpected exit code: %d", exitCode)
}
}

0 comments on commit c9a1a0a

Please sign in to comment.