Merge pull request #63649 from dixudx/kubectl_flags_binding

Automatic merge from submit-queue (batch tested with PRs 63761, 63794, 63649). If you want to cherry-pick this change to another branch, please follow the instructions <a href="https://github.com/kubernetes/community/blob/master/contributors/devel/cherry-picks.md">here</a>.

fix missing flag value bindings in kubectl

**What this PR does / why we need it**:
When working #63644, I find there are still some flag not bound correctly.

**Which issue(s) this PR fixes** *(optional, in `fixes #<issue number>(, fixes #<issue_number>, ...)` format, will close the issue(s) when PR gets merged)*:
xref #60366

**Special notes for your reviewer**:
/cc soltysh deads2k 
/cc kubernetes/sig-cli-api-reviews 
**Release note**:

```release-note
None
```
pull/8/head
Kubernetes Submit Queue 2018-05-14 07:59:11 -07:00 committed by GitHub
commit ff7abf2705
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 44 additions and 68 deletions

View File

@ -72,9 +72,9 @@ func NewCmdClusterInfoDump(f cmdutil.Factory, ioStreams genericclioptions.IOStre
cmdutil.CheckErr(o.Run())
},
}
cmd.Flags().StringVar(&o.OutputDir, "output-directory", "", i18n.T("Where to output the files. If empty or '-' uses stdout, otherwise creates a directory hierarchy in that directory"))
cmd.Flags().StringSliceVar(&o.Namespaces, "namespaces", []string{}, "A comma separated list of namespaces to dump.")
cmd.Flags().BoolVar(&o.AllNamespaces, "all-namespaces", false, "If true, dump all namespaces. If true, --namespaces is ignored.")
cmd.Flags().StringVar(&o.OutputDir, "output-directory", o.OutputDir, i18n.T("Where to output the files. If empty or '-' uses stdout, otherwise creates a directory hierarchy in that directory"))
cmd.Flags().StringSliceVar(&o.Namespaces, "namespaces", o.Namespaces, "A comma separated list of namespaces to dump.")
cmd.Flags().BoolVar(&o.AllNamespaces, "all-namespaces", o.AllNamespaces, "If true, dump all namespaces. If true, --namespaces is ignored.")
cmdutil.AddPodRunningTimeoutFlag(cmd, defaultPodLogsTimeout)
return cmd
}

View File

