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 all linter warnings #15684

Open
wants to merge 35 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
44db34c
add updated linter config
dprotaso Jan 11, 2025
4bd06eb
fix whitespace linting
dprotaso Jan 11, 2025
3844255
fix usestdlibvars linter
dprotaso Jan 11, 2025
cc2fd64
fix lint wastedassign
dprotaso Jan 11, 2025
8cc3257
address unparam linter - container concurrency wasn't being used when…
dprotaso Jan 11, 2025
e0cc35f
fix tenv linter
dprotaso Jan 11, 2025
3cb7a71
fix stylecheck linter
dprotaso Jan 11, 2025
65009c6
fix staticheck linter
dprotaso Jan 11, 2025
b0ce4af
fix perfsprint linter
dprotaso Jan 11, 2025
c716660
fix nosprintfhostport
dprotaso Jan 11, 2025
9afcee8
f perfsprint
dprotaso Jan 11, 2025
8d648ec
fix nolintlint - remove nolint directives that had no effect
dprotaso Jan 11, 2025
ca7f5e3
fix noctx linter
dprotaso Jan 11, 2025
153a53b
fix gomodguard linter - drop uber atomic package
dprotaso Jan 11, 2025
0d7e578
fix nilerr linter
dprotaso Jan 11, 2025
b26986f
fix mirror linter
dprotaso Jan 11, 2025
a22fa3b
fix loggercheck linter
dprotaso Jan 11, 2025
7cdf82a
fix govet linter
dprotaso Jan 11, 2025
74d8600
fix gosimple linter
dprotaso Jan 11, 2025
a06abbc
fix gosec linter
dprotaso Jan 12, 2025
a72a657
fix unconvert linter
dprotaso Jan 12, 2025
d2f37ed
fix perfsprint linter
dprotaso Jan 12, 2025
ff89cc0
fix errname linter
dprotaso Jan 12, 2025
3900cd3
fix errlint linter
dprotaso Jan 12, 2025
85df3e0
fix bodyclose linter
dprotaso Jan 12, 2025
129b481
fix canonicalheader linter
dprotaso Jan 12, 2025
73166ef
fix durationcheck linter
dprotaso Jan 12, 2025
f052fba
fix copyloopvar linter
dprotaso Jan 12, 2025
663dd2e
fix fatcontext linter
dprotaso Jan 12, 2025
c6b9012
fix gocritic-commentFormatting
dprotaso Jan 12, 2025
16d836d
fix gocritic linter
dprotaso Jan 13, 2025
18ea7bd
fix intrange linter
dprotaso Jan 13, 2025
f8e8ba7
fix prealloc linter
dprotaso Jan 13, 2025
b6a3c38
fix flakey kpa test
dprotaso Jan 13, 2025
86b4390
fix gofumpt linter
dprotaso Jan 13, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
255 changes: 200 additions & 55 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -1,74 +1,219 @@
run:
timeout: 10m

allow-parallel-runners: true
exclude-dirs:
- pkg/client
build-tags:
- e2e
- upgrade
- e2e
- hpa
- upgrade

output:
sort-results: true
sort-order:
- linter
- file
show-stats: true

skip-dirs:
- pkg/client

skip-files:
- ".pb.go$"
issues:
uniq-by-line: true
max-issues-per-linter: 0
max-same-issues: 0
exclude-rules:
- path: test # Excludes /test, *_test.go etc.
linters:
- gosec
- unparam
- noctx
- protogetter
- linters: ["gocritic"]
# Fixes are non-trivial do in a follow up
text: "ifElseChain"

linters-settings:
gocritic:
disabled-checks:
# we typically have this pattern during setup
- exitAfterDefer
# a lot cases we have are legit
- appendAssign
gomodguard:
blocked:
modules:
- github.com/ghodss/yaml:
recommendations:
- sigs.k8s.io/yaml
- go.uber.org/atomic:
recommendations:
- sync/atomic
- io/ioutil:
recommendations:
- os
- io
- github.com/hashicorp/go-multierror:
reason: "use errors.Join"
recommendations:
- errors
- go.uber.org/multierr:
reason: "use errors.Join"
recommendations:
- errors
revive:
rules:
# use unparam linter instead - defaults are better
- name: unused-parameter
disabled: true

linters:
disable:
- errcheck
enable:
# Check for pass []any as any in variadic func(...any).
- asasalint

# Only use ASCII chars in indentifiers
- asciicheck
- depguard

# Dangerous unicode characters
- bidichk

# Checks whether HTTP response body is closed successfully.
- bodyclose

# Canonicalheader checks whether net/http.Header uses canonical header.
- canonicalheader

# TODO - do a follow up PR
# # Containedctx is a linter that detects struct contained context.Context
# # field.
# - containedctx

