kubectl: simplify code with help of linter

This commit is contained in:
Alexander Campbell 2017-05-25 13:37:56 -07:00
parent 01ae6edc6c
commit ef9ae61240
16 changed files with 34 additions and 71 deletions

View File

@ -61,11 +61,7 @@ func SetOriginalConfiguration(info *resource.Info, original []byte) error {
} }
annots[api.LastAppliedConfigAnnotation] = string(original) annots[api.LastAppliedConfigAnnotation] = string(original)
if err := info.Mapping.MetadataAccessor.SetAnnotations(info.Object, annots); err != nil { return info.Mapping.MetadataAccessor.SetAnnotations(info.Object, annots)
return err
}
return nil
} }
// GetModifiedConfiguration retrieves the modified configuration of the object. // GetModifiedConfiguration retrieves the modified configuration of the object.

View File

@ -118,11 +118,7 @@ func (o *SetLastAppliedOptions) Complete(f cmdutil.Factory, cmd *cobra.Command)
} }
o.Namespace, o.EnforceNamespace, err = f.DefaultNamespace() o.Namespace, o.EnforceNamespace, err = f.DefaultNamespace()
if err != nil {
return err return err
}
return nil
} }
func (o *SetLastAppliedOptions) Validate(f cmdutil.Factory, cmd *cobra.Command) error { func (o *SetLastAppliedOptions) Validate(f cmdutil.Factory, cmd *cobra.Command) error {
@ -179,10 +175,7 @@ func (o *SetLastAppliedOptions) Validate(f cmdutil.Factory, cmd *cobra.Command)
return nil return nil
}) })
if err != nil {
return err return err
}
return nil
} }
func (o *SetLastAppliedOptions) RunSetLastApplied(f cmdutil.Factory, cmd *cobra.Command) error { func (o *SetLastAppliedOptions) RunSetLastApplied(f cmdutil.Factory, cmd *cobra.Command) error {

View File

@ -158,11 +158,7 @@ func (o *ConvertOptions) Complete(f cmdutil.Factory, out io.Writer, cmd *cobra.C
} }
o.encoder = f.JSONEncoder() o.encoder = f.JSONEncoder()
o.printer, err = f.PrinterForCommand(cmd, o.local, nil, printers.PrintOptions{}) o.printer, err = f.PrinterForCommand(cmd, o.local, nil, printers.PrintOptions{})
if err != nil {
return err return err
}
return nil
} }
// RunConvert implements the generic Convert command // RunConvert implements the generic Convert command

View File

