-
Notifications
You must be signed in to change notification settings - Fork 23
Add noreferences linter #163
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"` | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
|
|
||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. NIt, probably best to remove the blank lines in these code blocks
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.