# TODO - do a follow up PR
# # Check whether the function uses a non-inherited context.
# - contextcheck

# Copyloopvar is a linter detects places where loop variables are copied.
- copyloopvar

# Check declaration order of types, consts, vars and funcs.
- decorder

# Check for two durations multiplied together.
- durationcheck

# Checks that sentinel errors are prefixed with the Err- and error types
# are suffixed with the -Error.
- errname

# Errorlint is a linter for that can be used to find code that will cause
# problems with the error wrapping scheme introduced in Go 1.13.
- errorlint

# Detects nested contexts in loops.
- fatcontext

# Checks that go compiler directive comments (//go:) are valid.
- gocheckcompilerdirectives

# Provides diagnostics that check for bugs, performance and style issues.
# Extensible without recompilation through dynamic rules.
# Dynamic rules are written declaratively with AST patterns, filters,
# report message and optional suggestion.
- gocritic

# Gofmt checks whether code was gofmt-ed. By default this tool runs
# with -s option to check for code simplification.
- gofmt

# Gofumpt checks whether code was gofumpt-ed.
- gofumpt

# Check import statements are formatted according to the 'goimport'
# command. Reformat imports in autofix mode.
- goimports

# See config below
- gomodguard

# Inspects source code for security problems.
- gosec
- importas

# Linter that specializes in simplifying code.
- gosimple
- govet

# Intrange is a linter to find places where for loops could make use of
# an integer range.
- intrange

# Checks key value pairs for common logger libraries (kitlog,klog,logr,zap).
- loggercheck

# Finds slice declarations with non-zero initial length.
- makezero

# Reports wrong mirror patterns of bytes/strings usage
- mirror

# Finds commonly misspelled English words.
- misspell

# Finds the code that returns nil even if it checks that the error is not nil.
- nilerr

# Finds sending HTTP request without context.Context.
- noctx

# Reports ill-formed or insufficient nolint directives.
- nolintlint

# Checks for misuse of Sprintf to construct a host with port in a URL.
- nosprintfhostport

# Checks that fmt.Sprintf can be replaced with a faster alternative.
- perfsprint

# Finds slice declarations that could potentially be pre-allocated.
- prealloc

# Reports direct reads from proto message fields when getters should be used.
- protogetter

# Checks that package variables are not reassigned.
- reassign

# Fast, configurable, extensible, flexible, and beautiful linter for
# Go. Drop-in replacement of golint.
- revive

# Checks for mistakes with OpenTelemetry/Census spans.
- spancheck

# Stylecheck is a replacement for golint.
- stylecheck
- tparallel

# Tenv is analyzer that detects using os.Setenv instead of t.Setenv
# since Go1.17.
- tenv

# Linter checks if examples are testable (have an expected output).
- testableexamples

# Remove unnecessary type conversions.
- unconvert

# Reports unused function parameters and results in your code.
- unparam
disable:
- errcheck

linters-settings:
depguard:
rules:
main:
deny:
- pkg: sync/atomic
desc: "please use type-safe atomics from go.uber.org/atomic"
importas:
no-unaliased: true
alias:
- pkg: knative.dev/serving/pkg/apis/autoscaling/v1alpha1
alias: autoscalingv1alpha1
# A linter that detect the possibility to use variables/constants from the
# Go standard library.
- usestdlibvars

issues:
include:
# Disable excluding issues about comments from golint.
- EXC0002
# Finds wasted assignment statements.
- wastedassign

# Whitespace is a linter that checks for unnecessary newlines at the start
# and end of functions, if, for, etc.
- whitespace

exclude-rules:
- path: test # Excludes /test, *_test.go etc.
linters:
- gosec
- unparam

# Ignore "context.Context should be the first parameter of a function" errors in tests.
# See: https://github.com/golang/lint/issues/422
- path: test
text: "context.Context should be the first"
linters:
- revive

# Allow source and sink receivers in conversion code for clarity.
- path: _conversion\.go
text: "ST1016:"
linters:
- stylecheck
- path: _conversion\.go
text: "receiver name"
linters:
- revive

