Skip to content

Commit 5aab733

Browse files
authored
Merge pull request #660 from jetstack/linter_fix_part2
Linter fixes (part 2)
2 parents 4e2402c + 6d2a1d4 commit 5aab733

File tree

19 files changed

+94
-92
lines changed

19 files changed

+94
-92
lines changed

.golangci.yaml

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,12 @@ linters:
66
presets: [comments, common-false-positives, legacy, std-error-handling]
77
rules:
88
- linters:
9-
- bodyclose
10-
- errcheck
119
- errchkjson
1210
- forbidigo
13-
- gocritic
1411
- gosec
15-
- govet
1612
- musttag
1713
- nilerr
18-
- noctx
19-
- predeclared
20-
- staticcheck
21-
- unconvert
2214
- unparam
23-
- usestdlibvars
2415
text: .*
2516
paths: [third_party$, builtin$, examples$]
2617
warn-unused: true

api/common.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,5 +26,5 @@ func (t Time) MarshalJSON() ([]byte, error) {
2626
if err != nil {
2727
return nil, err
2828
}
29-
return []byte(jsonStr), nil
29+
return jsonStr, nil
3030
}

cmd/root.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ func setFlagsFromEnv(prefix string, fs *pflag.FlagSet) {
6767
}
6868
// remove trailing _ to reduce common errors with the prefix, i.e. people setting it to MY_PROG_
6969
cleanPrefix := strings.TrimSuffix(prefix, "_")
70-
name := fmt.Sprintf("%s_%s", cleanPrefix, strings.Replace(strings.ToUpper(f.Name), "-", "_", -1))
70+
name := fmt.Sprintf("%s_%s", cleanPrefix, strings.ReplaceAll(strings.ToUpper(f.Name), "-", "_"))
7171
if e, ok := os.LookupEnv(name); ok {
7272
_ = f.Value.Set(e)
7373
}