@ -34,12 +34,11 @@ import (
) )
var ( var (
cp_example = templates.Examples(i18n.T(` cpExample = templates.Examples(i18n.T(`
# !!!Important Note!!! # !!!Important Note!!!
# Requires that the 'tar' binary is present in your container # Requires that the 'tar' binary is present in your container
# image. If 'tar' is not present, 'kubectl cp' will fail. # image. If 'tar' is not present, 'kubectl cp' will fail.
# Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace # Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace
kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir
@ -65,7 +64,7 @@ func NewCmdCp(f cmdutil.Factory, cmdOut, cmdErr io.Writer) *cobra.Command {
Use: "cp <file-spec-src> <file-spec-dest>", Use: "cp <file-spec-src> <file-spec-dest>",
Short: i18n.T("Copy files and directories to and from containers."), Short: i18n.T("Copy files and directories to and from containers."),
Long: "Copy files and directories to and from containers.", Long: "Copy files and directories to and from containers.",
Example: cp_example, Example: cpExample,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(runCopy(f, cmd, cmdOut, cmdErr, args)) cmdutil.CheckErr(runCopy(f, cmd, cmdOut, cmdErr, args))
}, },

View File

@ -39,12 +39,12 @@ type CreateOptions struct {
} }
var ( var (
create_long = templates.LongDesc(i18n.T(` createLong = templates.LongDesc(i18n.T(`
Create a resource from a file or from stdin. Create a resource from a file or from stdin.
JSON and YAML formats are accepted.`)) JSON and YAML formats are accepted.`))
create_example = templates.Examples(i18n.T(` createExample = templates.Examples(i18n.T(`
# Create a pod using the data in pod.json. # Create a pod using the data in pod.json.
kubectl create -f ./pod.json kubectl create -f ./pod.json
@ -61,8 +61,8 @@ func NewCmdCreate(f cmdutil.Factory, out, errOut io.Writer) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "create -f FILENAME", Use: "create -f FILENAME",
Short: i18n.T("Create a resource from a file or from stdin."), Short: i18n.T("Create a resource from a file or from stdin."),
Long: create_long, Long: createLong,
Example: create_example, Example: createExample,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if cmdutil.IsFilenameEmpty(options.FilenameOptions.Filenames) { if cmdutil.IsFilenameEmpty(options.FilenameOptions.Filenames) {
defaultRunFunc := cmdutil.DefaultSubCommandRun(errOut) defaultRunFunc := cmdutil.DefaultSubCommandRun(errOut)

View File

@ -327,7 +327,7 @@ func deleteResource(info *resource.Info, out io.Writer, shortOutput bool, mapper
return nil return nil
} }
// objectDeletionWaitInterval is the interval to wait between checks for deletion. Exposed for testing. // objectDeletionWaitInterval is the interval to wait between checks for deletion.
var objectDeletionWaitInterval = time.Second var objectDeletionWaitInterval = time.Second
// waitForObjectDeletion refreshes the object, waiting until it is deleted, a timeout is reached, or // waitForObjectDeletion refreshes the object, waiting until it is deleted, a timeout is reached, or

View File

@ -116,7 +116,7 @@ func TestEdit(t *testing.T) {
if step.StepType != "edit" { if step.StepType != "edit" {
t.Fatalf("%s, step %d: expected edit step, got %s %s", name, i, req.Method, req.URL.Path) t.Fatalf("%s, step %d: expected edit step, got %s %s", name, i, req.Method, req.URL.Path)
} }
if bytes.Compare(body, expectedInput) != 0 { if !bytes.Equal(body, expectedInput) {
if updateInputFixtures { if updateInputFixtures {
// Convenience to allow recapturing the input and persisting it here // Convenience to allow recapturing the input and persisting it here
ioutil.WriteFile(inputFile, body, os.FileMode(0644)) ioutil.WriteFile(inputFile, body, os.FileMode(0644))
@ -139,7 +139,7 @@ func TestEdit(t *testing.T) {
req.Method, req.URL.Path, req.Header.Get("Content-Type"), req.Method, req.URL.Path, req.Header.Get("Content-Type"),
) )
} }
if bytes.Compare(body, expectedInput) != 0 { if !bytes.Equal(body, expectedInput) {
if updateInputFixtures { if updateInputFixtures {
// Convenience to allow recapturing the input and persisting it here // Convenience to allow recapturing the input and persisting it here
ioutil.WriteFile(inputFile, body, os.FileMode(0644)) ioutil.WriteFile(inputFile, body, os.FileMode(0644))

View File

@ -34,9 +34,9 @@ import (
) )
var ( var (
expose_resources = `pod (po), service (svc), replicationcontroller (rc), deployment (deploy), replicaset (rs)` exposeResources = `pod (po), service (svc), replicationcontroller (rc), deployment (deploy), replicaset (rs)`
expose_long = templates.LongDesc(` exposeLong = templates.LongDesc(`
Expose a resource as a new Kubernetes service. Expose a resource as a new Kubernetes service.
Looks up a deployment, service, replica set, replication controller or pod by name and uses the selector Looks up a deployment, service, replica set, replication controller or pod by name and uses the selector
@ -48,9 +48,9 @@ var (
Possible resources include (case insensitive): Possible resources include (case insensitive):
` + expose_resources) ` + exposeResources)
expose_example = templates.Examples(i18n.T(` exposeExample = templates.Examples(i18n.T(`
# Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000. # Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000.
kubectl expose rc nginx --port=80 --target-port=8000 kubectl expose rc nginx --port=80 --target-port=8000
@ -77,7 +77,7 @@ func NewCmdExposeService(f cmdutil.Factory, out io.Writer) *cobra.Command {
options := &resource.FilenameOptions{} options := &resource.FilenameOptions{}
validArgs, argAliases := []string{}, []string{} validArgs, argAliases := []string{}, []string{}
resources := regexp.MustCompile(`\s*,`).Split(expose_resources, -1) resources := regexp.MustCompile(`\s*,`).Split(exposeResources, -1)
for _, r := range resources { for _, r := range resources {
validArgs = append(validArgs, strings.Fields(r)[0]) validArgs = append(validArgs, strings.Fields(r)[0])
argAliases = kubectl.ResourceAliases(validArgs) argAliases = kubectl.ResourceAliases(validArgs)
@ -86,8 +86,8 @@ func NewCmdExposeService(f cmdutil.Factory, out io.Writer) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type]", Use: "expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type]",
Short: i18n.T("Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service"), Short: i18n.T("Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service"),
Long: expose_long, Long: exposeLong,
Example: expose_example, Example: exposeExample,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
err := RunExpose(f, out, cmd, args, options) err := RunExpose(f, out, cmd, args, options)
cmdutil.CheckErr(err) cmdutil.CheckErr(err)

View File

@ -289,8 +289,7 @@ func RunGet(f cmdutil.Factory, out, errOut io.Writer, cmd *cobra.Command, args [
first = false first = false
return false, nil return false, nil
} }
err := printer.PrintObj(e.Object, out) return false, printer.PrintObj(e.Object, out)
return false, err
}) })
return err return err
}) })

View File

@ -506,9 +506,7 @@ func extractResourceList(objs []runtime.Object) ([]runtime.Object, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
for _, item := range items { finalObjs = append(finalObjs, items...)
finalObjs = append(finalObjs, item)
}
} }
return finalObjs, nil return finalObjs, nil
} }

View File

@ -308,7 +308,7 @@ func parseLabels(spec []string) (map[string]string, []string, error) {
labels := map[string]string{} labels := map[string]string{}
var remove []string var remove []string
for _, labelSpec := range spec { for _, labelSpec := range spec {
if strings.Index(labelSpec, "=") != -1 { if strings.Contains(labelSpec, "=") {
parts := strings.Split(labelSpec, "=") parts := strings.Split(labelSpec, "=")
if len(parts) != 2 { if len(parts) != 2 {
return nil, nil, fmt.Errorf("invalid label spec: %v", labelSpec) return nil, nil, fmt.Errorf("invalid label spec: %v", labelSpec)

View File

@ -178,7 +178,7 @@ func parseTaints(spec []string) ([]v1.Taint, []v1.Taint, error) {
uniqueTaints := map[v1.TaintEffect]sets.String{} uniqueTaints := map[v1.TaintEffect]sets.String{}
for _, taintSpec := range spec { for _, taintSpec := range spec {
if strings.Index(taintSpec, "=") != -1 && strings.Index(taintSpec, ":") != -1 { if strings.Contains(taintSpec, "=") && strings.Contains(taintSpec, ":") {
newTaint, err := utiltaints.ParseTaint(taintSpec) newTaint, err := utiltaints.ParseTaint(taintSpec)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@ -197,7 +197,7 @@ func parseTaints(spec []string) ([]v1.Taint, []v1.Taint, error) {
} else if strings.HasSuffix(taintSpec, "-") { } else if strings.HasSuffix(taintSpec, "-") {
taintKey := taintSpec[:len(taintSpec)-1] taintKey := taintSpec[:len(taintSpec)-1]
var effect v1.TaintEffect var effect v1.TaintEffect
if strings.Index(taintKey, ":") != -1 { if strings.Contains(taintKey, ":") {
parts := strings.Split(taintKey, ":") parts := strings.Split(taintKey, ":")
taintKey = parts[0] taintKey = parts[0]
effect = v1.TaintEffect(parts[1]) effect = v1.TaintEffect(parts[1])

View File

@ -107,11 +107,7 @@ func RunVersion(f cmdutil.Factory, out io.Writer, cmd *cobra.Command) error {
} }
if serverErr != nil {
return serverErr return serverErr
}
return nil
} }
func retrieveServerVersion(f cmdutil.Factory) (*apimachineryversion.Info, error) { func retrieveServerVersion(f cmdutil.Factory) (*apimachineryversion.Info, error) {

View File

@ -565,10 +565,7 @@ func Rename(c coreclient.ReplicationControllersGetter, rc *api.ReplicationContro
} }
// Then create the same RC with the new name. // Then create the same RC with the new name.
_, err = c.ReplicationControllers(rc.Namespace).Create(rc) _, err = c.ReplicationControllers(rc.Namespace).Create(rc)
if err != nil {
return err return err
}
return nil
} }
func LoadExistingNextReplicationController(c coreclient.ReplicationControllersGetter, namespace, newName string) (*api.ReplicationController, error) { func LoadExistingNextReplicationController(c coreclient.ReplicationControllersGetter, namespace, newName string) (*api.ReplicationController, error) {
@ -684,14 +681,14 @@ func UpdateExistingReplicationController(rcClient coreclient.ReplicationControll
if _, found := oldRc.Spec.Selector[deploymentKey]; !found { if _, found := oldRc.Spec.Selector[deploymentKey]; !found {
SetNextControllerAnnotation(oldRc, newName) SetNextControllerAnnotation(oldRc, newName)
return AddDeploymentKeyToReplicationController(oldRc, rcClient, podClient, deploymentKey, deploymentValue, namespace, out) return AddDeploymentKeyToReplicationController(oldRc, rcClient, podClient, deploymentKey, deploymentValue, namespace, out)
} else { }
// If we didn't need to update the controller for the deployment key, we still need to write // If we didn't need to update the controller for the deployment key, we still need to write
// the "next" controller. // the "next" controller.
applyUpdate := func(rc *api.ReplicationController) { applyUpdate := func(rc *api.ReplicationController) {
SetNextControllerAnnotation(rc, newName) SetNextControllerAnnotation(rc, newName)
} }
return updateRcWithRetries(rcClient, namespace, oldRc, applyUpdate) return updateRcWithRetries(rcClient, namespace, oldRc, applyUpdate)
}
} }
func AddDeploymentKeyToReplicationController(oldRc *api.ReplicationController, rcClient coreclient.ReplicationControllersGetter, podClient coreclient.PodsGetter, deploymentKey, deploymentValue, namespace string, out io.Writer) (*api.ReplicationController, error) { func AddDeploymentKeyToReplicationController(oldRc *api.ReplicationController, rcClient coreclient.ReplicationControllersGetter, podClient coreclient.PodsGetter, deploymentKey, deploymentValue, namespace string, out io.Writer) (*api.ReplicationController, error) {

View File

@ -868,9 +868,3 @@ func parseEnvs(envArray []string) ([]v1.EnvVar, error) {
} }
return envs, nil return envs, nil
} }
func newBool(val bool) *bool {
p := new(bool)
*p = val
return p
}

View File

@ -136,11 +136,6 @@ type StatefulSetReaper struct {
pollInterval, timeout time.Duration pollInterval, timeout time.Duration
} }
type objInterface interface {
Delete(name string) error
Get(name string) (metav1.Object, error)
}
// getOverlappingControllers finds rcs that this controller overlaps, as well as rcs overlapping this controller. // getOverlappingControllers finds rcs that this controller overlaps, as well as rcs overlapping this controller.
func getOverlappingControllers(rcClient coreclient.ReplicationControllerInterface, rc *api.ReplicationController) ([]api.ReplicationController, error) { func getOverlappingControllers(rcClient coreclient.ReplicationControllerInterface, rc *api.ReplicationController) ([]api.ReplicationController, error) {
rcs, err := rcClient.List(metav1.ListOptions{}) rcs, err := rcClient.List(metav1.ListOptions{})