Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
39 changes: 39 additions & 0 deletions docs/linters.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
- [Notimestamp](#notimestamp) - Prevents usage of 'TimeStamp' fields
- [OptionalFields](#optionalfields) - Validates optional field conventions
- [OptionalOrRequired](#optionalorrequired) - Ensures fields are explicitly marked as optional or required
- [NoReferences](#noreferences) - Ensures field names use Ref/Refs instead of Reference/References
- [PreferredMarkers](#preferredmarkers) - Ensures preferred markers are used instead of equivalent markers
- [RequiredFields](#requiredfields) - Validates required field conventions
- [SSATags](#ssatags) - Ensures proper Server-Side Apply (SSA) tags on array fields
Expand Down Expand Up @@ -747,6 +748,44 @@ If you prefer not to suggest fixes for pointers in required fields, you can chan
If you prefer not to suggest fixes for `omitempty` in required fields, you can change the `omitempty.policy` to `Warn` or `Ignore`.
If you prefer not to suggest fixes for `omitzero` in required fields, you can change the `omitzero.policy` to `Warn` and also not to consider `omitzero` policy at all, it can be set to `Forbid`.

## NoReferences

The `noreferences` linter ensures that field names use 'Ref'/'Refs' instead of 'Reference'/'References'.

By default, `noreferences` is enabled and operates in standard mode, allowing 'Ref'/'Refs' but prohibiting 'Reference'/'References' in field names.

### Configuration

```yaml
lintersConfig:
noreferences:
policy: PreferAbbreviatedReference | NoReferences # Defaults to `PreferAbbreviatedReference`.
```

**Default behavior (policy: PreferAbbreviatedReference):**
- Reports errors for fields containing 'Reference' or 'References' and replaces with 'Ref' or 'Refs'
- **Allows** fields containing 'Ref' or 'Refs' without reporting errors

**Strict mode (policy: NoReferences):**
- **Warns** about any reference-related words ('Ref', 'Refs', 'Reference', or 'References') in field names
- Does not provide automatic fixes - serves as an informational warning
- In this strict mode, the goal is to inform developers about reference-related words in field names

### Fixes

The `noreferences` linter can automatically fix field names in **PreferAbbreviatedReference mode**:

**PreferAbbreviatedReference mode:**
- Replaces 'Reference' with 'Ref' and 'References' with 'Refs' anywhere in field names
- Case insensitive matching
- Examples:
- `NodeReference` → `NodeRef`
- `ReferenceNode` → `RefNode`
- `NodeReferences` → `NodeRefs`

**Note:**
- The `NoReferences` mode only reports warnings without providing fixes, allowing developers to choose appropriate field names manually.

## SSATags

The `ssatags` linter ensures that array fields in Kubernetes API objects have the appropriate
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.24.0
require (
github.com/golangci/golangci-lint/v2 v2.5.0
github.com/golangci/plugin-module-register v0.1.2
github.com/google/go-cmp v0.7.0
github.com/onsi/ginkgo/v2 v2.23.4
github.com/onsi/gomega v1.38.0
golang.org/x/tools v0.37.0
Expand Down Expand Up @@ -100,7 +101,6 @@ require (
github.com/golangci/revgrep v0.8.0 // indirect
github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e // indirect
github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/pprof v0.0.0-20250607225305-033d6d78b36a // indirect
github.com/gordonklaus/ineffassign v0.2.0 // indirect
github.com/gostaticanalysis/analysisutil v0.7.1 // indirect
Expand Down
109 changes: 109 additions & 0 deletions pkg/analysis/noreferences/analyzer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
Copyright 2025 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package noreferences

import (
"errors"
"fmt"

"golang.org/x/tools/go/analysis"
"k8s.io/apimachinery/pkg/util/validation/field"
"sigs.k8s.io/kube-api-linter/pkg/analysis/initializer"
"sigs.k8s.io/kube-api-linter/pkg/analysis/namingconventions"
)

const (
name = "noreferences"
doc = "Enforces that fields use Ref/Refs and not Reference/References"
)

var (
errUnexpectedInitializerType = errors.New("expected namingconventions.Initializer() to be of type initializer.ConfigurableAnalyzerInitializer, but was not")
errInvalidPolicy = errors.New("invalid policy")
)

// newAnalyzer creates a new analyzer for the noreferences linter that is a wrapper around the namingconventions linter.
func newAnalyzer(cfg *Config) *analysis.Analyzer {
if cfg == nil {
cfg = &Config{}
}

// Default to PreferAbbreviatedReference if no policy is specified
policy := cfg.Policy
if policy == "" {
policy = PolicyPreferAbbreviatedReference
}

// Build the namingconventions config based on the policy
ncConfig := &namingconventions.Config{
Conventions: buildConventions(policy),
}

// Get the configurable initializer for namingconventions
configInit, ok := namingconventions.Initializer().(initializer.ConfigurableAnalyzerInitializer)
if !ok {
panic(fmt.Errorf("getting initializer: %w", errUnexpectedInitializerType))
}

// Validate generated namingconventions configuration
errs := configInit.ValidateConfig(ncConfig, field.NewPath("noreferences"))
if err := errs.ToAggregate(); err != nil {
panic(fmt.Errorf("noreferences linter has an invalid namingconventions configuration: %w", err))
}

// Initialize the wrapped analyzer
analyzer, err := configInit.Init(ncConfig)
if err != nil {
panic(fmt.Errorf("noreferences linter encountered an error initializing wrapped namingconventions analyzer: %w", err))
}

analyzer.Name = name
analyzer.Doc = doc

return analyzer
}

// buildConventions creates the naming conventions based on the policy.
func buildConventions(policy Policy) []namingconventions.Convention {
switch policy {
case PolicyPreferAbbreviatedReference:
// Replace "Reference" or "References" with "Ref" or "Refs" anywhere in field name
return []namingconventions.Convention{
{
Name: "reference-to-ref",
ViolationMatcher: "^[Rr]eference|Reference(s?)$",
Operation: namingconventions.OperationReplacement,
Replacement: "Ref$1",
Message: "field names should use 'Ref' instead of 'Reference'",
},
}

case PolicyNoReferences:
// Warn about reference words anywhere in field name without providing fixes
return []namingconventions.Convention{
{
Name: "no-references",
ViolationMatcher: "^[Rr]ef(erence)?(s?)([A-Z])|Ref(erence)?(s?)$",
Operation: namingconventions.OperationInform,
Message: "field names should not contain reference-related words",
},
}

default:
// Should not happen due to validation
panic(fmt.Errorf("%w: %s", errInvalidPolicy, policy))
}
}
69 changes: 69 additions & 0 deletions pkg/analysis/noreferences/analyzer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
Copyright 2025 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package noreferences_test

import (
"testing"

"golang.org/x/tools/go/analysis/analysistest"
"sigs.k8s.io/kube-api-linter/pkg/analysis/noreferences"
)

func TestPreferAbbreviatedReference(t *testing.T) {
testdata := analysistest.TestData()

cfg := &noreferences.Config{
Policy: noreferences.PolicyPreferAbbreviatedReference,
}

analyzer, err := noreferences.Initializer().Init(cfg)
if err != nil {
t.Fatalf("initializing noreferences linter: %v", err)
}

analysistest.RunWithSuggestedFixes(t, testdata, analyzer, "a")
}

func TestEmptyConfig(t *testing.T) {
testdata := analysistest.TestData()

// Test with empty config - should default to PreferAbbreviatedReference behavior
cfg := &noreferences.Config{}

analyzer, err := noreferences.Initializer().Init(cfg)
if err != nil {
t.Fatalf("initializing noreferences linter: %v", err)
}

// With default config (empty Policy), it should default to PreferAbbreviatedReference behavior
// So we test with folder 'a' which has the same expectations
analysistest.RunWithSuggestedFixes(t, testdata, analyzer, "a")
}

func TestNoReferences(t *testing.T) {
testdata := analysistest.TestData()

cfg := &noreferences.Config{
Policy: noreferences.PolicyNoReferences,
}

analyzer, err := noreferences.Initializer().Init(cfg)
if err != nil {
t.Fatalf("initializing noreferences linter: %v", err)
}

analysistest.RunWithSuggestedFixes(t, testdata, analyzer, "b")
}
36 changes: 36 additions & 0 deletions pkg/analysis/noreferences/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
Copyright 2025 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package noreferences

// Policy defines the policy for handling references in field names.
type Policy string

const (
// PolicyPreferAbbreviatedReference allows abbreviated forms (Ref/Refs) in field names.
// It suggests replacing Reference/References with Ref/Refs.
PolicyPreferAbbreviatedReference Policy = "PreferAbbreviatedReference"
// PolicyNoReferences forbids any reference-related words in field names.
// It suggests removing Ref/Refs/Reference/References entirely.
PolicyNoReferences Policy = "NoReferences"
)

// Config represents the configuration for the noreferences linter.
type Config struct {
// policy controls how reference-related words are handled in field names.
// When set to PreferAbbreviatedReference (default), Reference/References are replaced with Ref/Refs.
// When set to NoReferences, all reference-related words are suggested to be removed.
Policy Policy `json:"policy,omitempty"`
}
39 changes: 39 additions & 0 deletions pkg/analysis/noreferences/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
Copyright 2025 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*
The `noreferences` linter ensures that field names use 'Ref'/'Refs' instead of 'Reference'/'References'.
By default, `noreferences` is enabled and enforces this naming convention.
The linter checks that 'Reference' is present at the beginning or end of the field name, and replaces it with 'Ref'.
Similarly, 'References' anywhere in field names is replaced with 'Refs'.

Example configuration:
Default behavior (allow Ref/Refs in field names):

lintersConfig:
noreferences:
policy: PreferAbbreviatedReference

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIt, probably best to remove the blank lines in these code blocks

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not yet actioned

Strict mode (forbid Ref/Refs in field names):

lintersConfig:
noreferences:
policy: NoReferences

When `policy` is set to `PreferAbbreviatedReference` (the default), fields containing 'Ref' or 'Refs' are allowed.
The policy can be set to `NoReferences` to also report errors for 'Ref' or 'Refs' in field names.
*/
package noreferences
64 changes: 64 additions & 0 deletions pkg/analysis/noreferences/initializer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
Copyright 2025 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package noreferences

import (
"golang.org/x/tools/go/analysis"
"k8s.io/apimachinery/pkg/util/validation/field"
"sigs.k8s.io/kube-api-linter/pkg/analysis/initializer"
"sigs.k8s.io/kube-api-linter/pkg/analysis/registry"
)

func init() {
registry.DefaultRegistry().RegisterLinter(Initializer())
}

// Initializer returns the AnalyzerInitializer for this
// Analyzer so that it can be added to the registry.
func Initializer() initializer.AnalyzerInitializer {
return initializer.NewConfigurableInitializer(
name,
initAnalyzer,
true,
validateConfig,
)
}

func initAnalyzer(cfg *Config) (*analysis.Analyzer, error) {
return newAnalyzer(cfg), nil
}

// validateConfig validates the configuration for the noreferences linter.
func validateConfig(cfg *Config, fldPath *field.Path) field.ErrorList {
if cfg == nil {
return nil // nil config is valid, will use defaults
}

var errs field.ErrorList

// Validate Policy enum if provided
switch cfg.Policy {
case PolicyPreferAbbreviatedReference, PolicyNoReferences, "":
default:
errs = append(errs, field.NotSupported(
fldPath.Child("policy"),
cfg.Policy,
[]string{string(PolicyPreferAbbreviatedReference), string(PolicyNoReferences)},
))
}

return errs
}
Loading