kubectl/cmd: many small refactors

* Rename variables and functions to match Go convention.
   For example, UsageError --> UsageErrorf.
 * Remove redundant or unreachable code.
 * Simplify some utility functions (no functionality changes).
 * Fix hanging 'if { return } else { return }' constructs.
 * Fix several incorrect printf verbs.
This commit is contained in:
Alexander Campbell 2017-06-14 14:14:42 -07:00
parent 98ee52ed78
commit 6fd36c10ad
46 changed files with 148 additions and 155 deletions

View File

@ -117,10 +117,10 @@ func NewCmdAnnotate(f cmdutil.Factory, out io.Writer) *cobra.Command {
Example: annotateExample,
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(out, cmd, args); err != nil {
cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
cmdutil.CheckErr(cmdutil.UsageErrorf(cmd, "%v", err))
}
if err := options.Validate(); err != nil {
cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
cmdutil.CheckErr(cmdutil.UsageErrorf(cmd, "%v", err))
}
cmdutil.CheckErr(options.RunAnnotate(f, cmd))
},
@ -167,7 +167,7 @@ func (o *AnnotateOptions) Complete(out io.Writer, cmd *cobra.Command, args []str
// Validate checks to the AnnotateOptions to see if there is sufficient information run the command.
func (o AnnotateOptions) Validate() error {
if len(o.resources) < 1 && cmdutil.IsFilenameEmpty(o.Filenames) {
if len(o.resources) < 1 && cmdutil.IsFilenameSliceEmpty(o.Filenames) {
return fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>")
}
if len(o.newAnnotations) < 1 && len(o.removeAnnotations) < 1 {

View File

@ -137,7 +137,7 @@ func NewCmdApply(f cmdutil.Factory, out, errOut io.Writer) *cobra.Command {
func validateArgs(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
return cmdutil.UsageError(cmd, "Unexpected args: %v", args)
return cmdutil.UsageErrorf(cmd, "Unexpected args: %v", args)
}
return nil

View File

@ -161,7 +161,7 @@ func (o *SetLastAppliedOptions) Validate(f cmdutil.Factory, cmd *cobra.Command)
return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving current configuration of:\n%v\nfrom server for:", info), info.Source, err)
}
if oringalBuf == nil && !o.CreateAnnotation {
return cmdutil.UsageError(cmd, "no last-applied-configuration annotation found on resource: %s, to create the annotation, run the command with --create-annotation", info.Name)
return cmdutil.UsageErrorf(cmd, "no last-applied-configuration annotation found on resource: %s, to create the annotation, run the command with --create-annotation", info.Name)
}
//only add to PatchBufferList when changed

View File

@ -55,7 +55,7 @@ func TestApplyExtraArgsFail(t *testing.T) {
func validateApplyArgs(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
return cmdutil.UsageError(cmd, "Unexpected args: %v", args)
return cmdutil.UsageErrorf(cmd, "Unexpected args: %v", args)
}
return nil
}

View File

@ -166,6 +166,6 @@ func (o *ViewLastAppliedOptions) ValidateOutputArgs(cmd *cobra.Command) error {
o.OutputFormat = "yaml"
return nil
default:
return cmdutil.UsageError(cmd, "Unexpected -o output mode: %s, the flag 'output' must be one of yaml|json", format)
return cmdutil.UsageErrorf(cmd, "Unexpected -o output mode: %s, the flag 'output' must be one of yaml|json", format)
}
}

View File

@ -17,6 +17,7 @@ limitations under the License.
package cmd
import (
"errors"
"fmt"
"io"
"net/url"
@ -127,10 +128,10 @@ type AttachOptions struct {
// Complete verifies command line arguments and loads data from the command environment
func (p *AttachOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, argsIn []string) error {
if len(argsIn) == 0 {
return cmdutil.UsageError(cmd, "at least one argument is required for attach")
return cmdutil.UsageErrorf(cmd, "at least 1 argument is required for attach")
}
if len(argsIn) > 2 {
return cmdutil.UsageError(cmd, fmt.Sprintf("expected fewer than three arguments: POD or TYPE/NAME or TYPE NAME, saw %d: %s", len(argsIn), argsIn))
return cmdutil.UsageErrorf(cmd, "expected POD, TYPE/NAME, or TYPE NAME, (at most 2 arguments) saw %d: %v", len(argsIn), argsIn)
}
namespace, _, err := f.DefaultNamespace()
@ -140,7 +141,7 @@ func (p *AttachOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, argsIn [
p.GetPodTimeout, err = cmdutil.GetPodRunningTimeoutFlag(cmd)
if err != nil {
return cmdutil.UsageError(cmd, err.Error())
return cmdutil.UsageErrorf(cmd, err.Error())
}
builder := f.NewBuilder(true).
@ -189,13 +190,13 @@ func (p *AttachOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, argsIn [
func (p *AttachOptions) Validate() error {
allErrs := []error{}
if len(p.PodName) == 0 {
allErrs = append(allErrs, fmt.Errorf("pod name must be specified"))
allErrs = append(allErrs, errors.New("pod name must be specified"))
}
if p.Out == nil || p.Err == nil {
allErrs = append(allErrs, fmt.Errorf("both output and error output must be provided"))
allErrs = append(allErrs, errors.New("both output and error output must be provided"))
}
if p.Attach == nil || p.PodClient == nil || p.Config == nil {
allErrs = append(allErrs, fmt.Errorf("client, client config, and attach must be provided"))
allErrs = append(allErrs, errors.New("client, client config, and attach must be provided"))
}
return utilerrors.NewAggregate(allErrs)
}

View File

@ -108,7 +108,7 @@ func RunAutoscale(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []s
generators := f.Generators("autoscale")
generator, found := generators[generatorName]
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
return cmdutil.UsageErrorf(cmd, "generator %q not found.", generatorName)
}
names := generator.ParamNames()

View File

@ -59,7 +59,7 @@ func (options *CertificateOptions) Complete(cmd *cobra.Command, args []string) e
}
func (options *CertificateOptions) Validate() error {
if len(options.csrNames) < 1 && cmdutil.IsFilenameEmpty(options.Filenames) {
if len(options.csrNames) < 1 && cmdutil.IsFilenameSliceEmpty(options.Filenames) {
return fmt.Errorf("one or more CSRs must be specified as <name> or -f <filename>")
}
return nil

View File

@ -91,7 +91,7 @@ func setupOutputWriter(cmd *cobra.Command, defaultWriter io.Writer, filename str
func dumpClusterInfo(f cmdutil.Factory, cmd *cobra.Command, out io.Writer) error {
timeout, err := cmdutil.GetPodRunningTimeoutFlag(cmd)
if err != nil {
return cmdutil.UsageError(cmd, err.Error())
return cmdutil.UsageErrorf(cmd, err.Error())
}
clientset, err := f.ClientSet()

View File

@ -116,14 +116,14 @@ func NewCmdCompletion(out io.Writer, boilerPlate string) *cobra.Command {
func RunCompletion(out io.Writer, boilerPlate string, cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return cmdutil.UsageError(cmd, "Shell not specified.")
return cmdutil.UsageErrorf(cmd, "Shell not specified.")
}
if len(args) > 1 {
return cmdutil.UsageError(cmd, "Too many arguments. Expected only the shell type.")
return cmdutil.UsageErrorf(cmd, "Too many arguments. Expected only the shell type.")
}
run, found := completion_shells[args[0]]
if !found {
return cmdutil.UsageError(cmd, "Unsupported shell type %q.", args[0])
return cmdutil.UsageErrorf(cmd, "Unsupported shell type %q.", args[0])
}
if len(boilerPlate) == 0 {

View File

@ -70,7 +70,7 @@ func NewCmdConfigRenameContext(out io.Writer, configAccess clientcmd.ConfigAcces
cmdutil.CheckErr(err)
}
if err := options.Validate(); err != nil {
cmdutil.UsageError(cmd, err.Error())
cmdutil.UsageErrorf(cmd, err.Error())
}
if err := options.RunRenameContext(out); err != nil {
cmdutil.CheckErr(err)

View File

@ -122,7 +122,7 @@ func (o *ConvertOptions) Complete(f cmdutil.Factory, out io.Writer, cmd *cobra.C
return err
}
if !api.Registry.IsEnabledVersion(o.outputVersion) {
cmdutil.UsageError(cmd, "'%s' is not a registered version.", o.outputVersion)
cmdutil.UsageErrorf(cmd, "'%s' is not a registered version.", o.outputVersion)
}
// build the builder

View File

@ -18,7 +18,7 @@ package cmd
import (
"archive/tar"
"fmt"
"errors"
"io"
"io/ioutil"
"os"
@ -80,13 +80,17 @@ type fileSpec struct {
File string
}
var errFileSpecDoesntMatchFormat = errors.New("Filespec must match the canonical format: [[namespace/]pod:]file/path")
func extractFileSpec(arg string) (fileSpec, error) {
pieces := strings.Split(arg, ":")
if len(pieces) == 1 {
return fileSpec{File: arg}, nil
}
if len(pieces) != 2 {
return fileSpec{}, fmt.Errorf("Unexpected fileSpec: %s, expected [[namespace/]pod:]file/path", arg)
// FIXME Kubernetes can't copy files that contain a ':'
// character.
return fileSpec{}, errFileSpecDoesntMatchFormat
}
file := pieces[1]
@ -105,12 +109,12 @@ func extractFileSpec(arg string) (fileSpec, error) {
}, nil
}
return fileSpec{}, fmt.Errorf("Unexpected file spec: %s, expected [[namespace/]pod:]file/path", arg)
return fileSpec{}, errFileSpecDoesntMatchFormat
}
func runCopy(f cmdutil.Factory, cmd *cobra.Command, out, cmderr io.Writer, args []string) error {
if len(args) != 2 {
return cmdutil.UsageError(cmd, cpUsageStr)
return cmdutil.UsageErrorf(cmd, cpUsageStr)
}
srcSpec, err := extractFileSpec(args[0])
if err != nil {
@ -126,7 +130,7 @@ func runCopy(f cmdutil.Factory, cmd *cobra.Command, out, cmderr io.Writer, args
if len(destSpec.PodName) != 0 {
return copyToPod(f, cmd, out, cmderr, srcSpec, destSpec)
}
return cmdutil.UsageError(cmd, "One of src or dest must be a remote file specification")
return cmdutil.UsageErrorf(cmd, "One of src or dest must be a remote file specification")
}
func copyToPod(f cmdutil.Factory, cmd *cobra.Command, stdout, stderr io.Writer, src, dest fileSpec) error {

View File

@ -64,7 +64,7 @@ func NewCmdCreate(f cmdutil.Factory, out, errOut io.Writer) *cobra.Command {
Long: createLong,
Example: createExample,
Run: func(cmd *cobra.Command, args []string) {
if cmdutil.IsFilenameEmpty(options.FilenameOptions.Filenames) {
if cmdutil.IsFilenameSliceEmpty(options.FilenameOptions.Filenames) {
defaultRunFunc := cmdutil.DefaultSubCommandRun(errOut)
defaultRunFunc(cmd, args)
return
@ -106,7 +106,7 @@ func NewCmdCreate(f cmdutil.Factory, out, errOut io.Writer) *cobra.Command {
func ValidateArgs(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
return cmdutil.UsageError(cmd, "Unexpected args: %v", args)
return cmdutil.UsageErrorf(cmd, "Unexpected args: %v", args)
}
return nil
}
@ -229,7 +229,7 @@ func createAndRefresh(info *resource.Info) error {
// NameFromCommandArgs is a utility function for commands that assume the first argument is a resource name
func NameFromCommandArgs(cmd *cobra.Command, args []string) (string, error) {
if len(args) == 0 {
return "", cmdutil.UsageError(cmd, "NAME is required")
return "", cmdutil.UsageErrorf(cmd, "NAME is required")
}
return args[0], nil
}
@ -241,8 +241,7 @@ type CreateSubcommandOptions struct {
// StructuredGenerator is the resource generator for the object being created
StructuredGenerator kubectl.StructuredGenerator
// DryRun is true if the command should be simulated but not run against the server
DryRun bool
// OutputFormat
DryRun bool
OutputFormat string
}

View File

@ -176,7 +176,7 @@ func CreateSecretDockerRegistry(f cmdutil.Factory, cmdOut io.Writer, cmd *cobra.
requiredFlags := []string{"docker-username", "docker-password", "docker-email", "docker-server"}
for _, requiredFlag := range requiredFlags {
if value := cmdutil.GetFlagString(cmd, requiredFlag); len(value) == 0 {
return cmdutil.UsageError(cmd, "flag %s is required", requiredFlag)
return cmdutil.UsageErrorf(cmd, "flag %s is required", requiredFlag)
}
}
var generator kubectl.StructuredGenerator
@ -241,7 +241,7 @@ func CreateSecretTLS(f cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, ar
requiredFlags := []string{"cert", "key"}
for _, requiredFlag := range requiredFlags {
if value := cmdutil.GetFlagString(cmd, requiredFlag); len(value) == 0 {
return cmdutil.UsageError(cmd, "flag %s is required", requiredFlag)
return cmdutil.UsageErrorf(cmd, "flag %s is required", requiredFlag)
}
}
var generator kubectl.StructuredGenerator

View File

@ -83,7 +83,7 @@ func NewCmdCreateServiceClusterIP(f cmdutil.Factory, cmdOut io.Writer) *cobra.Co
}
func errUnsupportedGenerator(cmd *cobra.Command, generatorName string) error {
return cmdutil.UsageError(cmd, "Generator %s not supported. ", generatorName)
return cmdutil.UsageErrorf(cmd, "Generator %s not supported. ", generatorName)
}
// CreateServiceClusterIP implements the behavior to run the create service clusterIP command

View File

@ -137,7 +137,7 @@ func NewCmdDelete(f cmdutil.Factory, out, errOut io.Writer) *cobra.Command {
cmdutil.CheckErr(err)
}
if err := options.Validate(cmd); err != nil {
cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
cmdutil.CheckErr(cmdutil.UsageErrorf(cmd, err.Error()))
}
if err := options.RunDelete(); err != nil {
cmdutil.CheckErr(err)

View File

@ -110,9 +110,9 @@ func RunDescribe(f cmdutil.Factory, out, cmdErr io.Writer, cmd *cobra.Command, a
if allNamespaces {
enforceNamespace = false
}
if len(args) == 0 && cmdutil.IsFilenameEmpty(options.Filenames) {
if len(args) == 0 && cmdutil.IsFilenameSliceEmpty(options.Filenames) {
fmt.Fprint(cmdErr, "You must specify the type of resource to describe. ", validResources)
return cmdutil.UsageError(cmd, "Required resource not specified.")
return cmdutil.UsageErrorf(cmd, "Required resource not specified.")
}
builder, err := f.NewUnstructuredBuilder(true)

View File

@ -197,7 +197,7 @@ func NewCmdDrain(f cmdutil.Factory, out, errOut io.Writer) *cobra.Command {
func (o *DrainOptions) SetupDrain(cmd *cobra.Command, args []string) error {
var err error
if len(args) != 1 {
return cmdutil.UsageError(cmd, fmt.Sprintf("USAGE: %s [flags]", cmd.Use))
return cmdutil.UsageErrorf(cmd, "USAGE: %s [flags]", cmd.Use)
}
if o.client, err = o.Factory.ClientSet(); err != nil {

View File

@ -152,19 +152,19 @@ type ExecOptions struct {
func (p *ExecOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, argsIn []string, argsLenAtDash int) error {
// Let kubectl exec follow rules for `--`, see #13004 issue
if len(p.PodName) == 0 && (len(argsIn) == 0 || argsLenAtDash == 0) {
return cmdutil.UsageError(cmd, execUsageStr)
return cmdutil.UsageErrorf(cmd, execUsageStr)
}
if len(p.PodName) != 0 {
printDeprecationWarning("exec POD_NAME", "-p POD_NAME")
if len(argsIn) < 1 {
return cmdutil.UsageError(cmd, execUsageStr)
return cmdutil.UsageErrorf(cmd, execUsageStr)
}
p.Command = argsIn
} else {
p.PodName = argsIn[0]
p.Command = argsIn[1:]
if len(p.Command) < 1 {
return cmdutil.UsageError(cmd, execUsageStr)
return cmdutil.UsageErrorf(cmd, execUsageStr)
}
}

View File

@ -66,10 +66,10 @@ func NewCmdExplain(f cmdutil.Factory, out, cmdErr io.Writer) *cobra.Command {
func RunExplain(f cmdutil.Factory, out, cmdErr io.Writer, cmd *cobra.Command, args []string) error {
if len(args) == 0 {
fmt.Fprint(cmdErr, "You must specify the type of resource to explain. ", validResources)
return cmdutil.UsageError(cmd, "Required resource not specified.")
return cmdutil.UsageErrorf(cmd, "Required resource not specified.")
}
if len(args) > 1 {
return cmdutil.UsageError(cmd, "We accept only this format: explain RESOURCE")
return cmdutil.UsageErrorf(cmd, "We accept only this format: explain RESOURCE")
}
recursive := cmdutil.GetFlagBool(cmd, "recursive")

View File

@ -17,7 +17,6 @@ limitations under the License.
package cmd
import (
"fmt"
"io"
"regexp"
"strings"
@ -136,7 +135,7 @@ func RunExpose(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []stri
Do()
err = r.Err()
if err != nil {
return cmdutil.UsageError(cmd, err.Error())
return cmdutil.UsageErrorf(cmd, err.Error())
}
// Get the generator, setup and validate all required parameters
@ -144,7 +143,7 @@ func RunExpose(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []stri
generators := f.Generators("expose")
generator, found := generators[generatorName]
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
return cmdutil.UsageErrorf(cmd, "generator %q not found.", generatorName)
}
names := generator.ParamNames()
@ -170,7 +169,7 @@ func RunExpose(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []stri
if s, found := params["selector"]; found && kubectl.IsZero(s) {
s, err := f.MapBasedSelectorForObject(info.Object)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't retrieve selectors via --selector flag or introspection: %s", err))
return cmdutil.UsageErrorf(cmd, "couldn't retrieve selectors via --selector flag or introspection: %v", err)
}
params["selector"] = s
}
@ -182,12 +181,12 @@ func RunExpose(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []stri
if port, found := params["port"]; found && kubectl.IsZero(port) {
ports, err := f.PortsForObject(info.Object)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find port via --port flag or introspection: %s", err))
return cmdutil.UsageErrorf(cmd, "couldn't find port via --port flag or introspection: %v", err)
}
switch len(ports) {
case 0:
if !isHeadlessService {
return cmdutil.UsageError(cmd, "couldn't find port via --port flag or introspection")
return cmdutil.UsageErrorf(cmd, "couldn't find port via --port flag or introspection")
}
case 1:
params["port"] = ports[0]
@ -201,7 +200,7 @@ func RunExpose(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []stri
if _, found := params["protocol"]; found {
protocolsMap, err := f.ProtocolsForObject(info.Object)
if err != nil {
return cmdutil.UsageError(cmd, fmt.Sprintf("couldn't find protocol via introspection: %s", err))
return cmdutil.UsageErrorf(cmd, "couldn't find protocol via introspection: %v", err)
}
if protocols := kubectl.MakeProtocols(protocolsMap); !kubectl.IsZero(protocols) {
params["protocols"] = protocols

View File

@ -51,7 +51,7 @@ type GetOptions struct {
}
var (
get_long = templates.LongDesc(`
getLong = templates.LongDesc(`
Display one or many resources.
` + validResources + `
@ -63,7 +63,7 @@ var (
By specifying the output as 'template' and providing a Go template as the value
of the --template flag, you can filter the attributes of the fetched resources.`)
get_example = templates.Examples(i18n.T(`
getExample = templates.Examples(i18n.T(`
# List all pods in ps output format.
kubectl get pods
@ -115,8 +115,8 @@ func NewCmdGet(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Comman
cmd := &cobra.Command{
Use: "get [(-o|--output=)json|yaml|wide|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...] (TYPE [NAME | -l label] | TYPE/NAME ...) [flags]",
Short: i18n.T("Display one or many resources"),
Long: get_long,
Example: get_example,
Long: getLong,
Example: getExample,
Run: func(cmd *cobra.Command, args []string) {
err := RunGet(f, out, errOut, cmd, args, options)
cmdutil.CheckErr(err)
@ -182,7 +182,7 @@ func RunGet(f cmdutil.Factory, out, errOut io.Writer, cmd *cobra.Command, args [
enforceNamespace = false
}
if len(args) == 0 && cmdutil.IsFilenameEmpty(options.Filenames) {
if len(args) == 0 && cmdutil.IsFilenameSliceEmpty(options.Filenames) {
fmt.Fprint(errOut, "You must specify the type of resource to get. ", validResources)
fullCmdName := cmd.Parent().CommandPath()
@ -191,7 +191,7 @@ func RunGet(f cmdutil.Factory, out, errOut io.Writer, cmd *cobra.Command, args [
usageString = fmt.Sprintf("%s\nUse \"%s explain <resource>\" for a detailed description of that resource (e.g. %[2]s explain pods).", usageString, fullCmdName)
}
return cmdutil.UsageError(cmd, usageString)
return cmdutil.UsageErrorf(cmd, usageString)
}
export := cmdutil.GetFlagBool(cmd, "export")

View File

@ -115,10 +115,10 @@ func NewCmdLabel(f cmdutil.Factory, out io.Writer) *cobra.Command {
Example: labelExample,
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(out, cmd, args); err != nil {
cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
cmdutil.CheckErr(cmdutil.UsageErrorf(cmd, err.Error()))
}
if err := options.Validate(); err != nil {
cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
cmdutil.CheckErr(cmdutil.UsageErrorf(cmd, err.Error()))
}
cmdutil.CheckErr(options.RunLabel(f, cmd))
},
@ -162,7 +162,7 @@ func (o *LabelOptions) Complete(out io.Writer, cmd *cobra.Command, args []string
// Validate checks to the LabelOptions to see if there is sufficient information run the command.
func (o *LabelOptions) Validate() error {
if len(o.resources) < 1 && cmdutil.IsFilenameEmpty(o.FilenameOptions.Filenames) {
if len(o.resources) < 1 && cmdutil.IsFilenameSliceEmpty(o.FilenameOptions.Filenames) {
return fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>")
}
if len(o.newLabels) < 1 && len(o.removeLabels) < 1 {

View File

@ -127,21 +127,21 @@ func (o *LogsOptions) Complete(f cmdutil.Factory, out io.Writer, cmd *cobra.Comm
switch len(args) {
case 0:
if len(selector) == 0 {
return cmdutil.UsageError(cmd, logsUsageStr)
return cmdutil.UsageErrorf(cmd, "%s", logsUsageStr)
}
case 1:
o.ResourceArg = args[0]
if len(selector) != 0 {
return cmdutil.UsageError(cmd, "only a selector (-l) or a POD name is allowed")
return cmdutil.UsageErrorf(cmd, "only a selector (-l) or a POD name is allowed")
}
case 2:
if cmd.Flag("container").Changed {
return cmdutil.UsageError(cmd, "only one of -c or an inline [CONTAINER] arg is allowed")
return cmdutil.UsageErrorf(cmd, "only one of -c or an inline [CONTAINER] arg is allowed")
}
o.ResourceArg = args[0]
containerName = args[1]
default:
return cmdutil.UsageError(cmd, logsUsageStr)
return cmdutil.UsageErrorf(cmd, "%s", logsUsageStr)
}
var err error
o.Namespace, _, err = f.DefaultNamespace()
@ -183,7 +183,7 @@ func (o *LogsOptions) Complete(f cmdutil.Factory, out io.Writer, cmd *cobra.Comm
if len(selector) != 0 {
if logOptions.Follow {
return cmdutil.UsageError(cmd, "only one of follow (-f) or selector (-l) is allowed")
return cmdutil.UsageErrorf(cmd, "only one of follow (-f) or selector (-l) is allowed")
}
if logOptions.TailLines == nil {
logOptions.TailLines = &selectorTail

View File

@ -136,13 +136,14 @@ func RunPatch(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []strin
ok := false
patchType, ok = patchTypes[patchTypeString]
if !ok {
return cmdutil.UsageError(cmd, fmt.Sprintf("--type must be one of %v, not %q", sets.StringKeySet(patchTypes).List(), patchTypeString))
return cmdutil.UsageErrorf(cmd, "--type must be one of %v, not %q",
sets.StringKeySet(patchTypes).List(), patchTypeString)
}
}
patch := cmdutil.GetFlagString(cmd, "patch")
if len(patch) == 0 {
return cmdutil.UsageError(cmd, "Must specify -p to patch")
return cmdutil.UsageErrorf(cmd, "Must specify -p to patch")
}
patchBytes, err := yaml.ToJSON([]byte(patch))
if err != nil {

View File

@ -81,7 +81,7 @@ func NewCmdPortForward(f cmdutil.Factory, cmdOut, cmdErr io.Writer) *cobra.Comma
cmdutil.CheckErr(err)
}
if err := opts.Validate(); err != nil {
cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
cmdutil.CheckErr(cmdutil.UsageErrorf(cmd, "%v", err.Error()))
}
if err := opts.RunPortForward(); err != nil {
cmdutil.CheckErr(err)
@ -118,7 +118,7 @@ func (o *PortForwardOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, arg
var err error
o.PodName = cmdutil.GetFlagString(cmd, "pod")
if len(o.PodName) == 0 && len(args) == 0 {
return cmdutil.UsageError(cmd, "POD is required for port-forward")
return cmdutil.UsageErrorf(cmd, "POD is required for port-forward")
}
if len(o.PodName) != 0 {

View File

@ -103,8 +103,8 @@ func RunReplace(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []str
}
force := cmdutil.GetFlagBool(cmd, "force")
if cmdutil.IsFilenameEmpty(options.Filenames) {
return cmdutil.UsageError(cmd, "Must specify --filename to replace")
if cmdutil.IsFilenameSliceEmpty(options.Filenames) {
return cmdutil.UsageErrorf(cmd, "Must specify --filename to replace")
}
shortOutput := cmdutil.GetFlagString(cmd, "output") == "name"

View File

@ -114,26 +114,26 @@ func validateArguments(cmd *cobra.Command, filenames, args []string) error {
errors := []error{}
if len(deploymentKey) == 0 {
errors = append(errors, cmdutil.UsageError(cmd, "--deployment-label-key can not be empty"))
errors = append(errors, cmdutil.UsageErrorf(cmd, "--deployment-label-key can not be empty"))
}
if len(filenames) > 1 {
errors = append(errors, cmdutil.UsageError(cmd, "May only specify a single filename for new controller"))
errors = append(errors, cmdutil.UsageErrorf(cmd, "May only specify a single filename for new controller"))
}
if !rollback {
if len(filenames) == 0 && len(image) == 0 {
errors = append(errors, cmdutil.UsageError(cmd, "Must specify --filename or --image for new controller"))
errors = append(errors, cmdutil.UsageErrorf(cmd, "Must specify --filename or --image for new controller"))
} else if len(filenames) != 0 && len(image) != 0 {
errors = append(errors, cmdutil.UsageError(cmd, "--filename and --image can not both be specified"))
errors = append(errors, cmdutil.UsageErrorf(cmd, "--filename and --image can not both be specified"))
}
} else {
if len(filenames) != 0 || len(image) != 0 {
errors = append(errors, cmdutil.UsageError(cmd, "Don't specify --filename or --image on rollback"))
errors = append(errors, cmdutil.UsageErrorf(cmd, "Don't specify --filename or --image on rollback"))
}
}
if len(args) < 1 {
errors = append(errors, cmdutil.UsageError(cmd, "Must specify the controller to update"))
errors = append(errors, cmdutil.UsageErrorf(cmd, "Must specify the controller to update"))
}
return utilerrors.NewAggregate(errors)
@ -213,20 +213,20 @@ func RunRollingUpdate(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args
// when creating resource(s) from a stream.
if list, ok := obj.(*api.List); ok {
if len(list.Items) > 1 {
return cmdutil.UsageError(cmd, "%s specifies multiple items", filename)
return cmdutil.UsageErrorf(cmd, "%s specifies multiple items", filename)
}
if len(list.Items) == 0 {
return cmdutil.UsageError(cmd, "please make sure %s exists and is not empty", filename)
return cmdutil.UsageErrorf(cmd, "please make sure %s exists and is not empty", filename)
}
obj = list.Items[0]
}
newRc, ok = obj.(*api.ReplicationController)
if !ok {
if gvks, _, err := typer.ObjectKinds(obj); err == nil {
return cmdutil.UsageError(cmd, "%s contains a %v not a ReplicationController", filename, gvks[0])
return cmdutil.UsageErrorf(cmd, "%s contains a %v not a ReplicationController", filename, gvks[0])
}
glog.V(4).Infof("Object %#v is not a ReplicationController", obj)
return cmdutil.UsageError(cmd, "%s does not specify a valid ReplicationController", filename)
return cmdutil.UsageErrorf(cmd, "%s does not specify a valid ReplicationController", filename)
}
infos, err := request.Infos()
if err != nil || len(infos) != 1 {
@ -247,7 +247,7 @@ func RunRollingUpdate(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args
}
if newRc != nil {
if inProgressImage := newRc.Spec.Template.Spec.Containers[0].Image; inProgressImage != image {
return cmdutil.UsageError(cmd, "Found existing in-progress update to image (%s).\nEither continue in-progress update with --image=%s or rollback with --rollback", inProgressImage, inProgressImage)
return cmdutil.UsageErrorf(cmd, "Found existing in-progress update to image (%s).\nEither continue in-progress update with --image=%s or rollback with --rollback", inProgressImage, inProgressImage)
}
fmt.Fprintf(out, "Found existing update in progress (%s), resuming.\n", newRc.Name)
} else {
@ -261,7 +261,7 @@ func RunRollingUpdate(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args
}
if oldRc.Spec.Template.Spec.Containers[0].Image == image {
if len(pullPolicy) == 0 {
return cmdutil.UsageError(cmd, "--image-pull-policy (Always|Never|IfNotPresent) must be provided when --image is the same as existing container image")
return cmdutil.UsageErrorf(cmd, "--image-pull-policy (Always|Never|IfNotPresent) must be provided when --image is the same as existing container image")
}
config.PullPolicy = api.PullPolicy(pullPolicy)
}
@ -292,12 +292,12 @@ func RunRollingUpdate(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args
}
if newRc == nil {
return cmdutil.UsageError(cmd, "Could not find %s to rollback.\n", newName)
return cmdutil.UsageErrorf(cmd, "Could not find %s to rollback.\n", newName)
}
}
if oldName == newRc.Name {
return cmdutil.UsageError(cmd, "%s cannot have the same name as the existing ReplicationController %s",
return cmdutil.UsageErrorf(cmd, "%s cannot have the same name as the existing ReplicationController %s",
filename, oldName)
}
@ -314,7 +314,7 @@ func RunRollingUpdate(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args
}
}
if !hasLabel {
return cmdutil.UsageError(cmd, "%s must specify a matching key with non-equal value in Selector for %s",
return cmdutil.UsageErrorf(cmd, "%s must specify a matching key with non-equal value in Selector for %s",
filename, oldName)
}
// TODO: handle scales during rolling update

View File

@ -66,8 +66,8 @@ func NewCmdRolloutHistory(f cmdutil.Factory, out io.Writer) *cobra.Command {
}
func RunHistory(f cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string, options *resource.FilenameOptions) error {
if len(args) == 0 && cmdutil.IsFilenameEmpty(options.Filenames) {
return cmdutil.UsageError(cmd, "Required resource not specified.")
if len(args) == 0 && cmdutil.IsFilenameSliceEmpty(options.Filenames) {
return cmdutil.UsageErrorf(cmd, "Required resource not specified.")
}
revision := cmdutil.GetFlagInt64(cmd, "revision")
if revision < 0 {

View File

@ -96,8 +96,8 @@ func NewCmdRolloutPause(f cmdutil.Factory, out io.Writer) *cobra.Command {
}
func (o *PauseConfig) CompletePause(f cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string) error {
if len(args) == 0 && cmdutil.IsFilenameEmpty(o.Filenames) {
return cmdutil.UsageError(cmd, cmd.Use)
if len(args) == 0 && cmdutil.IsFilenameSliceEmpty(o.Filenames) {
return cmdutil.UsageErrorf(cmd, "%s", cmd.Use)
}
o.Mapper, o.Typer = f.Object()

View File

@ -94,8 +94,8 @@ func NewCmdRolloutResume(f cmdutil.Factory, out io.Writer) *cobra.Command {
}
func (o *ResumeConfig) CompleteResume(f cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string) error {
if len(args) == 0 && cmdutil.IsFilenameEmpty(o.Filenames) {
return cmdutil.UsageError(cmd, cmd.Use)
if len(args) == 0 && cmdutil.IsFilenameSliceEmpty(o.Filenames) {
return cmdutil.UsageErrorf(cmd, "%s", cmd.Use)
}
o.Mapper, o.Typer = f.Object()

View File

@ -73,8 +73,8 @@ func NewCmdRolloutStatus(f cmdutil.Factory, out io.Writer) *cobra.Command {
}
func RunStatus(f cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string, options *resource.FilenameOptions) error {
if len(args) == 0 && cmdutil.IsFilenameEmpty(options.Filenames) {
return cmdutil.UsageError(cmd, "Required resource not specified.")
if len(args) == 0 && cmdutil.IsFilenameSliceEmpty(options.Filenames) {
return cmdutil.UsageErrorf(cmd, "Required resource not specified.")
}
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()

View File

@ -96,8 +96,8 @@ func NewCmdRolloutUndo(f cmdutil.Factory, out io.Writer) *cobra.Command {
}
func (o *UndoOptions) CompleteUndo(f cmdutil.Factory, cmd *cobra.Command, out io.Writer, args []string) error {
if len(args) == 0 && cmdutil.IsFilenameEmpty(o.Filenames) {
return cmdutil.UsageError(cmd, "Required resource not specified.")
if len(args) == 0 && cmdutil.IsFilenameSliceEmpty(o.Filenames) {
return cmdutil.UsageErrorf(cmd, "Required resource not specified.")
}
o.ToRevision = cmdutil.GetFlagInt64(cmd, "to-revision")

View File

@ -138,12 +138,12 @@ func addRunFlags(cmd *cobra.Command) {
func RunRun(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *cobra.Command, args []string, argsLenAtDash int) error {
// Let kubectl run follow rules for `--`, see #13004 issue
if len(args) == 0 || argsLenAtDash == 0 {
return cmdutil.UsageError(cmd, "NAME is required for run")
return cmdutil.UsageErrorf(cmd, "NAME is required for run")
}
timeout, err := cmdutil.GetPodRunningTimeoutFlag(cmd)
if err != nil {
return cmdutil.UsageError(cmd, err.Error())
return cmdutil.UsageErrorf(cmd, "%v", err)
}
// validate image name
@ -156,11 +156,11 @@ func RunRun(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *c
interactive := cmdutil.GetFlagBool(cmd, "stdin")
tty := cmdutil.GetFlagBool(cmd, "tty")
if tty && !interactive {
return cmdutil.UsageError(cmd, "-i/--stdin is required for containers with -t/--tty=true")
return cmdutil.UsageErrorf(cmd, "-i/--stdin is required for containers with -t/--tty=true")
}
replicas := cmdutil.GetFlagInt(cmd, "replicas")
if interactive && replicas != 1 {
return cmdutil.UsageError(cmd, fmt.Sprintf("-i/--stdin requires that replicas is 1, found %d", replicas))
return cmdutil.UsageErrorf(cmd, "-i/--stdin requires that replicas is 1, found %d", replicas)
}
namespace, _, err := f.DefaultNamespace()
@ -172,7 +172,7 @@ func RunRun(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *c
return err
}
if restartPolicy != api.RestartPolicyAlways && replicas != 1 {
return cmdutil.UsageError(cmd, fmt.Sprintf("--restart=%s requires that --replicas=1, found %d", restartPolicy, replicas))
return cmdutil.UsageErrorf(cmd, "--restart=%s requires that --replicas=1, found %d", restartPolicy, replicas)
}
attachFlag := cmd.Flags().Lookup("attach")
@ -184,11 +184,11 @@ func RunRun(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *c
remove := cmdutil.GetFlagBool(cmd, "rm")
if !attach && remove {
return cmdutil.UsageError(cmd, "--rm should only be used for attached containers")
return cmdutil.UsageErrorf(cmd, "--rm should only be used for attached containers")
}
if attach && cmdutil.GetDryRunFlag(cmd) {
return cmdutil.UsageError(cmd, "--dry-run can't be used with attached containers options (--attach, --stdin, or --tty)")
return cmdutil.UsageErrorf(cmd, "--dry-run can't be used with attached containers options (--attach, --stdin, or --tty)")
}
if err := verifyImagePullPolicy(cmd); err != nil {
@ -242,7 +242,7 @@ func RunRun(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *c
generators := f.Generators("run")
generator, found := generators[generatorName]
if !found {
return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName))
return cmdutil.UsageErrorf(cmd, "generator %q not found", generatorName)
}
names := generator.ParamNames()
params := kubectl.MakeParams(cmd, names)
@ -261,7 +261,7 @@ func RunRun(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *c
if cmdutil.GetFlagBool(cmd, "expose") {
serviceGenerator := cmdutil.GetFlagString(cmd, "service-generator")
if len(serviceGenerator) == 0 {
return cmdutil.UsageError(cmd, fmt.Sprintf("No service generator specified"))
return cmdutil.UsageErrorf(cmd, "No service generator specified")
}
if err := generateService(f, cmd, args, serviceGenerator, params, namespace, cmdOut); err != nil {
return err
@ -368,6 +368,7 @@ func RunRun(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *c
default:
return fmt.Errorf("pod %s/%s left in phase %s", pod.Namespace, pod.Name, pod.Status.Phase)
}
}
outputFormat := cmdutil.GetFlagString(cmd, "output")
@ -491,9 +492,8 @@ func getRestartPolicy(cmd *cobra.Command, interactive bool) (api.RestartPolicy,
return api.RestartPolicyOnFailure, nil
case api.RestartPolicyNever:
return api.RestartPolicyNever, nil
default:
return "", cmdutil.UsageError(cmd, fmt.Sprintf("invalid restart policy: %s", restart))
}
return "", cmdutil.UsageErrorf(cmd, "invalid restart policy: %s")
}
func verifyImagePullPolicy(cmd *cobra.Command) error {
@ -503,9 +503,8 @@ func verifyImagePullPolicy(cmd *cobra.Command) error {
return nil
case "":
return nil
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("invalid image pull policy: %s", pullPolicy))
}
return cmdutil.UsageErrorf(cmd, "invalid image pull policy: %s", pullPolicy)
}
func generateService(f cmdutil.Factory, cmd *cobra.Command, args []string, serviceGenerator string, paramsIn map[string]interface{}, namespace string, out io.Writer) error {

View File

@ -168,12 +168,11 @@ func TestRunArgsFollowDashRules(t *testing.T) {
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
if req.URL.Path == "/namespaces/test/replicationcontrollers" {
return &http.Response{StatusCode: 201, Header: defaultHeader(), Body: objBody(codec, rc)}, nil
} else {
return &http.Response{
StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewBuffer([]byte("{}"))),
}, nil
}
return &http.Response{
StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewBuffer([]byte("{}"))),
}, nil
}),
}
tf.Namespace = "test"

View File

@ -108,7 +108,7 @@ func RunScale(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []strin
Do()
err = r.Err()
if resource.IsUsageError(err) {
return cmdutil.UsageError(cmd, err.Error())
return cmdutil.UsageErrorf(cmd, "%v", err)
}
if err != nil {
return err
@ -116,7 +116,7 @@ func RunScale(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []strin
count := cmdutil.GetFlagInt(cmd, "replicas")
if count < 0 {
return cmdutil.UsageError(cmd, "The --replicas=COUNT flag is required, and COUNT must be greater than or equal to 0")
return cmdutil.UsageErrorf(cmd, "The --replicas=COUNT flag is required, and COUNT must be greater than or equal to 0")
}
infos := []*resource.Info{}

View File

@ -158,7 +158,7 @@ func (o *ImageOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []st
func (o *ImageOptions) Validate() error {
errors := []error{}
if len(o.Resources) < 1 && cmdutil.IsFilenameEmpty(o.Filenames) {
if len(o.Resources) < 1 && cmdutil.IsFilenameSliceEmpty(o.Filenames) {
errors = append(errors, fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>"))
}
if len(o.ContainerImages) < 1 {

View File

@ -142,7 +142,7 @@ func (o *SelectorOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args [
// Validate basic inputs
func (o *SelectorOptions) Validate() error {
if len(o.resources) < 1 && cmdutil.IsFilenameEmpty(o.fileOptions.Filenames) {
if len(o.resources) < 1 && cmdutil.IsFilenameSliceEmpty(o.fileOptions.Filenames) {
return fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>")
}
if o.selector == nil {

View File

@ -102,7 +102,7 @@ func NewCmdTaint(f cmdutil.Factory, out io.Writer) *cobra.Command {
cmdutil.CheckErr(err)
}
if err := options.Validate(); err != nil {
cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
cmdutil.CheckErr(cmdutil.UsageErrorf(cmd, err.Error()))
}
if err := options.RunTaint(); err != nil {
cmdutil.CheckErr(err)
@ -244,7 +244,7 @@ func (o *TaintOptions) Complete(f cmdutil.Factory, out io.Writer, cmd *cobra.Com
}
if o.taintsToAdd, o.taintsToRemove, err = parseTaints(taintArgs); err != nil {
return cmdutil.UsageError(cmd, err.Error())
return cmdutil.UsageErrorf(cmd, err.Error())
}
o.builder = f.NewBuilder(true).
ContinueOnError().

View File

@ -83,7 +83,7 @@ func NewCmdTopNode(f cmdutil.Factory, out io.Writer) *cobra.Command {
cmdutil.CheckErr(err)
}
if err := options.Validate(); err != nil {
cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
cmdutil.CheckErr(cmdutil.UsageErrorf(cmd, "%v", err))
}
if err := options.RunTopNode(); err != nil {
cmdutil.CheckErr(err)
@ -101,7 +101,7 @@ func (o *TopNodeOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []
if len(args) == 1 {
o.ResourceName = args[0]
} else if len(args) > 1 {
return cmdutil.UsageError(cmd, cmd.Use)
return cmdutil.UsageErrorf(cmd, "%s", cmd.Use)
}
clientset, err := f.ClientSet()

View File

@ -85,7 +85,7 @@ func NewCmdTopPod(f cmdutil.Factory, out io.Writer) *cobra.Command {
cmdutil.CheckErr(err)
}
if err := options.Validate(); err != nil {
cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
cmdutil.CheckErr(cmdutil.UsageErrorf(cmd, "%v", err))
}
if err := options.RunTopPod(); err != nil {
cmdutil.CheckErr(err)
@ -105,7 +105,7 @@ func (o *TopPodOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []s
if len(args) == 1 {
o.ResourceName = args[0]
} else if len(args) > 1 {
return cmdutil.UsageError(cmd, cmd.Use)
return cmdutil.UsageErrorf(cmd, "%s", cmd.Use)
}
o.Namespace, _, err = f.DefaultNamespace()

View File

@ -117,31 +117,32 @@ var ErrExit = fmt.Errorf("exit")
// This method is generic to the command in use and may be used by non-Kubectl
// commands.
func CheckErr(err error) {
checkErr("", err, fatalErrHandler)
checkErr(err, fatalErrHandler)
}
// checkErrWithPrefix works like CheckErr, but adds a caller-defined prefix to non-nil errors
func checkErrWithPrefix(prefix string, err error) {
checkErr(prefix, err, fatalErrHandler)
checkErr(err, fatalErrHandler)
}
// checkErr formats a given error as a string and calls the passed handleErr
// func with that string and an kubectl exit code.
func checkErr(prefix string, err error, handleErr func(string, int)) {
func checkErr(err error, handleErr func(string, int)) {
// unwrap aggregates of 1
if agg, ok := err.(utilerrors.Aggregate); ok && len(agg.Errors()) == 1 {
err = agg.Errors()[0]
}
switch {
case err == nil:
if err == nil {
return
}
switch {
case err == ErrExit:
handleErr("", DefaultErrorExitCode)
return
case kerrors.IsInvalid(err):
details := err.(*kerrors.StatusError).Status().Details
s := fmt.Sprintf("%sThe %s %q is invalid", prefix, details.Kind, details.Name)
s := fmt.Sprintf("The %s %q is invalid", details.Kind, details.Name)
if len(details.Causes) > 0 {
errs := statusCausesToAggrError(details.Causes)
handleErr(MultilineError(s+": ", errs), DefaultErrorExitCode)
@ -149,22 +150,22 @@ func checkErr(prefix string, err error, handleErr func(string, int)) {
handleErr(s, DefaultErrorExitCode)
}
case clientcmd.IsConfigurationInvalid(err):
handleErr(MultilineError(fmt.Sprintf("%sError in configuration: ", prefix), err), DefaultErrorExitCode)
handleErr(MultilineError("Error in configuration: ", err), DefaultErrorExitCode)
default:
switch err := err.(type) {
case *meta.NoResourceMatchError:
switch {
case len(err.PartialResource.Group) > 0 && len(err.PartialResource.Version) > 0:
handleErr(fmt.Sprintf("%sthe server doesn't have a resource type %q in group %q and version %q", prefix, err.PartialResource.Resource, err.PartialResource.Group, err.PartialResource.Version), DefaultErrorExitCode)
handleErr(fmt.Sprintf("the server doesn't have a resource type %q in group %q and version %q", err.PartialResource.Resource, err.PartialResource.Group, err.PartialResource.Version), DefaultErrorExitCode)
case len(err.PartialResource.Group) > 0:
handleErr(fmt.Sprintf("%sthe server doesn't have a resource type %q in group %q", prefix, err.PartialResource.Resource, err.PartialResource.Group), DefaultErrorExitCode)
handleErr(fmt.Sprintf("the server doesn't have a resource type %q in group %q", err.PartialResource.Resource, err.PartialResource.Group), DefaultErrorExitCode)
case len(err.PartialResource.Version) > 0:
handleErr(fmt.Sprintf("%sthe server doesn't have a resource type %q in version %q", prefix, err.PartialResource.Resource, err.PartialResource.Version), DefaultErrorExitCode)
handleErr(fmt.Sprintf("the server doesn't have a resource type %q in version %q", err.PartialResource.Resource, err.PartialResource.Version), DefaultErrorExitCode)
default:
handleErr(fmt.Sprintf("%sthe server doesn't have a resource type %q", prefix, err.PartialResource.Resource), DefaultErrorExitCode)
handleErr(fmt.Sprintf("the server doesn't have a resource type %q", err.PartialResource.Resource), DefaultErrorExitCode)
}
case utilerrors.Aggregate:
handleErr(MultipleErrors(prefix, err.Errors()), DefaultErrorExitCode)
handleErr(MultipleErrors(``, err.Errors()), DefaultErrorExitCode)
case utilexec.ExitError:
// do not print anything, only terminate with given error
handleErr("", err.ExitStatus())
@ -297,26 +298,23 @@ func messageForError(err error) string {
return msg
}
func UsageError(cmd *cobra.Command, format string, args ...interface{}) error {
func UsageErrorf(cmd *cobra.Command, format string, args ...interface{}) error {
msg := fmt.Sprintf(format, args...)
return fmt.Errorf("%s\nSee '%s -h' for help and examples.", msg, cmd.CommandPath())
}
func IsFilenameEmpty(filenames []string) bool {
func IsFilenameSliceEmpty(filenames []string) bool {
return len(filenames) == 0
}
// Whether this cmd need watching objects.
func isWatch(cmd *cobra.Command) bool {
if w, err := cmd.Flags().GetBool("watch"); w && err == nil {
if w, err := cmd.Flags().GetBool("watch"); err == nil && w {
return true
}
if wo, err := cmd.Flags().GetBool("watch-only"); wo && err == nil {
return true
}
return false
wo, err := cmd.Flags().GetBool("watch-only")
return err == nil && wo
}
func GetFlagString(cmd *cobra.Command, flag string) string {
@ -533,7 +531,6 @@ func UpdateObject(info *resource.Info, codec runtime.Codec, updateFn func(runtim
return info.Object, nil
}
// AddCmdRecordFlag adds --record flag to command
func AddRecordFlag(cmd *cobra.Command) {
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.")
}
@ -802,7 +799,7 @@ func DefaultSubCommandRun(out io.Writer) func(c *cobra.Command, args []string) {
// RequireNoArguments exits with a usage error if extra arguments are provided.
func RequireNoArguments(c *cobra.Command, args []string) {
if len(args) > 0 {
CheckErr(UsageError(c, fmt.Sprintf(`unknown command %q`, strings.Join(args, " "))))
CheckErr(UsageErrorf(c, "unknown command %q", strings.Join(args, " ")))
}
}

View File

@ -284,7 +284,7 @@ func testCheckError(t *testing.T, tests []checkErrTestCase) {
}
for _, test := range tests {
checkErr("", test.err, errHandle)
checkErr(test.err, errHandle)
if errReturned != test.expectedErr {
t.Fatalf("Got: %s, expected: %s", errReturned, test.expectedErr)

View File

@ -100,7 +100,7 @@ func PrintSuccess(mapper meta.RESTMapper, shortOutput bool, out io.Writer, resou
func ValidateOutputArgs(cmd *cobra.Command) error {
outputMode := GetFlagString(cmd, "output")
if outputMode != "" && outputMode != "name" {
return UsageError(cmd, "Unexpected -o output mode: %v. We only support '-o name'.", outputMode)
return UsageErrorf(cmd, "Unexpected -o output mode: %v. We only support '-o name'.", outputMode)
}
return nil
}

View File

@ -118,11 +118,5 @@ func retrieveServerVersion(f cmdutil.Factory) (*apimachineryversion.Info, error)
// Always request fresh data from the server
discoveryClient.Invalidate()
serverVersion, err := discoveryClient.ServerVersion()
if err != nil {
return nil, err
}
return serverVersion, nil
return discoveryClient.ServerVersion()
}