Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix some golint errors for packages in pkg/kubectl/cmd #70682

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 0 additions & 6 deletions hack/.golint_failures
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

cluster/images/etcd-version-monitor
cmd/cloud-controller-manager/app/apis/config/v1alpha1
cmd/hyperkube
Expand Down Expand Up @@ -138,15 +137,12 @@ pkg/kubeapiserver/options
pkg/kubectl
pkg/kubectl/apps
pkg/kubectl/cmd/annotate
pkg/kubectl/cmd/apiresources
pkg/kubectl/cmd/apply
pkg/kubectl/cmd/attach
pkg/kubectl/cmd/auth
pkg/kubectl/cmd/autoscale
pkg/kubectl/cmd/certificates
pkg/kubectl/cmd/clusterinfo
pkg/kubectl/cmd/completion
pkg/kubectl/cmd/config
pkg/kubectl/cmd/convert
pkg/kubectl/cmd/cp
pkg/kubectl/cmd/create
Expand Down Expand Up @@ -176,9 +172,7 @@ pkg/kubectl/cmd/taint
pkg/kubectl/cmd/testing
pkg/kubectl/cmd/top
pkg/kubectl/cmd/util
pkg/kubectl/cmd/util/editor
pkg/kubectl/cmd/util/openapi
pkg/kubectl/cmd/util/sanity
pkg/kubectl/cmd/version
pkg/kubectl/cmd/wait
pkg/kubectl/describe/versioned
Expand Down
4 changes: 3 additions & 1 deletion pkg/kubectl/cmd/annotate/annotate.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ var (
kubectl annotate pods foo description-`))
)

// NewAnnotateOptions creates the options for annotate
func NewAnnotateOptions(ioStreams genericclioptions.IOStreams) *AnnotateOptions {
return &AnnotateOptions{
PrintFlags: genericclioptions.NewPrintFlags("annotated").WithTypeSetter(scheme.Scheme),
Expand All @@ -119,14 +120,15 @@ func NewAnnotateOptions(ioStreams genericclioptions.IOStreams) *AnnotateOptions
}
}

// NewCmdAnnotate creates the `annotate` command
func NewCmdAnnotate(parent string, f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
o := NewAnnotateOptions(ioStreams)

cmd := &cobra.Command{
Use: "annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]",
DisableFlagsInUseLine: true,
Short: i18n.T("Update the annotations on a resource"),
Long: annotateLong + "\n\n" + cmdutil.SuggestApiResources(parent),
Long: annotateLong + "\n\n" + cmdutil.SuggestAPIResources(parent),
Example: annotateExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd, args))
Expand Down
22 changes: 13 additions & 9 deletions pkg/kubectl/cmd/apiresources/apiresources.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ var (
kubectl api-resources --api-group=extensions`)
)

// ApiResourcesOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
// referencing the cmd.Flags()
type ApiResourcesOptions struct {
// APIResourceOptions is the start of the data required to perform the operation.
// As new fields are added, add them here instead of referencing the cmd.Flags()
type APIResourceOptions struct {
Output string
APIGroup string
Namespaced bool
Expand All @@ -70,8 +70,9 @@ type groupResource struct {
APIResource metav1.APIResource
}

func NewAPIResourceOptions(ioStreams genericclioptions.IOStreams) *ApiResourcesOptions {
return &ApiResourcesOptions{
// NewAPIResourceOptions creates the options for APIResource
func NewAPIResourceOptions(ioStreams genericclioptions.IOStreams) *APIResourceOptions {
return &APIResourceOptions{
IOStreams: ioStreams,
Namespaced: true,
}
Expand All @@ -89,7 +90,7 @@ func NewCmdAPIResources(f cmdutil.Factory, ioStreams genericclioptions.IOStreams
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(cmd, args))
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.RunApiResources(cmd, f))
cmdutil.CheckErr(o.RunAPIResources(cmd, f))
},
}

Expand All @@ -103,22 +104,25 @@ func NewCmdAPIResources(f cmdutil.Factory, ioStreams genericclioptions.IOStreams
return cmd
}

func (o *ApiResourcesOptions) Validate() error {
// Validate checks to the APIResourceOptions to see if there is sufficient information run the command
func (o *APIResourceOptions) Validate() error {
supportedOutputTypes := sets.NewString("", "wide", "name")
if !supportedOutputTypes.Has(o.Output) {
return fmt.Errorf("--output %v is not available", o.Output)
}
return nil
}

func (o *ApiResourcesOptions) Complete(cmd *cobra.Command, args []string) error {
// Complete adapts from the command line args and validates them
func (o *APIResourceOptions) Complete(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
return cmdutil.UsageErrorf(cmd, "unexpected arguments: %v", args)
}
return nil
}

func (o *ApiResourcesOptions) RunApiResources(cmd *cobra.Command, f cmdutil.Factory) error {
// RunAPIResources does the work
func (o *APIResourceOptions) RunAPIResources(cmd *cobra.Command, f cmdutil.Factory) error {
w := printers.GetNewTabWriter(o.Out)
defer w.Flush()

Expand Down
20 changes: 12 additions & 8 deletions pkg/kubectl/cmd/apiresources/apiversions.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,35 +36,38 @@ var (
kubectl api-versions`))
)

type ApiVersionsOptions struct {
// APIVersionsOptions have the data required for API versions
type APIVersionsOptions struct {
discoveryClient discovery.CachedDiscoveryInterface

genericclioptions.IOStreams
}

func NewApiVersionsOptions(ioStreams genericclioptions.IOStreams) *ApiVersionsOptions {
return &ApiVersionsOptions{
// NewAPIVersionsOptions creates the options for APIVersions
func NewAPIVersionsOptions(ioStreams genericclioptions.IOStreams) *APIVersionsOptions {
return &APIVersionsOptions{
IOStreams: ioStreams,
}
}

// NewCmdAPIVersions creates the `api-versions` command
func NewCmdAPIVersions(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
o := NewApiVersionsOptions(ioStreams)
o := NewAPIVersionsOptions(ioStreams)
cmd := &cobra.Command{
Use: "api-versions",
Short: "Print the supported API versions on the server, in the form of \"group/version\"",
Long: "Print the supported API versions on the server, in the form of \"group/version\"",
Example: apiversionsExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd, args))
cmdutil.CheckErr(o.RunApiVersions())
cmdutil.CheckErr(o.RunAPIVersions())
},
}
return cmd
}

func (o *ApiVersionsOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
// Complete adapts from the command line args and factory to the data required
func (o *APIVersionsOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
if len(args) != 0 {
return cmdutil.UsageErrorf(cmd, "unexpected arguments: %v", args)
}
Expand All @@ -76,13 +79,14 @@ func (o *ApiVersionsOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, arg
return nil
}

func (o *ApiVersionsOptions) RunApiVersions() error {
// RunAPIVersions does the work
func (o *APIVersionsOptions) RunAPIVersions() error {
// Always request fresh data from the server
o.discoveryClient.Invalidate()

groupList, err := o.discoveryClient.ServerGroups()
if err != nil {
return fmt.Errorf("Couldn't get available api versions from server: %v\n", err)
return fmt.Errorf("couldn't get available api versions from server: %v", err)
}
apiVersions := metav1.ExtractGroupVersions(groupList)
sort.Strings(apiVersions)
Expand Down
13 changes: 7 additions & 6 deletions pkg/kubectl/cmd/apply/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ type ApplyOptions struct {
cmdBaseName string
All bool
Overwrite bool
OpenApiPatch bool
OpenAPIPatch bool
PruneWhitelist []string
ShouldIncludeUninitialized bool

Expand Down Expand Up @@ -133,14 +133,15 @@ func NewApplyOptions(ioStreams genericclioptions.IOStreams) *ApplyOptions {
PrintFlags: genericclioptions.NewPrintFlags("created").WithTypeSetter(scheme.Scheme),

Overwrite: true,
OpenApiPatch: true,
OpenAPIPatch: true,

Recorder: genericclioptions.NoopRecorder{},

IOStreams: ioStreams,
}
}

// NewCmdApply creates the `apply` command
func NewCmdApply(baseName string, f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
o := NewApplyOptions(ioStreams)

Expand Down Expand Up @@ -174,7 +175,7 @@ func NewCmdApply(baseName string, f cmdutil.Factory, ioStreams genericclioptions
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.All, "all", o.All, "Select all resources in the namespace of the specified resource types.")
cmd.Flags().StringArrayVar(&o.PruneWhitelist, "prune-whitelist", o.PruneWhitelist, "Overwrite the default whitelist with <group/version/kind> for --prune")
cmd.Flags().BoolVar(&o.OpenApiPatch, "openapi-patch", o.OpenApiPatch, "If true, use openapi to calculate diff when the openapi presents and the resource can be found in the openapi spec. Otherwise, fall back to use baked-in types.")
cmd.Flags().BoolVar(&o.OpenAPIPatch, "openapi-patch", o.OpenAPIPatch, "If true, use openapi to calculate diff when the openapi presents and the resource can be found in the openapi spec. Otherwise, fall back to use baked-in types.")
cmd.Flags().BoolVar(&o.ServerDryRun, "server-dry-run", o.ServerDryRun, "If true, request will be sent to server with dry-run flag, which means the modifications won't be persisted. This is an alpha feature and flag.")
cmdutil.AddDryRunFlag(cmd)
cmdutil.AddIncludeUninitializedFlag(cmd)
Expand Down Expand Up @@ -258,7 +259,7 @@ func validatePruneAll(prune, all bool, selector string) error {
return fmt.Errorf("cannot set --all and --selector at the same time")
}
if prune && !all && selector == "" {
return fmt.Errorf("all resources selected for prune without explicitly passing --all. To prune all resources, pass the --all flag. If you did not mean to prune all resources, specify a label selector.")
return fmt.Errorf("all resources selected for prune without explicitly passing --all. To prune all resources, pass the --all flag. If you did not mean to prune all resources, specify a label selector")
}
return nil
}
Expand Down Expand Up @@ -296,7 +297,7 @@ func parsePruneResources(mapper meta.RESTMapper, gvks []string) ([]pruneResource

func (o *ApplyOptions) Run() error {
var openapiSchema openapi.Resources
if o.OpenApiPatch {
if o.OpenAPIPatch {
openapiSchema = o.OpenAPISchema
}

Expand Down Expand Up @@ -901,7 +902,7 @@ func (p *Patcher) deleteAndCreate(original runtime.Object, modified []byte, name
// but still propagate and advertise error to user
recreated, recreateErr := p.Helper.Create(namespace, true, original, &options)
if recreateErr != nil {
err = fmt.Errorf("An error occurred force-replacing the existing object with the newly provided one:\n\n%v.\n\nAdditionally, an error occurred attempting to restore the original object:\n\n%v\n", err, recreateErr)
err = fmt.Errorf("An error occurred force-replacing the existing object with the newly provided one:\n\n%v.\n\nAdditionally, an error occurred attempting to restore the original object:\n\n%v", err, recreateErr)
} else {
createdObject = recreated
}
Expand Down
3 changes: 1 addition & 2 deletions pkg/kubectl/cmd/apply/apply_set_last_applied.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,8 @@ func (o *SetLastAppliedOptions) Validate() error {
if err := info.Get(); err != nil {
if errors.IsNotFound(err) {
return err
} else {
return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving current configuration of:\n%s\nfrom server for:", info.String()), info.Source, err)
}
return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving current configuration of:\n%s\nfrom server for:", info.String()), info.Source, err)
}
originalBuf, err := kubectl.GetOriginalConfiguration(info.Object)
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions pkg/kubectl/cmd/apply/apply_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ func TestRunApplyViewLastApplied(t *testing.T) {
name: "view resource/name invalid format",
filePath: "",
outputFormat: "wide",
expectedErr: "error: Unexpected -o output mode: wide, the flag 'output' must be one of yaml|json\nSee 'view-last-applied -h' for help and examples.",
expectedErr: "error: Unexpected -o output mode: wide, the flag 'output' must be one of yaml|json\nSee 'view-last-applied -h' for help and examples",
expectedOut: "",
selector: "",
args: []string{"replicationcontroller", "test-rc"},
Expand Down Expand Up @@ -648,7 +648,7 @@ func TestApplyRetry(t *testing.T) {
case p == pathRC && m == "PATCH":
if firstPatch {
firstPatch = false
statusErr := kubeerr.NewConflict(schema.GroupResource{Group: "", Resource: "rc"}, "test-rc", fmt.Errorf("the object has been modified. Please apply at first."))
statusErr := kubeerr.NewConflict(schema.GroupResource{Group: "", Resource: "rc"}, "test-rc", fmt.Errorf("the object has been modified. Please apply at first"))
bodyBytes, _ := json.Marshal(statusErr)
bodyErr := ioutil.NopCloser(bytes.NewReader(bodyBytes))
return &http.Response{StatusCode: http.StatusConflict, Header: cmdtesting.DefaultHeader(), Body: bodyErr}, nil
Expand Down Expand Up @@ -1280,7 +1280,7 @@ func TestForceApply(t *testing.T) {
case strings.HasSuffix(p, pathRC) && m == "PATCH":
counts["patch"]++
if counts["patch"] <= 6 {
statusErr := kubeerr.NewConflict(schema.GroupResource{Group: "", Resource: "rc"}, "test-rc", fmt.Errorf("the object has been modified. Please apply at first."))
statusErr := kubeerr.NewConflict(schema.GroupResource{Group: "", Resource: "rc"}, "test-rc", fmt.Errorf("the object has been modified. Please apply at first"))
bodyBytes, _ := json.Marshal(statusErr)
bodyErr := ioutil.NopCloser(bytes.NewReader(bodyBytes))
return &http.Response{StatusCode: http.StatusConflict, Header: cmdtesting.DefaultHeader(), Body: bodyErr}, nil
Expand Down
1 change: 1 addition & 0 deletions pkg/kubectl/cmd/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)

// NewCmdAuth returns an initialized Command instance for 'auth' sub command
func NewCmdAuth(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
// Parent command to which all subcommands are added.
cmds := &cobra.Command{
Expand Down
4 changes: 4 additions & 0 deletions pkg/kubectl/cmd/auth/cani.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ var (
kubectl auth can-i get /logs/`)
)

// NewCmdCanI returns an initialized Command for 'auth can-i' sub command
func NewCmdCanI(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
o := &CanIOptions{
IOStreams: streams,
Expand Down Expand Up @@ -112,6 +113,7 @@ func NewCmdCanI(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.C
return cmd
}

// Complete completes all the required options
func (o *CanIOptions) Complete(f cmdutil.Factory, args []string) error {
if o.Quiet {
o.Out = ioutil.Discard
Expand Down Expand Up @@ -155,6 +157,7 @@ func (o *CanIOptions) Complete(f cmdutil.Factory, args []string) error {
return nil
}

// Validate makes sure provided values for CanIOptions are valid
func (o *CanIOptions) Validate() error {
if o.NonResourceURL != "" {
if o.Subresource != "" {
Expand All @@ -167,6 +170,7 @@ func (o *CanIOptions) Validate() error {
return nil
}

// RunAccessCheck checks if user has access to a certain resource or non resource URL
func (o *CanIOptions) RunAccessCheck() (bool, error) {
var sar *authorizationv1.SelfSubjectAccessReview
if o.NonResourceURL == "" {
Expand Down
5 changes: 5 additions & 0 deletions pkg/kubectl/cmd/auth/reconcile.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ var (
kubectl auth reconcile -f my-rbac-rules.yaml`)
)

// NewReconcileOptions returns a new ReconcileOptions instance
func NewReconcileOptions(ioStreams genericclioptions.IOStreams) *ReconcileOptions {
return &ReconcileOptions{
FilenameOptions: &resource.FilenameOptions{},
Expand All @@ -74,6 +75,7 @@ func NewReconcileOptions(ioStreams genericclioptions.IOStreams) *ReconcileOption
}
}

// NewCmdReconcile holds the options for 'auth reconcile' sub command
func NewCmdReconcile(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
o := NewReconcileOptions(streams)

Expand Down Expand Up @@ -101,6 +103,7 @@ func NewCmdReconcile(f cmdutil.Factory, streams genericclioptions.IOStreams) *co
return cmd
}

// Complete completes all the required options
func (o *ReconcileOptions) Complete(cmd *cobra.Command, f cmdutil.Factory, args []string) error {
if len(args) > 0 {
return errors.New("no arguments are allowed")
Expand Down Expand Up @@ -149,6 +152,7 @@ func (o *ReconcileOptions) Complete(cmd *cobra.Command, f cmdutil.Factory, args
return nil
}

// Validate makes sure provided values for ReconcileOptions are valid
func (o *ReconcileOptions) Validate() error {
if o.Visitor == nil {
return errors.New("ReconcileOptions.Visitor must be set")
Expand All @@ -171,6 +175,7 @@ func (o *ReconcileOptions) Validate() error {
return nil
}

// RunReconcile performs the execution
func (o *ReconcileOptions) RunReconcile() error {
return o.Visitor.Visit(func(info *resource.Info, err error) error {
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions pkg/kubectl/cmd/autoscale/autoscale.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ type AutoscaleOptions struct {
Generator string
Min int32
Max int32
CpuPercent int32
CPUPercent int32

createAnnotation bool
args []string
Expand Down Expand Up @@ -120,7 +120,7 @@ func NewCmdAutoscale(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *
cmd.Flags().Int32Var(&o.Min, "min", -1, "The lower limit for the number of pods that can be set by the autoscaler. If it's not specified or negative, the server will apply a default value.")
cmd.Flags().Int32Var(&o.Max, "max", -1, "The upper limit for the number of pods that can be set by the autoscaler. Required.")
cmd.MarkFlagRequired("max")
cmd.Flags().Int32Var(&o.CpuPercent, "cpu-percent", -1, fmt.Sprintf("The target average CPU utilization (represented as a percent of requested CPU) over all the pods. If it's not specified or negative, a default autoscaling policy will be used."))
cmd.Flags().Int32Var(&o.CPUPercent, "cpu-percent", -1, fmt.Sprintf("The target average CPU utilization (represented as a percent of requested CPU) over all the pods. If it's not specified or negative, a default autoscaling policy will be used."))
cmd.Flags().StringVar(&o.Name, "name", "", i18n.T("The name for the newly created object. If not specified, the name of the input resource will be used."))
cmdutil.AddDryRunFlag(cmd)
cmdutil.AddFilenameOptionFlags(cmd, o.FilenameOptions, "identifying the resource to autoscale.")
Expand Down Expand Up @@ -156,7 +156,7 @@ func (o *AutoscaleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args
Name: name,
MinReplicas: o.Min,
MaxReplicas: o.Max,
CPUPercent: o.CpuPercent,
CPUPercent: o.CPUPercent,
ScaleRefName: name,
ScaleRefKind: mapping.GroupVersionKind.Kind,
ScaleRefAPIVersion: mapping.GroupVersionKind.GroupVersion().String(),
Expand Down