Skip to content

Commit 2cfeeb7

Browse files
committed
Add more linters (nginx#2092)
Problem: We want to catch errors and styling issues as early as possible. Solution: Enable new linters.
1 parent a1a3192 commit 2cfeeb7

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+130
-106
lines changed

.github/.cache/buster-for-binary

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
touts zoosporangium viner glucolipin galeproof sanctionment siper galeproof glucolipin fructiculture

.github/.cache/buster-for-unit-tests

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
tzolkin sacristy hymnwise curative debris preachification suscept spongiculture medicably craniomete

.github/.cache/buster-for-vars

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
brandenburgs singleheartedly coal-whipper transmutations Tarandian arquebus cropland drumskin intern

.github/workflows/ci.yml

+9
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ jobs:
4343
uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7 # v5.0.1
4444
with:
4545
go-version: stable
46+
cache-dependency-path: |
47+
go.sum
48+
.github/.cache/buster-for-vars
4649
4750
- name: Check for changes
4851
uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
@@ -81,6 +84,9 @@ jobs:
8184
uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7 # v5.0.1
8285
with:
8386
go-version: stable
87+
cache-dependency-path: |
88+
go.sum
89+
.github/.cache/buster-for-unit-tests
8490
8591
- name: Run Tests
8692
run: make unit-test
@@ -136,6 +142,9 @@ jobs:
136142
uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7 # v5.0.1
137143
with:
138144
go-version: stable
145+
cache-dependency-path: |
146+
go.sum
147+
.github/.cache/buster-for-binary
139148
140149
- name: Create/Update Draft
141150
uses: lucacome/draft-release@8a63d32c79a171ae6048e614a8988f0ac3ed56d4 # v1.1.0

.golangci.yml

+22
Original file line numberDiff line numberDiff line change
@@ -37,33 +37,55 @@ linters-settings:
3737
- fieldalignment
3838
lll:
3939
line-length: 120
40+
dupword:
41+
ignore:
42+
- "test"
4043
linters:
4144
enable:
45+
- asasalint
4246
- asciicheck
47+
- dupword
4348
- errcheck
49+
- errname
4450
- errorlint
51+
- exportloopref
52+
- fatcontext
4553
- ginkgolinter
54+
- gocheckcompilerdirectives
4655
- gocyclo
56+
- godot
4757
- gofmt
4858
- gofumpt
4959
- goimports
5060
- gosec
5161
- gosimple
62+
- gosmopolitan
5263
- govet
5364
- ineffassign
65+
- intrange
5466
- lll
67+
- loggercheck
5568
- makezero
5669
- misspell
5770
- nilerr
5871
- noctx
72+
- nolintlint
5973
- predeclared
74+
- promlinter
75+
- reassign
6076
- revive
77+
- spancheck
6178
- staticcheck
79+
- stylecheck
80+
- tenv
81+
- thelper
6282
- typecheck
6383
- unconvert
6484
- unparam
6585
- unused
86+
- usestdlibvars
6687
- wastedassign
88+
- whitespace
6789
disable-all: true
6890
issues:
6991
max-issues-per-linter: 0

Makefile

+1-1
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ check-golangci-lint:
188188

189189
.PHONY: lint
190190
lint: check-golangci-lint ## Run golangci-lint against code
191-
golangci-lint run
191+
golangci-lint run --fix
192192

193193
.PHONY: unit-test
194194
unit-test: ## Run unit tests for the go code

apis/v1alpha1/clientsettingspolicy_types.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ type ClientKeepAlive struct {
108108
}
109109

110110
// ClientKeepAliveTimeout defines the timeouts related to keep-alive client connections.
111-
// Default: Default: https://nginx.org/en/docs/http/ngx_http_core_module.html#keepalive_timeout.
111+
// Default: https://nginx.org/en/docs/http/ngx_http_core_module.html#keepalive_timeout.
112112
type ClientKeepAliveTimeout struct {
113113
// Server sets the timeout during which a keep-alive client connection will stay open on the server side.
114114
// Setting this value to 0 disables keep-alive client connections.

apis/v1alpha1/register.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@ import (
99
// GroupName specifies the group name used to register the objects.
1010
const GroupName = "gateway.nginx.org"
1111

12-
// SchemeGroupVersion is group version used to register these objects
12+
// SchemeGroupVersion is group version used to register these objects.
1313
var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"}
1414

15-
// Resource takes an unqualified resource and returns a Group qualified GroupResource
15+
// Resource takes an unqualified resource and returns a Group qualified GroupResource.
1616
func Resource(resource string) schema.GroupResource {
1717
return SchemeGroupVersion.WithResource(resource).GroupResource()
1818
}

cmd/gateway/commands.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -444,8 +444,9 @@ func createProvisionerModeCommand() *cobra.Command {
444444

445445
// FIXME(pleshakov): Remove this command once NGF min supported Kubernetes version supports sleep action in
446446
// preStop hook.
447-
// nolint:lll
448447
// See https://github.com/kubernetes/enhancements/tree/4ec371d92dcd4f56a2ab18c8ba20bb85d8d20efe/keps/sig-node/3960-pod-lifecycle-sleep-action
448+
//
449+
//nolint:lll
449450
func createSleepCommand() *cobra.Command {
450451
// flag names
451452
const durationFlag = "duration"

cmd/gateway/commands_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ type flagTestCase struct {
1818
}
1919

2020
func testFlag(t *testing.T, cmd *cobra.Command, test flagTestCase) {
21+
t.Helper()
2122
g := NewWithT(t)
2223
// discard any output generated by cobra
2324
cmd.SetOut(io.Discard)

cmd/gateway/main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import (
55
"os"
66
)
77

8-
// Set during go build
8+
// Set during go build.
99
var (
1010
version string
1111
commit string

cmd/gateway/validation.go

+2-3
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import (
1414
)
1515

1616
const (
17-
// nolint:lll
1817
// Regex from: https://github.com/kubernetes-sigs/gateway-api/blob/v1.1.0/apis/v1/shared_types.go#L647
1918
controllerNameRegex = `^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[A-Za-z0-9\/\-._~%!$&'()*+,;=:]+$` //nolint:lll
2019
)
@@ -163,15 +162,15 @@ func validateEndpoint(endpoint string) error {
163162
return fmt.Errorf("%q must be in the format <host>:<port>", endpoint)
164163
}
165164

166-
// validatePort makes sure a given port is inside the valid port range for its usage
165+
// validatePort makes sure a given port is inside the valid port range for its usage.
167166
func validatePort(port int) error {
168167
if port < 1024 || port > 65535 {
169168
return fmt.Errorf("port outside of valid port range [1024 - 65535]: %v", port)
170169
}
171170
return nil
172171
}
173172

174-
// ensureNoPortCollisions checks if the same port has been defined multiple times
173+
// ensureNoPortCollisions checks if the same port has been defined multiple times.
175174
func ensureNoPortCollisions(ports ...int) error {
176175
seen := make(map[int]struct{})
177176

internal/framework/controller/predicate/service.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ func (ServicePortsChangedPredicate) Update(e event.UpdateEvent) bool {
5050
oldPortSet := make(map[ports]struct{})
5151
newPortSet := make(map[ports]struct{})
5252

53-
for i := 0; i < len(oldSvc.Spec.Ports); i++ {
53+
for i := range len(oldSvc.Spec.Ports) {
5454
oldPortSet[ports{servicePort: oldPorts[i].Port, targetPort: oldPorts[i].TargetPort}] = struct{}{}
5555
newPortSet[ports{servicePort: newPorts[i].Port, targetPort: newPorts[i].TargetPort}] = struct{}{}
5656
}

internal/framework/controller/reconciler.go

+7-3
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ func NewReconciler(cfg ReconcilerConfig) *Reconciler {
5353
}
5454
}
5555

56-
func (r *Reconciler) newObject(objectType ngftypes.ObjectType) ngftypes.ObjectType {
56+
func (r *Reconciler) mustCreateNewObject(objectType ngftypes.ObjectType) ngftypes.ObjectType {
5757
if r.cfg.OnlyMetadata {
5858
partialObj := &metav1.PartialObjectMetadata{}
5959
partialObj.SetGroupVersionKind(objectType.GetObjectKind().GroupVersionKind())
@@ -65,7 +65,11 @@ func (r *Reconciler) newObject(objectType ngftypes.ObjectType) ngftypes.ObjectTy
6565
t := reflect.TypeOf(objectType).Elem()
6666

6767
// We could've used objectType.DeepCopyObject() here, but it's a bit slower confirmed by benchmarks.
68-
return reflect.New(t).Interface().(client.Object)
68+
obj, ok := reflect.New(t).Interface().(client.Object)
69+
if !ok {
70+
panic("failed to create a new object")
71+
}
72+
return obj
6973
}
7074

7175
// Reconcile implements the reconcile.Reconciler Reconcile method.
@@ -83,7 +87,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req reconcile.Request) (reco
8387
}
8488
}
8589

86-
obj := r.newObject(r.cfg.ObjectType)
90+
obj := r.mustCreateNewObject(r.cfg.ObjectType)
8791

8892
if err := r.cfg.Getter.Get(ctx, req.NamespacedName, obj); err != nil {
8993
if !apierrors.IsNotFound(err) {

internal/framework/kinds/kinds.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@ import (
99
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
1010
)
1111

12-
// Gateway API Kinds
12+
// Gateway API Kinds.
1313
const (
14-
// Gateway is the Gateway Kind
14+
// Gateway is the Gateway Kind.
1515
Gateway = "Gateway"
1616
// GatewayClass is the GatewayClass Kind.
1717
GatewayClass = "GatewayClass"

internal/framework/runnables/cronjob.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ func NewCronJob(cfg CronJobConfig) *CronJob {
3737
}
3838

3939
// Start starts the cronjob.
40-
// Implements controller-runtime manager.Runnable
40+
// Implements controller-runtime manager.Runnable.
4141
func (j *CronJob) Start(ctx context.Context) error {
4242
select {
4343
case <-j.cfg.ReadyCh:

internal/framework/status/updater.go

-2
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,6 @@ func (u *Updater) writeStatuses(
121121
//
122122
// Note: this function is public because fake dependencies require us to test this function from the test package
123123
// to avoid import cycles.
124-
//
125-
//nolint:nilerr
126124
func NewRetryUpdateFunc(
127125
getter controller.Getter,
128126
updater K8sUpdater,

internal/mode/static/handler.go

+8-9
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import (
88

99
"github.com/go-logr/logr"
1010
ngxclient "github.com/nginxinc/nginx-plus-go-client/client"
11-
apiv1 "k8s.io/api/core/v1"
1211
v1 "k8s.io/api/core/v1"
1312
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1413
"k8s.io/apimachinery/pkg/types"
@@ -20,7 +19,7 @@ import (
2019
"github.com/nginxinc/nginx-gateway-fabric/internal/framework/events"
2120
"github.com/nginxinc/nginx-gateway-fabric/internal/framework/helpers"
2221
frameworkStatus "github.com/nginxinc/nginx-gateway-fabric/internal/framework/status"
23-
"github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/config"
22+
2423
ngfConfig "github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/config"
2524
ngxConfig "github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/nginx/config"
2625
"github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/nginx/file"
@@ -75,7 +74,7 @@ type eventHandlerConfig struct {
7574
// eventRecorder records events for Kubernetes resources.
7675
eventRecorder record.EventRecorder
7776
// usageReportConfig contains the configuration for NGINX Plus usage reporting.
78-
usageReportConfig *config.UsageReportConfig
77+
usageReportConfig *ngfConfig.UsageReportConfig
7978
// nginxConfiguredOnStartChecker sets the health of the Pod to Ready once we've written out our initial config.
8079
nginxConfiguredOnStartChecker *nginxConfiguredOnStartChecker
8180
// gatewayPodConfig contains information about this Pod.
@@ -89,7 +88,7 @@ type eventHandlerConfig struct {
8988
}
9089

9190
const (
92-
// groups for GroupStatusUpdater
91+
// groups for GroupStatusUpdater.
9392
groupAllExceptGateways = "all-graphs-except-gateways"
9493
groupGateways = "gateways"
9594
groupControlPlane = "control-plane"
@@ -308,7 +307,7 @@ func (h *eventHandlerImpl) parseAndCaptureEvent(ctx context.Context, logger logr
308307
}
309308
}
310309

311-
// updateNginxConf updates nginx conf files and reloads nginx
310+
// updateNginxConf updates nginx conf files and reloads nginx.
312311
func (h *eventHandlerImpl) updateNginxConf(ctx context.Context, conf dataplane.Configuration) error {
313312
files := h.cfg.generator.Generate(conf)
314313
if err := h.cfg.nginxFileMgr.ReplaceFiles(files); err != nil {
@@ -324,7 +323,7 @@ func (h *eventHandlerImpl) updateNginxConf(ctx context.Context, conf dataplane.C
324323

325324
// updateUpstreamServers is called only when endpoints have changed. It updates nginx conf files and then:
326325
// - if using NGINX Plus, determines which servers have changed and uses the N+ API to update them;
327-
// - otherwise if not using NGINX Plus, or an error was returned from the API, reloads nginx
326+
// - otherwise if not using NGINX Plus, or an error was returned from the API, reloads nginx.
328327
func (h *eventHandlerImpl) updateUpstreamServers(
329328
ctx context.Context,
330329
logger logr.Logger,
@@ -410,7 +409,7 @@ func serversEqual(newServers []ngxclient.UpstreamServer, oldServers []ngxclient.
410409
}
411410

412411
// updateControlPlaneAndSetStatus updates the control plane configuration and then sets the status
413-
// based on the outcome
412+
// based on the outcome.
414413
func (h *eventHandlerImpl) updateControlPlaneAndSetStatus(
415414
ctx context.Context,
416415
logger logr.Logger,
@@ -429,7 +428,7 @@ func (h *eventHandlerImpl) updateControlPlaneAndSetStatus(
429428
logger.Error(err, msg)
430429
h.cfg.eventRecorder.Eventf(
431430
cfg,
432-
apiv1.EventTypeWarning,
431+
v1.EventTypeWarning,
433432
"UpdateFailed",
434433
msg+": %s",
435434
err.Error(),
@@ -454,7 +453,7 @@ func getGatewayAddresses(
454453
ctx context.Context,
455454
k8sClient client.Client,
456455
svc *v1.Service,
457-
podConfig config.GatewayPodConfig,
456+
podConfig ngfConfig.GatewayPodConfig,
458457
) ([]gatewayv1.GatewayStatusAddress, error) {
459458
podAddress := []gatewayv1.GatewayStatusAddress{
460459
{

internal/mode/static/manager.go

+3-4
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ import (
6363
)
6464

6565
const (
66-
// clusterTimeout is a timeout for connections to the Kubernetes API
66+
// clusterTimeout is a timeout for connections to the Kubernetes API.
6767
clusterTimeout = 10 * time.Second
6868
)
6969

@@ -80,7 +80,7 @@ func init() {
8080
utilruntime.Must(appsv1.AddToScheme(scheme))
8181
}
8282

83-
// nolint:gocyclo
83+
//nolint:gocyclo
8484
func StartManager(cfg config.Config) error {
8585
nginxChecker := newNginxConfiguredOnStartChecker()
8686
mgr, err := createManager(cfg, nginxChecker)
@@ -530,7 +530,7 @@ func registerControllers(
530530
}
531531

532532
// 10 min jitter is enough per telemetry destination recommendation
533-
// For the default period of 24 hours, jitter will be 10min /(24*60)min = 0.0069
533+
// For the default period of 24 hours, jitter will be 10min /(24*60)min = 0.0069.
534534
const telemetryJitterFactor = 10.0 / (24 * 60) // added jitter is bound by jitterFactor * period
535535

536536
func createTelemetryJob(
@@ -566,7 +566,6 @@ func createTelemetryJob(
566566
if err != nil {
567567
return nil, fmt.Errorf("cannot create telemetry exporter: %w", err)
568568
}
569-
570569
} else {
571570
exporter = telemetry.NewLoggingExporter(cfg.Logger.WithName("telemetryExporter").V(1 /* debug */))
572571
}

internal/mode/static/metrics/collectors/controller.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ type ControllerCollector struct {
1515
eventBatchProcessDuration prometheus.Histogram
1616
}
1717

18-
// NewControllerCollector creates a new ControllerCollector
18+
// NewControllerCollector creates a new ControllerCollector.
1919
func NewControllerCollector(constLabels map[string]string) *ControllerCollector {
2020
nc := &ControllerCollector{
2121
eventBatchProcessDuration: prometheus.NewHistogram(

internal/mode/static/metrics/collectors/nginx.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,15 @@ const (
1616
nginxStatusURI = "http://config-status/stub_status"
1717
)
1818

19-
// NewNginxMetricsCollector creates an NginxCollector which fetches stats from NGINX over a unix socket
19+
// NewNginxMetricsCollector creates an NginxCollector which fetches stats from NGINX over a unix socket.
2020
func NewNginxMetricsCollector(constLabels map[string]string, logger log.Logger) prometheus.Collector {
2121
httpClient := runtime.GetSocketClient(nginxStatusSock)
2222
ngxClient := prometheusClient.NewNginxClient(&httpClient, nginxStatusURI)
2323

2424
return nginxCollector.NewNginxCollector(ngxClient, metrics.Namespace, constLabels, logger)
2525
}
2626

27-
// NewNginxPlusMetricsCollector creates an NginxCollector which fetches stats from NGINX Plus API over a unix socket
27+
// NewNginxPlusMetricsCollector creates an NginxCollector which fetches stats from NGINX Plus API over a unix socket.
2828
func NewNginxPlusMetricsCollector(
2929
plusClient *client.NginxClient,
3030
constLabels map[string]string,

0 commit comments

Comments
 (0)