Skip to content

Commit 9971881

Browse files
authored
Fix import shadowing and unchecked type assertions in test (#2574)
1 parent a2aa4d3 commit 9971881

18 files changed

+82
-58
lines changed

.golangci.yml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,28 +9,36 @@ linters-settings:
99
ignore-generated-header: true
1010
rules:
1111
- name: blank-imports
12+
- name: constant-logical-expr
1213
- name: context-as-argument
1314
- name: context-keys-type
15+
- name: defer
1416
- name: dot-imports
1517
arguments:
1618
- allowedPackages:
1719
- github.com/onsi/gomega
1820
- github.com/onsi/ginkgo/v2
21+
- name: duplicated-imports
1922
- name: empty-block
2023
- name: error-naming
2124
- name: error-return
2225
- name: error-strings
2326
- name: errorf
2427
- name: exported
28+
- name: import-shadowing
2529
- name: increment-decrement
2630
- name: indent-error-flow
2731
- name: package-comments
2832
- name: range
33+
- name: range-val-address
34+
- name: range-val-in-closure
2935
- name: receiver-naming
3036
- name: redefines-builtin-id
37+
- name: string-of-int
3138
- name: superfluous-else
3239
- name: time-naming
3340
- name: unexported-return
41+
- name: unnecessary-stmt
3442
- name: unreachable-code
3543
- name: unused-parameter
3644
- name: var-declaration
@@ -80,9 +88,11 @@ linters:
8088
- lll
8189
- loggercheck
8290
- makezero
91+
- mirror
8392
- misspell
8493
- musttag
8594
- nilerr
95+
- nilnil
8696
- noctx
8797
- nolintlint
8898
- predeclared

internal/framework/controller/reconciler_test.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,11 @@ var _ = Describe("Reconciler", func() {
6666
) error {
6767
Expect(object).To(BeAssignableToTypeOf(&v1.HTTPRoute{}))
6868
Expect(nsname).To(Equal(client.ObjectKeyFromObject(hr)))
69+
Expect(hr).ToNot(BeNil())
6970

70-
hr.DeepCopyInto(object.(*v1.HTTPRoute))
71+
hrObj, ok := object.(*v1.HTTPRoute)
72+
Expect(ok).To(BeTrue(), "object is not *v1.HTTPRoute")
73+
hr.DeepCopyInto(hrObj)
7174

7275
return nil
7376
}

internal/framework/events/first_eventbatch_preparer_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,8 @@ var _ = Describe("FirstEventBatchPreparer", func() {
108108
fakeReader.ListCalls(
109109
func(_ context.Context, list client.ObjectList, _ ...client.ListOption) error {
110110
httpRoute := v1.HTTPRoute{ObjectMeta: metav1.ObjectMeta{Name: "test"}}
111-
typedList := list.(*v1.HTTPRouteList)
111+
typedList, ok := list.(*v1.HTTPRouteList)
112+
Expect(ok).To(BeTrue(), "expected list to be of type *v1.HTTPRouteList")
112113
typedList.Items = append(typedList.Items, httpRoute)
113114

114115
return nil

internal/framework/helpers/helpers.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,12 @@ func GetPointer[T any](v T) *T {
3333
// making it is possible to use it in tests when comparing against values returned by the fake client.
3434
// It panics if it fails to process the time.
3535
func PrepareTimeForFakeClient(t metav1.Time) metav1.Time {
36-
bytes, err := t.Marshal()
36+
b, err := t.Marshal()
3737
if err != nil {
3838
panic(fmt.Errorf("failed to marshal time: %w", err))
3939
}
4040

41-
if err = t.Unmarshal(bytes); err != nil {
41+
if err = t.Unmarshal(b); err != nil {
4242
panic(fmt.Errorf("failed to unmarshal time: %w", err))
4343
}
4444

@@ -78,10 +78,10 @@ func EqualPointers[T comparable](p1, p2 *T) bool {
7878
}
7979

8080
// MustExecuteTemplate executes the template with the given data.
81-
func MustExecuteTemplate(template *template.Template, data interface{}) []byte {
81+
func MustExecuteTemplate(templ *template.Template, data interface{}) []byte {
8282
var buf bytes.Buffer
8383

84-
if err := template.Execute(&buf, data); err != nil {
84+
if err := templ.Execute(&buf, data); err != nil {
8585
panic(err)
8686
}
8787

internal/framework/status/leader_aware_group_updater_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ var _ = Describe("LeaderAwareGroupUpdater", func() {
5959

6060
if updateNeeded {
6161
setter = func(obj client.Object) bool {
62-
gc := obj.(*v1.GatewayClass)
62+
gc, ok := obj.(*v1.GatewayClass)
63+
Expect(ok).To(BeTrue(), "obj is not a *v1.GatewayClass")
6364
gc.Status = createGCStatus(condType)
6465
return true
6566
}

internal/framework/status/updater.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,9 @@ type Updater struct {
5454
}
5555

5656
// NewUpdater creates a new Updater.
57-
func NewUpdater(client client.Client, logger logr.Logger) *Updater {
57+
func NewUpdater(c client.Client, logger logr.Logger) *Updater {
5858
return &Updater{
59-
client: client,
59+
client: c,
6060
logger: logger,
6161
}
6262
}

internal/framework/status/updater_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,8 @@ func prepareReq(name string, condType string, updateNeeded bool) UpdateRequest {
6969
var setter Setter
7070
if updateNeeded {
7171
setter = func(obj client.Object) bool {
72-
gc := obj.(*v1.GatewayClass)
72+
gc, ok := obj.(*v1.GatewayClass)
73+
Expect(ok).To(BeTrue(), "obj is not a *v1.GatewayClass")
7374
gc.Status = createGCStatus(condType)
7475
return true
7576
}

internal/mode/static/handler.go

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ func (h *eventHandlerImpl) HandleEventBatch(ctx context.Context, logger logr.Log
181181
h.parseAndCaptureEvent(ctx, logger, event)
182182
}
183183

184-
changeType, graph := h.cfg.processor.Process()
184+
changeType, gr := h.cfg.processor.Process()
185185

186186
var err error
187187
switch changeType {
@@ -193,7 +193,7 @@ func (h *eventHandlerImpl) HandleEventBatch(ctx context.Context, logger logr.Log
193193
return
194194
case state.EndpointsOnlyChange:
195195
h.version++
196-
cfg := dataplane.BuildConfiguration(ctx, graph, h.cfg.serviceResolver, h.version)
196+
cfg := dataplane.BuildConfiguration(ctx, gr, h.cfg.serviceResolver, h.version)
197197

198198
h.setLatestConfiguration(&cfg)
199199

@@ -204,7 +204,7 @@ func (h *eventHandlerImpl) HandleEventBatch(ctx context.Context, logger logr.Log
204204
)
205205
case state.ClusterStateChange:
206206
h.version++
207-
cfg := dataplane.BuildConfiguration(ctx, graph, h.cfg.serviceResolver, h.version)
207+
cfg := dataplane.BuildConfiguration(ctx, gr, h.cfg.serviceResolver, h.version)
208208

209209
h.setLatestConfiguration(&cfg)
210210

@@ -230,10 +230,10 @@ func (h *eventHandlerImpl) HandleEventBatch(ctx context.Context, logger logr.Log
230230

231231
h.latestReloadResult = nginxReloadRes
232232

233-
h.updateStatuses(ctx, logger, graph)
233+
h.updateStatuses(ctx, logger, gr)
234234
}
235235

236-
func (h *eventHandlerImpl) updateStatuses(ctx context.Context, logger logr.Logger, graph *graph.Graph) {
236+
func (h *eventHandlerImpl) updateStatuses(ctx context.Context, logger logr.Logger, gr *graph.Graph) {
237237
gwAddresses, err := getGatewayAddresses(ctx, h.cfg.k8sClient, nil, h.cfg.gatewayPodConfig)
238238
if err != nil {
239239
logger.Error(err, "Setting GatewayStatusAddress to Pod IP Address")
@@ -243,18 +243,18 @@ func (h *eventHandlerImpl) updateStatuses(ctx context.Context, logger logr.Logge
243243

244244
var gcReqs []frameworkStatus.UpdateRequest
245245
if h.cfg.updateGatewayClassStatus {
246-
gcReqs = status.PrepareGatewayClassRequests(graph.GatewayClass, graph.IgnoredGatewayClasses, transitionTime)
246+
gcReqs = status.PrepareGatewayClassRequests(gr.GatewayClass, gr.IgnoredGatewayClasses, transitionTime)
247247
}
248248
routeReqs := status.PrepareRouteRequests(
249-
graph.L4Routes,
250-
graph.Routes,
249+
gr.L4Routes,
250+
gr.Routes,
251251
transitionTime,
252252
h.latestReloadResult,
253253
h.cfg.gatewayCtlrName,
254254
)
255255

256-
polReqs := status.PrepareBackendTLSPolicyRequests(graph.BackendTLSPolicies, transitionTime, h.cfg.gatewayCtlrName)
257-
ngfPolReqs := status.PrepareNGFPolicyRequests(graph.NGFPolicies, transitionTime, h.cfg.gatewayCtlrName)
256+
polReqs := status.PrepareBackendTLSPolicyRequests(gr.BackendTLSPolicies, transitionTime, h.cfg.gatewayCtlrName)
257+
ngfPolReqs := status.PrepareNGFPolicyRequests(gr.NGFPolicies, transitionTime, h.cfg.gatewayCtlrName)
258258

259259
reqs := make([]frameworkStatus.UpdateRequest, 0, len(gcReqs)+len(routeReqs)+len(polReqs)+len(ngfPolReqs))
260260
reqs = append(reqs, gcReqs...)
@@ -267,8 +267,8 @@ func (h *eventHandlerImpl) updateStatuses(ctx context.Context, logger logr.Logge
267267
// We put Gateway status updates separately from the rest of the statuses because we want to be able
268268
// to update them separately from the rest of the graph whenever the public IP of NGF changes.
269269
gwReqs := status.PrepareGatewayRequests(
270-
graph.Gateway,
271-
graph.IgnoredGateways,
270+
gr.Gateway,
271+
gr.IgnoredGateways,
272272
transitionTime,
273273
gwAddresses,
274274
h.latestReloadResult,
@@ -558,15 +558,15 @@ func (h *eventHandlerImpl) nginxGatewayServiceUpsert(ctx context.Context, logger
558558
logger.Error(err, "Setting GatewayStatusAddress to Pod IP Address")
559559
}
560560

561-
graph := h.cfg.processor.GetLatestGraph()
562-
if graph == nil {
561+
gr := h.cfg.processor.GetLatestGraph()
562+
if gr == nil {
563563
return
564564
}
565565

566566
transitionTime := metav1.Now()
567567
gatewayStatuses := status.PrepareGatewayRequests(
568-
graph.Gateway,
569-
graph.IgnoredGateways,
568+
gr.Gateway,
569+
gr.IgnoredGateways,
570570
transitionTime,
571571
gwAddresses,
572572
h.latestReloadResult,
@@ -584,15 +584,15 @@ func (h *eventHandlerImpl) nginxGatewayServiceDelete(
584584
logger.Error(err, "Setting GatewayStatusAddress to Pod IP Address")
585585
}
586586

587-
graph := h.cfg.processor.GetLatestGraph()
588-
if graph == nil {
587+
gr := h.cfg.processor.GetLatestGraph()
588+
if gr == nil {
589589
return
590590
}
591591

592592
transitionTime := metav1.Now()
593593
gatewayStatuses := status.PrepareGatewayRequests(
594-
graph.Gateway,
595-
graph.IgnoredGateways,
594+
gr.Gateway,
595+
gr.IgnoredGateways,
596596
transitionTime,
597597
gwAddresses,
598598
h.latestReloadResult,

internal/mode/static/manager.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -715,14 +715,14 @@ func setInitialConfig(
715715
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
716716
defer cancel()
717717

718-
var config ngfAPI.NginxGateway
718+
var conf ngfAPI.NginxGateway
719719
// Polling to wait for CRD to exist if the Deployment is created first.
720720
if err := wait.PollUntilContextCancel(
721721
ctx,
722722
500*time.Millisecond,
723723
true, /* poll immediately */
724724
func(ctx context.Context) (bool, error) {
725-
if err := reader.Get(ctx, configName, &config); err != nil {
725+
if err := reader.Get(ctx, configName, &conf); err != nil {
726726
if !apierrors.IsNotFound(err) {
727727
return false, err
728728
}
@@ -736,7 +736,7 @@ func setInitialConfig(
736736

737737
// status is not updated until the status updater's cache is started and the
738738
// resource is processed by the controller
739-
return updateControlPlane(&config, logger, eventRecorder, configName, logLevelSetter)
739+
return updateControlPlane(&conf, logger, eventRecorder, configName, logLevelSetter)
740740
}
741741

742742
func getMetricsOptions(cfg config.MetricsConfig) metricsserver.Options {

internal/mode/static/state/dataplane/configuration.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -607,7 +607,7 @@ func (hpr *hostPathRules) maxServerCount() int {
607607
func buildUpstreams(
608608
ctx context.Context,
609609
listeners []*graph.Listener,
610-
resolver resolver.ServiceResolver,
610+
svcResolver resolver.ServiceResolver,
611611
ipFamily IPFamilyType,
612612
) []Upstream {
613613
// There can be duplicate upstreams if multiple routes reference the same upstream.
@@ -643,7 +643,7 @@ func buildUpstreams(
643643

644644
var errMsg string
645645

646-
eps, err := resolver.Resolve(ctx, br.SvcNsName, br.ServicePort, allowedAddressType)
646+
eps, err := svcResolver.Resolve(ctx, br.SvcNsName, br.ServicePort, allowedAddressType)
647647
if err != nil {
648648
errMsg = err.Error()
649649
}

internal/mode/static/state/graph/gateway_listener.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -306,8 +306,8 @@ func validateListenerAllowedRouteKind(listener v1.Listener) (conds []conditions.
306306
}
307307

308308
func getListenerSupportedKinds(listener v1.Listener) []v1.RouteGroupKind {
309-
_, kinds := getAndValidateListenerSupportedKinds(listener)
310-
return kinds
309+
_, sk := getAndValidateListenerSupportedKinds(listener)
310+
return sk
311311
}
312312

313313
func validateListenerLabelSelector(listener v1.Listener) (conds []conditions.Condition, attachable bool) {

internal/mode/static/state/graph/policies.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -154,19 +154,19 @@ func attachPolicyToGateway(
154154
}
155155

156156
func processPolicies(
157-
policies map[PolicyKey]policies.Policy,
157+
pols map[PolicyKey]policies.Policy,
158158
validator validation.PolicyValidator,
159159
gateways processedGateways,
160160
routes map[RouteKey]*L7Route,
161161
globalSettings *policies.GlobalSettings,
162162
) map[PolicyKey]*Policy {
163-
if len(policies) == 0 || gateways.Winner == nil {
163+
if len(pols) == 0 || gateways.Winner == nil {
164164
return nil
165165
}
166166

167167
processedPolicies := make(map[PolicyKey]*Policy)
168168

169-
for key, policy := range policies {
169+
for key, policy := range pols {
170170
var conds []conditions.Condition
171171

172172
targetRefs := make([]PolicyTargetRef, 0, len(policy.GetTargetRefs()))
@@ -280,7 +280,7 @@ func buildHostPortPaths(route *L7Route) map[string]string {
280280

281281
// markConflictedPolicies marks policies that conflict with a policy of greater precedence as invalid.
282282
// Policies are sorted by timestamp and then alphabetically.
283-
func markConflictedPolicies(policies map[PolicyKey]*Policy, validator validation.PolicyValidator) {
283+
func markConflictedPolicies(pols map[PolicyKey]*Policy, validator validation.PolicyValidator) {
284284
// Policies can only conflict if they are the same policy type (gvk) and they target the same resource(s).
285285
type key struct {
286286
policyGVK schema.GroupVersionKind
@@ -289,7 +289,7 @@ func markConflictedPolicies(policies map[PolicyKey]*Policy, validator validation
289289

290290
possibles := make(map[key][]*Policy)
291291

292-
for policyKey, policy := range policies {
292+
for policyKey, policy := range pols {
293293
// If a policy is invalid, it cannot conflict with another policy.
294294
if policy.Valid {
295295
for _, ref := range policy.TargetRefs {

internal/mode/static/state/resolver/resolver.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,8 @@ type ServiceResolverImpl struct {
4444
}
4545

4646
// NewServiceResolverImpl creates a new instance of a ServiceResolverImpl.
47-
func NewServiceResolverImpl(client client.Client) *ServiceResolverImpl {
48-
return &ServiceResolverImpl{client: client}
47+
func NewServiceResolverImpl(c client.Client) *ServiceResolverImpl {
48+
return &ServiceResolverImpl{client: c}
4949
}
5050

5151
// Resolve resolves a Service's NamespacedName and ServicePort to a list of Endpoints.

internal/mode/static/state/store.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@ type ngfPolicyObjectStore struct {
3636

3737
// newNGFPolicyObjectStore returns a new ngfPolicyObjectStore.
3838
func newNGFPolicyObjectStore(
39-
policies map[graph.PolicyKey]policies.Policy,
39+
pols map[graph.PolicyKey]policies.Policy,
4040
gvkFunc kinds.MustExtractGVK,
4141
) *ngfPolicyObjectStore {
4242
return &ngfPolicyObjectStore{
43-
policies: policies,
43+
policies: pols,
4444
extractGVKFunc: gvkFunc,
4545
}
4646
}

0 commit comments

Comments
 (0)