@ -96,7 +96,7 @@ func NewCmdCp(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.C
cmdutil.CheckErr(o.Run(args))
},
}
cmd.Flags().StringP("container", "c", "", "Container name. If omitted, the first container in the pod will be chosen")
cmd.Flags().StringVarP(&o.Container, "container", "c", o.Container, "Container name. If omitted, the first container in the pod will be chosen")
return cmd
}
@ -143,8 +143,6 @@ func extractFileSpec(arg string) (fileSpec, error) {
}
func (o *CopyOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
o.Container = cmdutil.GetFlagString(cmd, "container")
var err error
o.Namespace, _, err = f.DefaultNamespace()
if err != nil {

View File

@ -89,7 +89,7 @@ func NewCmdCreateJob(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *
cmdutil.AddApplyAnnotationFlags(cmd)
cmdutil.AddValidateFlags(cmd)
cmdutil.AddDryRunFlag(cmd)
cmd.Flags().String("from", "", "The name of the resource to create a Job from (only cronjob is supported).")
cmd.Flags().StringVar(&o.From, "from", o.From, "The name of the resource to create a Job from (only cronjob is supported).")
return cmd
}
@ -100,7 +100,6 @@ func (o *CreateJobOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args
}
o.Name = args[0]
o.From = cmdutil.GetFlagString(cmd, "from")
o.Namespace, _, err = f.DefaultNamespace()
if err != nil {
return err

View File

@ -113,17 +113,14 @@ func NewCmdDescribe(parent string, f cmdutil.Factory, streams genericclioptions.
}
usage := "containing the resource to describe"
cmdutil.AddFilenameOptionFlags(cmd, o.FilenameOptions, usage)
cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)")
cmd.Flags().Bool("all-namespaces", false, "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.")
cmd.Flags().StringVarP(&o.Selector, "selector", "l", o.Selector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)")
cmd.Flags().BoolVar(&o.AllNamespaces, "all-namespaces", o.AllNamespaces, "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.")
cmd.Flags().BoolVar(&o.DescriberSettings.ShowEvents, "show-events", o.DescriberSettings.ShowEvents, "If true, display events related to the described object.")
cmdutil.AddIncludeUninitializedFlag(cmd)
return cmd
}
func (o *DescribeOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
o.Selector = cmdutil.GetFlagString(cmd, "selector")
o.AllNamespaces = cmdutil.GetFlagBool(cmd, "all-namespaces")
var err error
o.Namespace, o.EnforceNamespace, err = f.DefaultNamespace()
if err != nil {

View File

@ -85,17 +85,13 @@ func NewCmdExplain(parent string, f cmdutil.Factory, streams genericclioptions.I
cmdutil.CheckErr(o.Run(args))
},
}
cmd.Flags().Bool("recursive", false, "Print the fields of fields (Currently only 1 level deep)")
cmd.Flags().String("api-version", "", "Get different explanations for particular API version")
cmd.Flags().BoolVar(&o.Recursive, "recursive", o.Recursive, "Print the fields of fields (Currently only 1 level deep)")
cmd.Flags().StringVar(&o.ApiVersion, "api-version", o.ApiVersion, "Get different explanations for particular API version")
return cmd
}
func (o *ExplainOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
var err error
o.Recursive = cmdutil.GetFlagBool(cmd, "recursive")
o.ApiVersion = cmdutil.GetFlagString(cmd, "api-version")
o.Mapper, err = f.RESTMapper()
if err != nil {
return err

View File

@ -138,8 +138,9 @@ func NewGetOptions(parent string, streams genericclioptions.IOStreams) *GetOptio
PrintFlags: NewGetPrintFlags(legacyscheme.Scheme),
CmdParent: parent,
IOStreams: streams,
ChunkSize: 500,
IOStreams: streams,
ChunkSize: 500,
ServerPrint: true,
}
}
@ -173,8 +174,8 @@ func NewCmdGet(parent string, f cmdutil.Factory, streams genericclioptions.IOStr
cmd.Flags().StringVar(&o.FieldSelector, "field-selector", o.FieldSelector, "Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.")
cmd.Flags().BoolVar(&o.AllNamespaces, "all-namespaces", o.AllNamespaces, "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.")
cmdutil.AddIncludeUninitializedFlag(cmd)
addOpenAPIPrintColumnFlags(cmd)
addServerPrintColumnFlags(cmd)
addOpenAPIPrintColumnFlags(cmd, o)
addServerPrintColumnFlags(cmd, o)
cmd.Flags().BoolVar(&o.Export, "export", o.Export, "If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information.")
cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "identifying the resource to get from a server.")
return cmd
@ -189,8 +190,6 @@ func (o *GetOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []stri
return nil
}
o.ServerPrint = cmdutil.GetFlagBool(cmd, useServerPrintColumns)
var err error
o.Namespace, o.ExplicitNamespace, err = f.DefaultNamespace()
if err != nil {
@ -221,7 +220,6 @@ func (o *GetOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []stri
}
o.IncludeUninitialized = cmdutil.ShouldIncludeUninitialized(cmd, false)
o.PrintWithOpenAPICols = cmdutil.GetFlagBool(cmd, useOpenAPIPrintColumnFlagLabel)
o.ToPrinter = func(mapping *meta.RESTMapping, withNamespace bool) (printers.ResourcePrinterFunc, error) {
// make a new copy of current flags / opts before mutating
@ -720,12 +718,12 @@ func (o *GetOptions) printGeneric(r *resource.Result) error {
return utilerrors.Reduce(utilerrors.Flatten(utilerrors.NewAggregate(errs)))
}
func addOpenAPIPrintColumnFlags(cmd *cobra.Command) {
cmd.Flags().Bool(useOpenAPIPrintColumnFlagLabel, false, "If true, use x-kubernetes-print-column metadata (if present) from the OpenAPI schema for displaying a resource.")
func addOpenAPIPrintColumnFlags(cmd *cobra.Command, opt *GetOptions) {
cmd.Flags().BoolVar(&opt.PrintWithOpenAPICols, useOpenAPIPrintColumnFlagLabel, opt.PrintWithOpenAPICols, "If true, use x-kubernetes-print-column metadata (if present) from the OpenAPI schema for displaying a resource.")
}
func addServerPrintColumnFlags(cmd *cobra.Command) {
cmd.Flags().Bool(useServerPrintColumns, true, "If true, have the server return the appropriate table output. Supports extension APIs and CRDs.")
func addServerPrintColumnFlags(cmd *cobra.Command, opt *GetOptions) {
cmd.Flags().BoolVar(&opt.ServerPrint, useServerPrintColumns, opt.ServerPrint, "If true, have the server return the appropriate table output. Supports extension APIs and CRDs.")
}
func shouldGetNewPrinterForMapping(printer printers.ResourcePrinter, lastMapping, mapping *meta.RESTMapping) bool {

View File

@ -93,15 +93,16 @@ type LogsOptions struct {
genericclioptions.IOStreams
}
func NewLogsOptions(streams genericclioptions.IOStreams) *LogsOptions {
func NewLogsOptions(streams genericclioptions.IOStreams, allContainers bool) *LogsOptions {
return &LogsOptions{
IOStreams: streams,
IOStreams: streams,
AllContainers: allContainers,
}
}
// NewCmdLogs creates a new pod logs command
func NewCmdLogs(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
o := NewLogsOptions(streams)
o := NewLogsOptions(streams, false)
cmd := &cobra.Command{
Use: "logs [-f] [-p] (POD | TYPE/NAME) [-c CONTAINER]",
@ -121,7 +122,7 @@ func NewCmdLogs(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.C
},
Aliases: []string{"log"},
}
cmd.Flags().Bool("all-containers", false, "Get all containers's logs in the pod(s).")
cmd.Flags().BoolVar(&o.AllContainers, "all-containers", o.AllContainers, "Get all containers's logs in the pod(s).")
cmd.Flags().BoolP("follow", "f", false, "Specify if the logs should be streamed.")
cmd.Flags().Bool("timestamps", false, "Include timestamps on each line in the log output")
cmd.Flags().Int64("limit-bytes", 0, "Maximum bytes of logs to return. Defaults to no limit.")
@ -140,7 +141,6 @@ func NewCmdLogs(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.C
func (o *LogsOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
containerName := cmdutil.GetFlagString(cmd, "container")
selector := cmdutil.GetFlagString(cmd, "selector")
o.AllContainers = cmdutil.GetFlagBool(cmd, "all-containers")
switch len(args) {
case 0:
if len(selector) == 0 {
@ -237,7 +237,7 @@ func (o LogsOptions) Validate() error {
return errors.New("unexpected logs options object")
}
if o.AllContainers && len(logsOptions.Container) > 0 {
return fmt.Errorf("--all-containers=true should not be specifiled with container name %s", logsOptions.Container)
return fmt.Errorf("--all-containers=true should not be specified with container name %s", logsOptions.Container)
}
if errs := validation.ValidatePodLogOptions(logsOptions); len(errs) > 0 {
return errs.ToAggregate()

View File

@ -140,7 +140,7 @@ func TestValidateLogFlags(t *testing.T) {
name: "container name combined with --all-containers",
flags: map[string]string{"all-containers": "true"},
args: []string{"my-pod", "my-container"},
expected: "--all-containers=true should not be specifiled with container",
expected: "--all-containers=true should not be specified with container",
},
}
for _, test := range tests {
@ -152,7 +152,7 @@ func TestValidateLogFlags(t *testing.T) {
}
// checkErr breaks tests in case of errors, plus we just
// need to check errors returned by the command validation
o := NewLogsOptions(streams)
o := NewLogsOptions(streams, test.flags["all-containers"] == "true")
cmd.Run = func(cmd *cobra.Command, args []string) {
o.Complete(f, cmd, args)
out = o.Validate().Error()
@ -213,7 +213,7 @@ func TestLogComplete(t *testing.T) {
}
// checkErr breaks tests in case of errors, plus we just
// need to check errors returned by the command validation
o := NewLogsOptions(genericclioptions.NewTestIOStreamsDiscard())
o := NewLogsOptions(genericclioptions.NewTestIOStreamsDiscard(), false)
err = o.Complete(f, cmd, test.args)
out = err.Error()
if !strings.Contains(out, test.expected) {

View File

@ -65,6 +65,7 @@ var (
func NewCmdRolloutUndo(f cmdutil.Factory, out io.Writer) *cobra.Command {
o := &UndoOptions{
PrintFlags: printers.NewPrintFlags("", legacyscheme.Scheme),
ToRevision: int64(0),
}
validArgs := []string{"deployment", "daemonset", "statefulset"}
@ -90,7 +91,7 @@ func NewCmdRolloutUndo(f cmdutil.Factory, out io.Writer) *cobra.Command {
ValidArgs: validArgs,
}
cmd.Flags().Int64("to-revision", 0, "The revision to rollback to. Default to 0 (last revision).")
cmd.Flags().Int64Var(&o.ToRevision, "to-revision", o.ToRevision, "The revision to rollback to. Default to 0 (last revision).")
usage := "identifying the resource to get from a server."
cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, usage)
cmdutil.AddDryRunFlag(cmd)
@ -102,7 +103,6 @@ func (o *UndoOptions) CompleteUndo(f cmdutil.Factory, cmd *cobra.Command, out io
return cmdutil.UsageErrorf(cmd, "Required resource not specified.")
}
o.ToRevision = cmdutil.GetFlagInt64(cmd, "to-revision")
o.Out = out
o.DryRun = cmdutil.GetDryRunFlag(cmd)

View File

@ -155,16 +155,16 @@ func NewCmdRun(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Co
o.PrintFlags.AddFlags(cmd)
o.RecordFlags.AddFlags(cmd)
addRunFlags(cmd)
addRunFlags(cmd, o)
cmdutil.AddApplyAnnotationFlags(cmd)
cmdutil.AddPodRunningTimeoutFlag(cmd, defaultPodAttachTimeout)
return cmd
}
func addRunFlags(cmd *cobra.Command) {
func addRunFlags(cmd *cobra.Command, opt *RunOptions) {
cmdutil.AddDryRunFlag(cmd)
cmd.Flags().String("generator", "", i18n.T("The name of the API generator to use, see http://kubernetes.io/docs/user-guide/kubectl-conventions/#generators for a list."))
cmd.Flags().String("image", "", i18n.T("The image for the container to run."))
cmd.Flags().StringVar(&opt.Generator, "generator", opt.Generator, i18n.T("The name of the API generator to use, see http://kubernetes.io/docs/user-guide/kubectl-conventions/#generators for a list."))
cmd.Flags().StringVar(&opt.Image, "image", opt.Image, i18n.T("The image for the container to run."))
cmd.MarkFlagRequired("image")
cmd.Flags().String("image-pull-policy", "", i18n.T("The image pull policy for the container. If left empty, this value will not be specified by the client and defaulted by the server"))
cmd.Flags().IntP("replicas", "r", 1, "Number of replicas to create for this container. Default is 1.")
@ -172,22 +172,22 @@ func addRunFlags(cmd *cobra.Command) {
cmd.Flags().String("overrides", "", i18n.T("An inline JSON override for the generated object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field."))
cmd.Flags().StringArray("env", []string{}, "Environment variables to set in the container")
cmd.Flags().String("serviceaccount", "", "Service account to set in the pod spec")
cmd.Flags().String("port", "", i18n.T("The port that this container exposes. If --expose is true, this is also the port used by the service that is created."))
cmd.Flags().StringVar(&opt.Port, "port", opt.Port, i18n.T("The port that this container exposes. If --expose is true, this is also the port used by the service that is created."))
cmd.Flags().Int("hostport", -1, "The host port mapping for the container port. To demonstrate a single-machine container.")
cmd.Flags().StringP("labels", "l", "", "Comma separated labels to apply to the pod(s). Will override previous values.")
cmd.Flags().BoolP("stdin", "i", false, "Keep stdin open on the container(s) in the pod, even if nothing is attached.")
cmd.Flags().BoolP("tty", "t", false, "Allocated a TTY for each container in the pod.")
cmd.Flags().Bool("attach", false, "If true, wait for the Pod to start running, and then attach to the Pod as if 'kubectl attach ...' were called. Default false, unless '-i/--stdin' is set, in which case the default is true. With '--restart=Never' the exit code of the container process is returned.")
cmd.Flags().Bool("leave-stdin-open", false, "If the pod is started in interactive mode or with stdin, leave stdin open after the first attach completes. By default, stdin will be closed after the first attach completes.")
cmd.Flags().BoolVarP(&opt.Interactive, "stdin", "i", opt.Interactive, "Keep stdin open on the container(s) in the pod, even if nothing is attached.")
cmd.Flags().BoolVarP(&opt.TTY, "tty", "t", opt.TTY, "Allocated a TTY for each container in the pod.")
cmd.Flags().BoolVar(&opt.Attach, "attach", opt.Attach, "If true, wait for the Pod to start running, and then attach to the Pod as if 'kubectl attach ...' were called. Default false, unless '-i/--stdin' is set, in which case the default is true. With '--restart=Never' the exit code of the container process is returned.")
cmd.Flags().BoolVar(&opt.LeaveStdinOpen, "leave-stdin-open", opt.LeaveStdinOpen, "If the pod is started in interactive mode or with stdin, leave stdin open after the first attach completes. By default, stdin will be closed after the first attach completes.")
cmd.Flags().String("restart", "Always", i18n.T("The restart policy for this Pod. Legal values [Always, OnFailure, Never]. If set to 'Always' a deployment is created, if set to 'OnFailure' a job is created, if set to 'Never', a regular pod is created. For the latter two --replicas must be 1. Default 'Always', for CronJobs `Never`."))
cmd.Flags().Bool("command", false, "If true and extra arguments are present, use them as the 'command' field in the container, rather than the 'args' field which is the default.")
cmd.Flags().String("requests", "", i18n.T("The resource requirement requests for this container. For example, 'cpu=100m,memory=256Mi'. Note that server side components may assign requests depending on the server configuration, such as limit ranges."))
cmd.Flags().String("limits", "", i18n.T("The resource requirement limits for this container. For example, 'cpu=200m,memory=512Mi'. Note that server side components may assign limits depending on the server configuration, such as limit ranges."))
cmd.Flags().Bool("expose", false, "If true, a public, external service is created for the container(s) which are run")
cmd.Flags().BoolVar(&opt.Expose, "expose", opt.Expose, "If true, a public, external service is created for the container(s) which are run")
cmd.Flags().String("service-generator", "service/v2", i18n.T("The name of the generator to use for creating a service. Only used if --expose is true"))
cmd.Flags().String("service-overrides", "", i18n.T("An inline JSON override for the generated service object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field. Only used if --expose is true."))
cmd.Flags().Bool("quiet", false, "If true, suppress prompt messages.")
cmd.Flags().String("schedule", "", i18n.T("A schedule in the Cron format the job should be run with."))
cmd.Flags().BoolVar(&opt.Quiet, "quiet", opt.Quiet, "If true, suppress prompt messages.")
cmd.Flags().StringVar(&opt.Schedule, "schedule", opt.Schedule, i18n.T("A schedule in the Cron format the job should be run with."))
}
func (o *RunOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
@ -206,18 +206,8 @@ func (o *RunOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
o.ArgsLenAtDash = cmd.ArgsLenAtDash()
o.DryRun = cmdutil.GetFlagBool(cmd, "dry-run")
o.Expose = cmdutil.GetFlagBool(cmd, "expose")
o.Generator = cmdutil.GetFlagString(cmd, "generator")
o.Image = cmdutil.GetFlagString(cmd, "image")
o.Interactive = cmdutil.GetFlagBool(cmd, "stdin")
o.LeaveStdinOpen = cmdutil.GetFlagBool(cmd, "leave-stdin-open")
o.Port = cmdutil.GetFlagString(cmd, "port")
o.Quiet = cmdutil.GetFlagBool(cmd, "quiet")
o.Schedule = cmdutil.GetFlagString(cmd, "schedule")
o.TTY = cmdutil.GetFlagBool(cmd, "tty")
attachFlag := cmd.Flags().Lookup("attach")
o.Attach = cmdutil.GetFlagBool(cmd, "attach")
if !attachFlag.Changed && o.Interactive {
o.Attach = true
}

View File

@ -392,7 +392,7 @@ func TestGenerateService(t *testing.T) {
cmd := &cobra.Command{}
cmd.Flags().Bool(cmdutil.ApplyAnnotationsFlag, false, "")
cmd.Flags().Bool("record", false, "Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.")
addRunFlags(cmd)
addRunFlags(cmd, opts)
if !test.expectPOST {
opts.DryRun = true

View File

@ -108,8 +108,8 @@ func NewCmdSelector(f cmdutil.Factory, streams genericclioptions.IOStreams) *cob
o.PrintFlags.AddFlags(cmd)
o.RecordFlags.AddFlags(cmd)
cmd.Flags().Bool("all", false, "Select all resources, including uninitialized ones, in the namespace of the specified resource types")
cmd.Flags().Bool("local", false, "If true, set selector will NOT contact api-server but run locally.")
cmd.Flags().BoolVar(&o.all, "all", o.all, "Select all resources, including uninitialized ones, in the namespace of the specified resource types")
cmd.Flags().BoolVar(&o.local, "local", o.local, "If true, set selector will NOT contact api-server but run locally.")
cmd.Flags().String("resource-version", "", "If non-empty, the selectors update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.")
usage := "the resource to update the selectors"
cmdutil.AddFilenameOptionFlags(cmd, &o.fileOptions, usage)
@ -129,8 +129,6 @@ func (o *SetSelectorOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, arg
return err
}
o.local = cmdutil.GetFlagBool(cmd, "local")
o.all = cmdutil.GetFlagBool(cmd, "all")
o.dryrun = cmdutil.GetDryRunFlag(cmd)
o.output = cmdutil.GetFlagString(cmd, "output")