Skip to content

Commit 6dfdcdd

Browse files
committed
Add more linters
Problem: We want to catch errors and styling issues as early as possible. Solution: Enable new linters.
1 parent 212c0f6 commit 6dfdcdd

Some content is hidden

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

53 files changed

+128
-105
lines changed

.github/workflows/ci.yml

+6
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
@@ -87,6 +90,9 @@ jobs:
8790
uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7 # v5.0.1
8891
with:
8992
go-version: stable
93+
cache-dependency-path: |
94+
go.sum
95+
.github/.cache/buster-for-unit-tests
9096
9197
- name: Run Tests
9298
run: make unit-test

.golangci.yml

+23
Original file line numberDiff line numberDiff line change
@@ -37,32 +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
53+
- forcetypeassert
4554
- ginkgolinter
55+
- gocheckcompilerdirectives
4656
- gocyclo
57+
- godot
4758
- gofmt
4859
- gofumpt
4960
- goimports
5061
- gosec
5162
- gosimple
63+
- gosmopolitan
5264
- govet
5365
- ineffassign
66+
- intrange
5467
- lll
68+
- loggercheck
5569
- makezero
5670
- misspell
5771
- nilerr
5872
- noctx
73+
- nolintlint
74+
- prealloc
5975
- predeclared
76+
- promlinter
77+
- reassign
6078
- revive
79+
- spancheck
6180
- staticcheck
81+
- stylecheck
82+
- tenv
83+
- thelper
6284
- typecheck
6385
- unconvert
6486
- unparam
6587
- unused
88+
- usestdlibvars
6689
- wastedassign
6790
disable-all: true
6891
issues:

Makefile

+1-1
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ check-golangci-lint:
178178

179179
.PHONY: lint
180180
lint: check-golangci-lint ## Run golangci-lint against code
181-
golangci-lint run
181+
golangci-lint run --fix
182182

183183
.PHONY: unit-test
184184
unit-test: ## Run unit tests for the go code

apis/v1alpha1/clientsettingspolicy_types.go

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

109109
// ClientKeepAliveTimeout defines the timeouts related to keep-alive client connections.
110-
// Default: Default: https://nginx.org/en/docs/http/ngx_http_core_module.html#keepalive_timeout.
110+
// Default: https://nginx.org/en/docs/http/ngx_http_core_module.html#keepalive_timeout.
111111
type ClientKeepAliveTimeout struct {
112112
// Server sets the timeout during which a keep-alive client connection will stay open on the server side.
113113
// 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

+12-4
Original file line numberDiff line numberDiff line change
@@ -52,19 +52,23 @@ func NewReconciler(cfg ReconcilerConfig) *Reconciler {
5252
}
5353
}
5454

55-
func (r *Reconciler) newObject(objectType client.Object) client.Object {
55+
func (r *Reconciler) newObject(objectType client.Object) (client.Object, error) {
5656
if r.cfg.OnlyMetadata {
5757
partialObj := &metav1.PartialObjectMetadata{}
5858
partialObj.SetGroupVersionKind(objectType.GetObjectKind().GroupVersionKind())
5959

60-
return partialObj
60+
return partialObj, nil
6161
}
6262

6363
// without Elem(), t will be a pointer to the type. For example, *v1.Gateway, not v1.Gateway
6464
t := reflect.TypeOf(objectType).Elem()
6565

6666
// We could've used objectType.DeepCopyObject() here, but it's a bit slower confirmed by benchmarks.
67-
return reflect.New(t).Interface().(client.Object)
67+
obj, ok := reflect.New(t).Interface().(client.Object)
68+
if !ok {
69+
return nil, fmt.Errorf("failed to assert the object type")
70+
}
71+
return obj, nil
6872
}
6973

7074
// Reconcile implements the reconcile.Reconciler Reconcile method.
@@ -82,7 +86,11 @@ func (r *Reconciler) Reconcile(ctx context.Context, req reconcile.Request) (reco
8286
}
8387
}
8488

85-
obj := r.newObject(r.cfg.ObjectType)
89+
obj, err := r.newObject(r.cfg.ObjectType)
90+
if err != nil {
91+
logger.Error(err, "Failed to create a new object")
92+
return reconcile.Result{}, err
93+
}
8694

8795
if err := r.cfg.Getter.Get(ctx, req.NamespacedName, obj); err != nil {
8896
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
@@ -120,8 +120,6 @@ func (u *Updater) writeStatuses(
120120
//
121121
// Note: this function is public because fake dependencies require us to test this function from the test package
122122
// to avoid import cycles.
123-
//
124-
//nolint:nilerr
125123
func NewRetryUpdateFunc(
126124
getter controller.Getter,
127125
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
@@ -62,7 +62,7 @@ import (
6262
)
6363

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

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

82-
// nolint:gocyclo
82+
//nolint:gocyclo
8383
func StartManager(cfg config.Config) error {
8484
nginxChecker := newNginxConfiguredOnStartChecker()
8585
mgr, err := createManager(cfg, nginxChecker)
@@ -529,7 +529,7 @@ func registerControllers(
529529
}
530530

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

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

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,

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
"github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/metrics"
99
)
1010

11-
// NginxRuntimeCollector implements runtime.Collector interface and prometheus.Collector interface
11+
// NginxRuntimeCollector implements runtime.Collector interface and prometheus.Collector interface.
1212
type NginxRuntimeCollector struct {
1313
// Metrics
1414
reloadsTotal prometheus.Counter
@@ -17,7 +17,7 @@ type NginxRuntimeCollector struct {
1717
reloadsDuration prometheus.Histogram
1818
}
1919

20-
// NewManagerMetricsCollector creates a new NginxRuntimeCollector
20+
// NewManagerMetricsCollector creates a new NginxRuntimeCollector.
2121
func NewManagerMetricsCollector(constLabels map[string]string) *NginxRuntimeCollector {
2222
nc := &NginxRuntimeCollector{
2323
reloadsTotal: prometheus.NewCounter(

0 commit comments

Comments
 (0)