pkg/agent/config.go

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,9 @@ func InitAgentCmdFlags(c *cobra.Command, cfg *AgentCmdFlags) {
232232
false,
233233
fmt.Sprintf("Turns on the %s mode. The flag --credentials-file must also be passed.", JetstackSecureOAuth),
234234
)
235-
c.PersistentFlags().MarkHidden("venafi-cloud")
235+
if err := c.PersistentFlags().MarkHidden("venafi-cloud"); err != nil {
236+
panic(err)
237+
}
236238
c.PersistentFlags().StringVarP(
237239
&cfg.ClientID,
238240
"client-id",
@@ -247,7 +249,7 @@ func InitAgentCmdFlags(c *cobra.Command, cfg *AgentCmdFlags) {
247249
"private-key-path",
248250
"",
249251
"",
250-
fmt.Sprintf("To be used in conjunction with --client-id. The path to the private key file for the service account."),
252+
"To be used in conjunction with --client-id. The path to the private key file for the service account.",
251253
)
252254
c.PersistentFlags().BoolVarP(
253255
&cfg.OneShot,
@@ -334,7 +336,9 @@ func InitAgentCmdFlags(c *cobra.Command, cfg *AgentCmdFlags) {
334336
false,
335337
"Deprecated. No longer has an effect.",
336338
)
337-
c.PersistentFlags().MarkDeprecated("disable-compression", "no longer has an effect")
339+
if err := c.PersistentFlags().MarkDeprecated("disable-compression", "no longer has an effect"); err != nil {
340+
panic(err)
341+
}
338342

339343
// This is a hidden feature flag we use to build the "Machine Hub" feature
340344
// gradually without impacting customers. Once the feature is GA, we will
@@ -345,7 +349,9 @@ func InitAgentCmdFlags(c *cobra.Command, cfg *AgentCmdFlags) {
345349
false,
346350
"Enables the MachineHub mode. The agent will push data to CyberArk MachineHub.",
347351
)
348-
c.PersistentFlags().MarkHidden("machine-hub")
352+
if err := c.PersistentFlags().MarkHidden("machine-hub"); err != nil {
353+
panic(err)
354+
}
349355

350356
}
351357

@@ -531,8 +537,8 @@ func ValidateAndCombineConfig(log logr.Logger, cfg Config, flags AgentCmdFlags)
531537
// Validation of `venafi-cloud.upload_path`.
532538
{
533539
var uploadPath string
534-
switch {
535-
case res.TLSPKMode == VenafiCloudKeypair:
540+
switch res.TLSPKMode { // nolint:exhaustive
541+
case VenafiCloudKeypair:
536542
if cfg.VenafiCloud == nil || cfg.VenafiCloud.UploadPath == "" {
537543
errs = multierror.Append(errs, fmt.Errorf("the venafi-cloud.upload_path field is required when using the %s mode", res.TLSPKMode))
538544
break // Skip to the end of the switch statement.
@@ -544,7 +550,7 @@ func ValidateAndCombineConfig(log logr.Logger, cfg Config, flags AgentCmdFlags)
544550
}
545551

546552
uploadPath = cfg.VenafiCloud.UploadPath
547-
case res.TLSPKMode == VenafiCloudVenafiConnection:
553+
case VenafiCloudVenafiConnection:
548554
// The venafi-cloud.upload_path was initially meant to let users
549555
// configure HTTP proxies, but it has never been used since HTTP
550556
// proxies don't rewrite paths. Thus, we've disabled the ability to
@@ -577,18 +583,18 @@ func ValidateAndCombineConfig(log logr.Logger, cfg Config, flags AgentCmdFlags)
577583
if res.TLSPKMode != Off {
578584
var clusterID string
579585
var organizationID string // Only used by the old jetstack-secure mode.
580-
switch {
581-
case res.TLSPKMode == VenafiCloudKeypair:
586+
switch res.TLSPKMode { // nolint:exhaustive
587+
case VenafiCloudKeypair:
582588
if cfg.ClusterID == "" {
583589
errs = multierror.Append(errs, fmt.Errorf("cluster_id is required in %s mode", res.TLSPKMode))
584590
}
585591
clusterID = cfg.ClusterID
586-
case res.TLSPKMode == VenafiCloudVenafiConnection:
592+
case VenafiCloudVenafiConnection:
587593
if cfg.ClusterID == "" {
588594
errs = multierror.Append(errs, fmt.Errorf("cluster_id is required in %s mode", res.TLSPKMode))
589595
}
590596
clusterID = cfg.ClusterID
591-
case res.TLSPKMode == JetstackSecureOAuth || res.TLSPKMode == JetstackSecureAPIToken:
597+
case JetstackSecureOAuth, JetstackSecureAPIToken:
592598
if cfg.OrganizationID == "" {
593599
errs = multierror.Append(errs, fmt.Errorf("organization_id is required"))
594600
}
@@ -637,7 +643,7 @@ func ValidateAndCombineConfig(log logr.Logger, cfg Config, flags AgentCmdFlags)
637643
}
638644

639645
// Validation of --install-namespace.
640-
var installNS string = flags.InstallNS
646+
installNS := flags.InstallNS
641647
if flags.InstallNS == "" {
642648
var err error
643649
installNS, err = getInClusterNamespace()
@@ -650,7 +656,7 @@ func ValidateAndCombineConfig(log logr.Logger, cfg Config, flags AgentCmdFlags)
650656
// Validation of --venafi-connection and --venafi-connection-namespace.
651657
if res.TLSPKMode == VenafiCloudVenafiConnection {
652658
res.VenConnName = flags.VenConnName
653-
var venConnNS string = flags.VenConnNS
659+
venConnNS := flags.VenConnNS
654660
if flags.VenConnNS == "" {
655661
venConnNS = installNS
656662
}
@@ -714,8 +720,8 @@ func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClie
714720

715721
var preflightClient client.Client
716722
metadata := &api.AgentMetadata{Version: version.PreflightVersion, ClusterID: cfg.ClusterID}
717-
switch {
718-
case cfg.TLSPKMode == JetstackSecureOAuth:
723+
switch cfg.TLSPKMode {
724+
case JetstackSecureOAuth:
719725
// Note that there are no command line flags to configure the
720726
// JetstackSecureOAuth mode.
721727
credsBytes, err := readCredentialsFile(flagCredentialsPath)
@@ -734,7 +740,7 @@ func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClie
734740
if err != nil {
735741
errs = multierror.Append(errs, err)
736742
}
737-
case cfg.TLSPKMode == VenafiCloudKeypair:
743+
case VenafiCloudKeypair:
738744
var creds client.Credentials
739745

740746
if flagClientID != "" && flagCredentialsPath != "" {
@@ -750,14 +756,15 @@ func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClie
750756
break
751757
}
752758

753-
if flagClientID != "" && flagPrivateKeyPath != "" {
759+
switch {
760+
case flagClientID != "" && flagPrivateKeyPath != "":
754761
// If --client-id and --private-key-path are passed, then
755762
// --credentials-file is ignored.
756763
creds = &client.VenafiSvcAccountCredentials{
757764
ClientID: flagClientID,
758765
PrivateKeyFile: flagPrivateKeyPath,
759766
}
760-
} else if flagCredentialsPath != "" {
767+
case flagCredentialsPath != "":
761768
credsBytes, err := readCredentialsFile(flagCredentialsPath)
762769
if err != nil {
763770
errs = multierror.Append(errs, multierror.Prefix(err, "credentials file:"))
@@ -768,7 +775,7 @@ func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClie
768775
errs = multierror.Append(errs, multierror.Prefix(err, "credentials file:"))
769776
break // Don't continue with the client since creds is invalid.
770777
}
771-
} else {
778+
default:
772779
return nil, fmt.Errorf("programmer mistake: --client-id and --private-key-path or --credentials-file must have been provided")
773780
}
774781

@@ -777,7 +784,7 @@ func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClie
777784
if err != nil {
778785
errs = multierror.Append(errs, err)
779786
}
780-
case cfg.TLSPKMode == VenafiCloudVenafiConnection:
787+
case VenafiCloudVenafiConnection:
781788
var restCfg *rest.Config
782789
restCfg, err := kubeconfig.LoadRESTConfig("")
783790
if err != nil {
@@ -789,13 +796,13 @@ func validateCredsAndCreateClient(log logr.Logger, flagCredentialsPath, flagClie
789796
if err != nil {
790797
errs = multierror.Append(errs, err)
791798
}
792-
case cfg.TLSPKMode == JetstackSecureAPIToken:
799+
case JetstackSecureAPIToken:
793800
var err error
794801
preflightClient, err = client.NewAPITokenClient(metadata, flagAPIToken, cfg.Server)
795802
if err != nil {
796803
errs = multierror.Append(errs, err)
797804
}
798-
case cfg.TLSPKMode == Off:
805+
case Off:
799806
// No client needed in this mode.
800807
default:
801808
panic(fmt.Errorf("programmer mistake: auth mode not implemented: %s", cfg.TLSPKMode))

pkg/client/client_oauth.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ func (c *OAuthClient) renewAccessToken(ctx context.Context) error {
186186
payload.Set("audience", audience)
187187
payload.Set("username", c.credentials.UserID)
188188
payload.Set("password", c.credentials.UserSecret)
189-
req, err := http.NewRequestWithContext(ctx, "POST", tokenURL, strings.NewReader(payload.Encode()))
189+
req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(payload.Encode()))
190190
if err != nil {
191191
return errors.WithStack(err)
192192
}

pkg/client/client_venafi_cloud.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ type (
7171
}
7272

7373
accessTokenInformation struct {
74-
AccessToken string `json:"access_token"` //base 64 encoded token
74+
AccessToken string `json:"access_token"` // base 64 encoded token
7575
Type string `json:"token_type"` // always be “bearer” for now
7676
ExpiresIn int64 `json:"expires_in"` // number of seconds after which the access token will expire
7777
}

pkg/datagatherer/k8s/cache.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,14 +56,14 @@ func onAdd(log logr.Logger, obj interface{}, dgCache *cache.Cache) {
5656
// onUpdate handles the informer update events, replacing the old object with the new one
5757
// if it's present in the data gatherer's cache, (if the object isn't present, it gets added).
5858
// The cache key is the uid of the object
59-
func onUpdate(log logr.Logger, old, new interface{}, dgCache *cache.Cache) {
60-
item, ok := old.(cacheResource)
59+
func onUpdate(log logr.Logger, oldObj, newObj interface{}, dgCache *cache.Cache) {
60+
item, ok := oldObj.(cacheResource)
6161
if ok {
62-
cacheObject := updateCacheGatheredResource(string(item.GetUID()), new, dgCache)
62+
cacheObject := updateCacheGatheredResource(string(item.GetUID()), newObj, dgCache)
6363
dgCache.Set(string(item.GetUID()), cacheObject, cache.DefaultExpiration)
6464
return
6565
}
66-
logCacheUpdateFailure(log, old, "update")
66+
logCacheUpdateFailure(log, oldObj, "update")
6767
}
6868

6969
// onDelete handles the informer deletion events, updating the object's properties with the deletion

pkg/datagatherer/k8s/cache_test.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ func TestOnAddCache(t *testing.T) {
5252
getObject("v1", "Service", "testservice", "testns", false),
5353
getObject("foobar/v1", "NotFoo", "notfoo", "testns", false),
5454
},
55-
eventFunc: func(log logr.Logger, old, new interface{}, dgCache *cache.Cache) { onDelete(log, old, dgCache) },
55+
eventFunc: func(log logr.Logger, oldObj, newObj interface{}, dgCache *cache.Cache) {
56+
onDelete(log, oldObj, dgCache)
57+
},
5658
expected: []*api.GatheredResource{
5759
makeGatheredResource(
5860
getObject("foobar/v1", "Foo", "testfoo", "testns", false),

pkg/datagatherer/k8s/dynamic.go

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -76,27 +76,27 @@ func (c *ConfigDynamic) UnmarshalYAML(unmarshal func(interface{}) error) error {
7676

7777
// validate validates the configuration.
7878
func (c *ConfigDynamic) validate() error {
79-
var errors []string
79+
var errs []string
8080
if len(c.ExcludeNamespaces) > 0 && len(c.IncludeNamespaces) > 0 {
81-
errors = append(errors, "cannot set excluded and included namespaces")
81+
errs = append(errs, "cannot set excluded and included namespaces")
8282
}
8383

8484
if c.GroupVersionResource.Resource == "" {
85-
errors = append(errors, "invalid configuration: GroupVersionResource.Resource cannot be empty")
85+
errs = append(errs, "invalid configuration: GroupVersionResource.Resource cannot be empty")
8686
}
8787

8888
for i, selectorString := range c.FieldSelectors {
8989
if selectorString == "" {
90-
errors = append(errors, fmt.Sprintf("invalid field selector %d: must not be empty", i))
90+
errs = append(errs, fmt.Sprintf("invalid field selector %d: must not be empty", i))
9191
}
9292
_, err := fields.ParseSelector(selectorString)
9393
if err != nil {
94-
errors = append(errors, fmt.Sprintf("invalid field selector %d: %s", i, err))
94+
errs = append(errs, fmt.Sprintf("invalid field selector %d: %s", i, err))
9595
}
9696
}
9797

98-
if len(errors) > 0 {
99-
return fmt.Errorf(strings.Join(errors, ", "))
98+
if len(errs) > 0 {
99+
return errors.New(strings.Join(errs, ", "))
100100
}
101101

102102
return nil
@@ -221,8 +221,8 @@ func (c *ConfigDynamic) newDataGathererWithClient(ctx context.Context, cl dynami
221221
AddFunc: func(obj interface{}) {
222222
onAdd(log, obj, dgCache)
223223
},
224-
UpdateFunc: func(old, new interface{}) {
225-
onUpdate(log, old, new, dgCache)
224+
UpdateFunc: func(oldObj, newObj interface{}) {
225+
onUpdate(log, oldObj, newObj, dgCache)
226226
},
227227
DeleteFunc: func(obj interface{}) {
228228
onDelete(log, obj, dgCache)
@@ -329,7 +329,7 @@ func (g *DataGathererDynamic) Fetch() (interface{}, int, error) {
329329
fetchNamespaces = []string{metav1.NamespaceAll}
330330
}
331331

332-
//delete expired items from the cache
332+
// delete expired items from the cache
333333
g.cache.DeleteExpired()
334334
for _, item := range g.cache.Items() {
335335
// filter cache items by namespace
@@ -371,11 +371,15 @@ func redactList(list []*api.GatheredResource, excludeAnnotKeys, excludeLabelKeys
371371
for _, gvk := range gvks {
372372
// secret object
373373
if gvk.Kind == "Secret" && (gvk.Group == "core" || gvk.Group == "") {
374-
Select(SecretSelectedFields, resource)
374+
if err := Select(SecretSelectedFields, resource); err != nil {
375+
return err
376+
}
375377

376378
// route object
377379
} else if gvk.Kind == "Route" && gvk.Group == "route.openshift.io" {
378-
Select(RouteSelectedFields, resource)
380+
if err := Select(RouteSelectedFields, resource); err != nil {
381+
return err
382+
}
379383
}
380384
}
381385

0 commit comments

Comments
 (0)