@@ -28,6 +28,7 @@ import (
28
28
29
29
"github.com/spf13/cobra"
30
30
31
+ "k8s.io/client-go/rest"
31
32
"k8s.io/client-go/tools/clientcmd"
32
33
cliflag "k8s.io/component-base/cli/flag"
33
34
cmdpkg "k8s.io/kubectl/pkg/cmd"
@@ -69,6 +70,7 @@ import (
69
70
"k8s.io/kubectl/pkg/cmd/wait"
70
71
"k8s.io/kubectl/pkg/util/i18n"
71
72
"k8s.io/kubectl/pkg/util/templates"
73
+ "k8s.io/kubectl/pkg/util/term"
72
74
"k8s.io/kubernetes/pkg/kubectl/cmd/auth"
73
75
"k8s.io/kubernetes/pkg/kubectl/cmd/convert"
74
76
"k8s.io/kubernetes/pkg/kubectl/cmd/cp"
@@ -428,6 +430,9 @@ func HandlePluginCommand(pluginHandler PluginHandler, cmdArgs []string) error {
428
430
429
431
// NewKubectlCommand creates the `kubectl` command and its nested children.
430
432
func NewKubectlCommand (in io.Reader , out , err io.Writer ) * cobra.Command {
433
+ warningHandler := rest .NewWarningWriter (err , rest.WarningWriterOptions {Deduplicate : true , Color : term .AllowsColorOutput (err )})
434
+ warningsAsErrors := false
435
+
431
436
// Parent command to which all subcommands are added.
432
437
cmds := & cobra.Command {
433
438
Use : "kubectl" ,
@@ -441,10 +446,25 @@ func NewKubectlCommand(in io.Reader, out, err io.Writer) *cobra.Command {
441
446
// Hook before and after Run initialize and write profiles to disk,
442
447
// respectively.
443
448
PersistentPreRunE : func (* cobra.Command , []string ) error {
449
+ rest .SetDefaultWarningHandler (warningHandler )
444
450
return initProfiling ()
445
451
},
446
452
PersistentPostRunE : func (* cobra.Command , []string ) error {
447
- return flushProfiling ()
453
+ if err := flushProfiling (); err != nil {
454
+ return err
455
+ }
456
+ if warningsAsErrors {
457
+ count := warningHandler .WarningCount ()
458
+ switch count {
459
+ case 0 :
460
+ // no warnings
461
+ case 1 :
462
+ return fmt .Errorf ("%d warning received" , count )
463
+ default :
464
+ return fmt .Errorf ("%d warnings received" , count )
465
+ }
466
+ }
467
+ return nil
448
468
},
449
469
BashCompletionFunction : bashCompletionFunc ,
450
470
}
@@ -458,6 +478,8 @@ func NewKubectlCommand(in io.Reader, out, err io.Writer) *cobra.Command {
458
478
459
479
addProfilingFlags (flags )
460
480
481
+ flags .BoolVar (& warningsAsErrors , "warnings-as-errors" , warningsAsErrors , "Treat warnings received from the server as errors and exit with a non-zero exit code" )
482
+
461
483
kubeConfigFlags := genericclioptions .NewConfigFlags (true ).WithDeprecatedPasswordFlag ()
462
484
kubeConfigFlags .AddFlags (flags )
463
485
matchVersionKubeConfigFlags := cmdutil .NewMatchVersionFlags (kubeConfigFlags )
0 commit comments