Skip to content

poc: generic naming convention linter #106

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
156 changes: 156 additions & 0 deletions pkg/analysis/fieldnaming/analyzer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
/*
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 fieldnaming

import (
"fmt"
"go/ast"
"go/token"
"regexp"

"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
kalerrors "sigs.k8s.io/kube-api-linter/pkg/analysis/errors"
"sigs.k8s.io/kube-api-linter/pkg/analysis/helpers/extractjsontags"
"sigs.k8s.io/kube-api-linter/pkg/analysis/utils"
)

const name = "fieldnaming"

// Analyzer is the analyzer for the nophase package.
// It checks that no struct fields named 'phase', or that contain phase as a
// substring are present.
var Analyzer = &analysis.Analyzer{
Name: name,
Doc: "phase fields are deprecated and conditions should be preferred, avoid phase like enum fields",
Run: run,
Requires: []*analysis.Analyzer{inspect.Analyzer, extractjsontags.Analyzer},
}

var defaults = []NamingConvention{

Check failure on line 44 in pkg/analysis/fieldnaming/analyzer.go

View workflow job for this annotation

GitHub Actions / golangci-lint

defaults is a global variable (gochecknoglobals)
{
Matcher: *regexp.MustCompile("(?i)phase"),
Operation: "Drop",
Message: "phase fields are deprecated and discouraged. conditions should be used instead.",
},
{
Matcher: *regexp.MustCompile("(?i)timestamp"),
Operation: "Replace",
Message: "prefer use of the term 'time' over 'timestamp'",
// replacement of `Time` follows CamelCase principles for field names and JSON tags
// TODO: Handle case where it is _not_ the second word in CamelCase for json tag
Replacement: "Time",
},
{
Matcher: *regexp.MustCompile("(?i)reference"),
Operation: "Replace",
Message: "prefer use of the term 'ref' over 'reference'",
// replacement of `Ref` follows CamelCase principles for field names and JSON tags
// TODO: Handle case where it is _not_ the second word in CamelCase for json tag
Replacement: "Ref",
},
}

type NamingConvention struct {

Check failure on line 68 in pkg/analysis/fieldnaming/analyzer.go

View workflow job for this annotation

GitHub Actions / golangci-lint

exported: exported type NamingConvention should have comment or be unexported (revive)
// Matcher is a regular expression
// used to identify field names
// where this convention applies
Matcher regexp.Regexp

// Replacement is an optional
// string value used to replace the matched content
// in a suggested fix.
// Only used when Operation is Replace.
Replacement string

// Operation is the type of operation that should take place for this
// naming convention.
// One of Drop, Replace.
Operation string

// Message is the message that should be included in the
// linter report when this naming convention is applied.
Message string
}
Comment on lines +44 to +88
Copy link
Contributor Author

Choose a reason for hiding this comment

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

If we were to continue with this approach, the thinking is that we would implement a configuration layer for this linter that exposes this NamingConvention type to allow the development of custom naming conventions.

We could also add a configuration option to include/exclude the defaults we have put in place based on the Kubernetes API conventions doc.


func run(pass *analysis.Pass) (any, error) {

Check failure on line 90 in pkg/analysis/fieldnaming/analyzer.go

View workflow job for this annotation

GitHub Actions / golangci-lint

calculated cyclomatic complexity for function run is 11, max is 10 (cyclop)
inspect, ok := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
if !ok {
return nil, kalerrors.ErrCouldNotGetInspector
}

jsonTags, ok := pass.ResultOf[extractjsontags.Analyzer].(extractjsontags.StructFieldTags)
if !ok {
return nil, kalerrors.ErrCouldNotGetJSONTags
}

// Filter to fields so that we can iterate over fields in a struct.
nodeFilter := []ast.Node{
(*ast.Field)(nil),
}

// Preorder visits all the nodes of the AST in depth-first order. It calls
// f(n) for each node n before it visits n's children.
//
// We use the filter defined above, ensuring we only look at struct fields.
inspect.Preorder(nodeFilter, func(n ast.Node) {
field, ok := n.(*ast.Field)
if !ok {
return
}

if field == nil || len(field.Names) == 0 {
return
}

fieldName := utils.FieldName(field)
for _, convention := range defaults {

Check failure on line 121 in pkg/analysis/fieldnaming/analyzer.go

View workflow job for this annotation

GitHub Actions / golangci-lint

ranges should only be cuddled with assignments used in the iteration (wsl)
if convention.Operation == "Drop" {
if convention.Matcher.MatchString(fieldName) {
pass.Reportf(field.Pos(), "field %s: %s", fieldName, convention.Message)
}
}

if convention.Operation == "Replace" {
replacement := convention.Matcher.ReplaceAllString(fieldName, convention.Replacement)
if replacement != fieldName {
pass.Report(analysis.Diagnostic{
Pos: field.Pos(),
Message: fmt.Sprintf("field %s: %s", fieldName, convention.Message),
SuggestedFixes: []analysis.SuggestedFix{
{
Message: fmt.Sprintf("replace with %s", convention.Replacement),
TextEdits: []analysis.TextEdit{
{
Pos: field.Pos(),
NewText: []byte(replacement),
End: field.Pos()+token.Pos(len(fieldName)),

Check failure on line 141 in pkg/analysis/fieldnaming/analyzer.go

View workflow job for this annotation

GitHub Actions / golangci-lint

File is not properly formatted (gofmt)
},
},
},
},
})
}
}
}

// Then check if the json serialization of the field contains 'phase'
_ = jsonTags.FieldTags(field)
})

return nil, nil //nolint:nilnil
}
28 changes: 28 additions & 0 deletions pkg/analysis/fieldnaming/analyzer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
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 fieldnaming_test

import (
"testing"

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

func Test(t *testing.T) {
testdata := analysistest.TestData()
analysistest.RunWithSuggestedFixes(t, testdata, fieldnaming.Analyzer, "a")
}
1 change: 1 addition & 0 deletions pkg/analysis/fieldnaming/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package fieldnaming

Check failure on line 1 in pkg/analysis/fieldnaming/doc.go

View workflow job for this annotation

GitHub Actions / golangci-lint

Missed header for check (goheader)
45 changes: 45 additions & 0 deletions pkg/analysis/fieldnaming/initializer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
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 fieldnaming

import (
"golang.org/x/tools/go/analysis"
"sigs.k8s.io/kube-api-linter/pkg/config"
)

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

// intializer implements the AnalyzerInitializer interface.
type initializer struct{}

// Name returns the name of the Analyzer.
func (initializer) Name() string {
return name
}

// Init returns the intialized Analyzer.
func (initializer) Init(_ config.LintersConfig) (*analysis.Analyzer, error) {
return Analyzer, nil
}

// Default determines whether this Analyzer is on by default, or not.
func (initializer) Default() bool {
return true
}
52 changes: 52 additions & 0 deletions pkg/analysis/fieldnaming/testdata/src/a/a.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package a

import "time"

type NoPhaseTestStruct struct {
// +optional
Phase *string `json:"phase,omitempty"` // want "field Phase: phase fields are deprecated and discouraged. conditions should be used instead."
}

// DoNothing is used to check that the analyser doesn't report on methods.
func (NoPhaseTestStruct) DoNothing() {}

type NoSubPhaseTestStruct struct {
// +optional
FooPhase *string `json:"fooPhase,omitempty"` // want "field FooPhase: phase fields are deprecated and discouraged. conditions should be used instead."
}

type SerializedPhaseTeststruct struct {
// +optional
FooField *string `json:"fooPhase,omitempty"`
}

type NoTimeStampTestStruct struct {
// +optional
TimeStamp *time.Time `json:"timeStamp,omitempty"` // want "field TimeStamp: prefer use of the term 'time' over 'timestamp'"
}

// DoNothing is used to check that the analyser doesn't report on methods.
func (NoTimeStampTestStruct) DoNothing() {}

type NoSubTimeStampTestStruct struct {
// +optional
FooTimeStamp *time.Time `json:"fooTimeStamp,omitempty"` // want "field FooTimeStamp: prefer use of the term 'time' over 'timestamp'"
}

type SerializedTimeStampTestStruct struct {
// +optional
FooTime *time.Time `json:"fooTime,omitempty"`
}

type NoReferenceTestStruct struct {
// +optional
Reference *string `json:"reference,omitempty"` // want "field Reference: prefer use of the term 'ref' over 'reference'"
}

// DoNothing is used to check that the analyser doesn't report on methods.
func (NoReferenceTestStruct) DoNothing() {}

type NoReferenceSuffixTestStruct struct {
// +optional
FooReference *string `json:"fooReference,omitempty"` // want "field FooReference: prefer use of the term 'ref' over 'reference'"
}
52 changes: 52 additions & 0 deletions pkg/analysis/fieldnaming/testdata/src/a/a.go.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package a

import "time"

type NoPhaseTestStruct struct {
// +optional
Phase *string `json:"phase,omitempty"` // want "field Phase: phase fields are deprecated and discouraged. conditions should be used instead."
}

// DoNothing is used to check that the analyser doesn't report on methods.
func (NoPhaseTestStruct) DoNothing() {}

type NoSubPhaseTestStruct struct {
// +optional
FooPhase *string `json:"fooPhase,omitempty"` // want "field FooPhase: phase fields are deprecated and discouraged. conditions should be used instead."
}

type SerializedPhaseTeststruct struct {
// +optional
FooField *string `json:"fooPhase,omitempty"`
}

type NoTimeStampTestStruct struct {
// +optional
Time *time.Time `json:"Time,omitempty"` // want "field TimeStamp: prefer use of the term 'time' over 'timestamp'"
}

// DoNothing is used to check that the analyser doesn't report on methods.
func (NoTimeStampTestStruct) DoNothing() {}

type NoSubTimeStampTestStruct struct {
// +optional
FooTime *time.Time `json:"fooTime,omitempty"` // want "field FooTimeStamp: prefer use of the term 'time' over 'timestamp'"
}

type SerializedTimeStampTestStruct struct {
// +optional
FooTime *time.Time `json:"fooTime,omitempty"`
}

type NoReferenceTestStruct struct {
// +optional
Ref *string `json:"Reference,omitempty"` // want "field Reference: prefer use of the term 'ref' over 'reference'"
}

// DoNothing is used to check that the analyser doesn't report on methods.
func (NoReferenceTestStruct) DoNothing() {}

type NoReferenceSuffixTestStruct struct {
// +optional
FooRef *string `json:"fooRef,omitempty"` // want "field FooReference: prefer use of the term 'ref' over 'reference'"
}
Loading