# This check has quite a few false positives where there isn't much value in the package comment.
- text: "ST1000: at least one file in a package should have a package comment"
linters:
- stylecheck
4 changes: 2 additions & 2 deletions cmd/activator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,11 +214,11 @@ func main() {
ah := activatorhandler.New(ctx, throttler, transport, networkConfig.EnableMeshPodAddressability, logger, tlsEnabled)
ah = handler.NewTimeoutHandler(ah, "activator request timeout", func(r *http.Request) (time.Duration, time.Duration, time.Duration) {
if rev := activatorhandler.RevisionFrom(r.Context()); rev != nil {
var responseStartTimeout = 0 * time.Second
responseStartTimeout := 0 * time.Second
if rev.Spec.ResponseStartTimeoutSeconds != nil {
responseStartTimeout = time.Duration(*rev.Spec.ResponseStartTimeoutSeconds) * time.Second
}
var idleTimeout = 0 * time.Second
idleTimeout := 0 * time.Second
if rev.Spec.IdleTimeoutSeconds != nil {
idleTimeout = time.Duration(*rev.Spec.IdleTimeoutSeconds) * time.Second
}
Expand Down
1 change: 0 additions & 1 deletion cmd/autoscaler/leaderelection.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ func setupSharedElector(ctx context.Context, controllers []*controller.Impl) (le
noopEnqueue := func(reconciler.Bucket, types.NamespacedName) {}

el, err := leaderelection.BuildElector(ctx, coalesce(reconcilers), queueName, noopEnqueue)

if err != nil {
return nil, err
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/autoscaler/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,8 @@ func main() {
}

func uniScalerFactoryFunc(podLister corev1listers.PodLister,
metricClient asmetrics.MetricClient) scaling.UniScalerFactory {
metricClient asmetrics.MetricClient,
) scaling.UniScalerFactory {
return func(decider *scaling.Decider) (scaling.UniScaler, error) {
configName := decider.Labels[serving.ConfigurationLabelKey]
if configName == "" {
Expand Down
2 changes: 1 addition & 1 deletion cmd/default-domain/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ func main() {
}
ipAddr, err := net.ResolveIPAddr("ip", address.Hostname)
if err != nil {
logger.Fatalw("Error resolving the IP address of %q", address.Hostname, zap.Error(err))
logger.Fatalw(fmt.Sprintf("Error resolving the IP address of %q", address.Hostname), zap.Error(err))
}
ip = ipAddr.String()
}
Expand Down
8 changes: 2 additions & 6 deletions cmd/schema-tweak/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ func main() {

processFile(file)
}

}

func processFile(file fs.DirEntry) {
Expand Down Expand Up @@ -81,7 +80,6 @@ func processFile(file fs.DirEntry) {
if err = os.WriteFile(filename, buf.Bytes(), file.Type().Perm()); err != nil {
log.Fatalln("failed to write CRD", err)
}

}

func applyOverrides(root *yaml.Node) {
Expand Down Expand Up @@ -149,7 +147,7 @@ func updateFeatureFlags(node *yaml.Node, features []flagField) {
}

func updateFeatureFlagProperty(root *yaml.Node, f flagField) {
desc := fmt.Sprintf("This is accessible behind a feature flag - %s", f.flag)
desc := "This is accessible behind a feature flag - " + f.flag

setString(root, "description", desc)

Expand Down Expand Up @@ -184,7 +182,6 @@ func updateFeatureFlagProperty(root *yaml.Node, f flagField) {
Value: "true",
},
)

}

func filterAllowedFields(node *yaml.Node, allowed sets.Set[string], features []flagField) {
Expand Down Expand Up @@ -216,8 +213,7 @@ func filterAllowedFields(node *yaml.Node, allowed sets.Set[string], features []f
func dropRequiredFields(node *yaml.Node, fields sets.Set[string]) {
dataType := dataType(node)

switch dataType {
case "array":
if dataType == "array" {
node = items(node)
}

Expand Down
11 changes: 5 additions & 6 deletions cmd/schema-tweak/overrides.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,8 @@ func revSpecOverrides(prefixPath string) []entry {
"drop",
),
}, {
path: "containers.securityContext.capabilities.add",
description: fmt.Sprintf("This is accessible behind a feature flag - %s",
config.FeatureContainerSpecAddCapabilities),
path: "containers.securityContext.capabilities.add",
description: "This is accessible behind a feature flag - " + config.FeatureContainerSpecAddCapabilities,
}, {
path: "containers.resources",
allowedFields: sets.New(
Expand Down Expand Up @@ -345,7 +344,7 @@ func revSpecOverrides(prefixPath string) []entry {

for _, probe := range probes {
entries = append(entries, entry{
path: fmt.Sprintf("containers.%s", probe),
path: "containers." + probe,
allowedFields: sets.New(
"initialDelaySeconds",
"timeoutSeconds",
Expand Down Expand Up @@ -406,11 +405,11 @@ func revSpecOverrides(prefixPath string) []entry {

func revisionSpecFields() []string {
var (
fields []string
revType = reflect.TypeOf(v1.RevisionSpec{})
fields = make([]string, 0, revType.NumField())
)

for i := 0; i < revType.NumField(); i++ {
for i := range revType.NumField() {
if revType.Field(i).Name == "PodSpec" {
continue
}
Expand Down
1 change: 0 additions & 1 deletion cmd/schema-tweak/yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,5 +150,4 @@ func deleteKeysExcluding(node *yaml.Node, keys ...string) {
i -= 2 // reset index
}
}

}
Loading
Loading