Skip to content

Commit

Permalink
fix missing flag value bindings in kubectl
Browse files Browse the repository at this point in the history
  • Loading branch information
dixudx committed May 14, 2018
1 parent 9f7348e commit e8ef744
Show file tree
Hide file tree
Showing 12 changed files with 44 additions and 68 deletions.
6 changes: 3 additions & 3 deletions pkg/kubectl/cmd/clusterinfo_dump.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
4 changes: 1 addition & 3 deletions pkg/kubectl/cmd/cp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down
3 changes: 1 addition & 2 deletions pkg/kubectl/cmd/create/create_job.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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
Expand Down
7 changes: 2 additions & 5 deletions pkg/kubectl/cmd/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 2 additions & 6 deletions pkg/kubectl/cmd/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 9 additions & 11 deletions pkg/kubectl/cmd/get/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}

Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
12 changes: 6 additions & 6 deletions pkg/kubectl/cmd/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]",
Expand All @@ -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.")
Expand All @@ -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 {
Expand Down Expand Up @@ -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()
Expand Down
6 changes: 3 additions & 3 deletions pkg/kubectl/cmd/logs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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()
Expand Down Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions pkg/kubectl/cmd/rollout/rollout_undo.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand All @@ -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)
Expand All @@ -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)

Expand Down
34 changes: 12 additions & 22 deletions pkg/kubectl/cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,39 +155,39 @@ 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.")
cmd.Flags().Bool("rm", false, "If true, delete resources created in this command for attached containers.")
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 {
Expand All @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/kubectl/cmd/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading

0 comments on commit e8ef744

Please sign in to comment.