Skip to content

linters: add forbiddenmarkers and nonullable linters #111

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 3 commits 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
184 changes: 184 additions & 0 deletions pkg/analysis/forbiddenmarkers/analyzer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
/*
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 forbiddenmarkers

import (
"fmt"
"go/ast"

"golang.org/x/tools/go/analysis"
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/helpers/inspector"
"sigs.k8s.io/kube-api-linter/pkg/analysis/helpers/markers"
"sigs.k8s.io/kube-api-linter/pkg/analysis/utils"
"sigs.k8s.io/kube-api-linter/pkg/config"
)

const name = "forbiddenmarkers"

type analyzer struct {
forbiddenMarkers []config.ForbiddenMarker
}

// ForbiddenMarkersOptions is a function that configures the

Check failure on line 37 in pkg/analysis/forbiddenmarkers/analyzer.go

View workflow job for this annotation

GitHub Actions / golangci-lint

exported: comment on exported type ForbiddenMarkersOption should be of the form "ForbiddenMarkersOption ..." (with optional leading article) (revive)
// forbiddenmarkers analysis.Analyzer
type ForbiddenMarkersOption func(a *analysis.Analyzer)

// WithName sets the name of the forbiddenmarkers analysis.Analyzer

Check failure on line 41 in pkg/analysis/forbiddenmarkers/analyzer.go

View workflow job for this annotation

GitHub Actions / golangci-lint

Comment should end in a period (godot)
func WithName(name string) ForbiddenMarkersOption {
return func(a *analysis.Analyzer) {
a.Name = name
}
}

// WithDoc sets the doc string of the forbiddenmarkers analysis.Analyzer

Check failure on line 48 in pkg/analysis/forbiddenmarkers/analyzer.go

View workflow job for this annotation

GitHub Actions / golangci-lint

Comment should end in a period (godot)
func WithDoc(doc string) ForbiddenMarkersOption {
return func(a *analysis.Analyzer) {
a.Doc = doc
}
}

// NewAnalyzer creates a new analysis.Analyzer for the forbiddenmarkers
// linter based on the provided config.ForbiddenMarkersConfig.
func NewAnalyzer(cfg config.ForbiddenMarkersConfig, opts ...ForbiddenMarkersOption) *analysis.Analyzer {
a := &analyzer{
forbiddenMarkers: cfg.Markers,
}

analyzer := &analysis.Analyzer{
Name: name,
Doc: "Check that no forbidden markers are present on types and fields.",
Run: a.run,
Requires: []*analysis.Analyzer{inspector.Analyzer},
}

for _, opt := range opts {
opt(analyzer)
}

return analyzer
}

func (a *analyzer) run(pass *analysis.Pass) (any, error) {
inspect, ok := pass.ResultOf[inspector.Analyzer].(inspector.Inspector)
if !ok {
return nil, kalerrors.ErrCouldNotGetInspector
}

inspect.InspectFields(func(field *ast.Field, stack []ast.Node, _ extractjsontags.FieldTagInfo, markersAccess markers.Markers) {
checkField(pass, field, markersAccess, a.forbiddenMarkers)
})

inspect.InspectTypeSpec(func(typeSpec *ast.TypeSpec, markersAccess markers.Markers) {
checkType(pass, typeSpec, markersAccess, a.forbiddenMarkers)
})

return nil, nil //nolint:nilnil
}

func checkField(pass *analysis.Pass, field *ast.Field, markersAccess markers.Markers, forbiddenMarkers []config.ForbiddenMarker) {
if field == nil || len(field.Names) == 0 {
return
}

markers := utils.TypeAwareMarkerCollectionForField(pass, markersAccess, field)
check(markers, forbiddenMarkers, reportField(pass, field))
}

func checkType(pass *analysis.Pass, typeSpec *ast.TypeSpec, markersAccess markers.Markers, forbiddenMarkers []config.ForbiddenMarker) {
if typeSpec == nil {
return
}

markers := markersAccess.TypeMarkers(typeSpec)
check(markers, forbiddenMarkers, reportType(pass, typeSpec))
}

func check(markerSet markers.MarkerSet, forbiddenMarkers []config.ForbiddenMarker, reportFunc func(marker markers.Marker)) {
for _, marker := range forbiddenMarkers {
marks := markerSet.Get(marker.Identifier)
for _, mark := range marks {
if markerMatchesAttributeRules(mark, marker.Attributes...) {
reportFunc(mark)
}
}
}
}

// TODO: this should probably return some representation of the marker that is failing the
// attribute rules so that it can be returned to users helpfully.
func markerMatchesAttributeRules(marker markers.Marker, attrRules ...config.ForbiddenMarkerAttribute) bool {
matchesAll := true
for _, attrRule := range attrRules {

Check failure on line 126 in pkg/analysis/forbiddenmarkers/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 val, ok := marker.Expressions[attrRule.Attribute]; ok {
// if no values are specified, that means the existence match is enough
// and we can continue to the next rule
if len(attrRule.Values) == 0 {
continue
}

// if the value doesn't match one of the forbidden ones, this marker is not forbidden
matchesOneValue := false
for _, value := range attrRule.Values {

Check failure on line 136 in pkg/analysis/forbiddenmarkers/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 val == value {
matchesOneValue = true
break
}
}

if !matchesOneValue {
matchesAll = false
break
}
}
// if the marker doesn't contain the attribute for a specified rule it fails the AND
// operation.
matchesAll = false
break

Check failure on line 151 in pkg/analysis/forbiddenmarkers/analyzer.go

View workflow job for this annotation

GitHub Actions / golangci-lint

break with no blank line before (nlreturn)
}

return matchesAll
}

func reportField(pass *analysis.Pass, field *ast.Field) func(marker markers.Marker) {
return func(marker markers.Marker) {
pass.Report(analysis.Diagnostic{
Pos: field.Pos(),
Message: fmt.Sprintf("field %s has forbidden marker %q", field.Names[0].Name, marker.Identifier),
SuggestedFixes: []analysis.SuggestedFix{
{
Message: fmt.Sprintf("remove forbidden marker %q", marker.Identifier),
TextEdits: []analysis.TextEdit{
{
Pos: marker.Pos,
End: marker.End + 1,
},
},
},
},
})
}
}

func reportType(pass *analysis.Pass, typeSpec *ast.TypeSpec) func(marker markers.Marker) {
return func(marker markers.Marker) {
pass.Report(analysis.Diagnostic{
Pos: typeSpec.Pos(),
Message: fmt.Sprintf("type %s has forbidden marker %q", typeSpec.Name, marker.Identifier),
})
}
}
88 changes: 88 additions & 0 deletions pkg/analysis/forbiddenmarkers/analyzer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
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 forbiddenmarkers_test

import (
"testing"

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

func TestWithConfiguration(t *testing.T) {
testdata := analysistest.TestData()
analysistest.RunWithSuggestedFixes(t, testdata, forbiddenmarkers.NewAnalyzer(config.ForbiddenMarkersConfig{
Markers: []config.ForbiddenMarker{
{
Identifier: "custom:forbidden",
},
{
Identifier: "custom:AttrNoValues",
Attributes: []config.ForbiddenMarkerAttribute{
{
Attribute: "fruit",
},
},
},
{
Identifier: "custom:AttrValues",
Attributes: []config.ForbiddenMarkerAttribute{
{
Attribute: "fruit",
Values: []string{
"apple",
"orange",
"banana",
},
},
},
},
{
Identifier: "custom:AttrsNoValues",
Attributes: []config.ForbiddenMarkerAttribute{
{
Attribute: "fruit",
},
{
Attribute: "color",
},
},
},
{
Identifier: "custom:AttrsValues",
Attributes: []config.ForbiddenMarkerAttribute{
{
Attribute: "fruit",
Values: []string{
"apple",
"orange",
"banana",
},
},
{
Attribute: "color",
Values: []string{
"red",
"blue",
"green",
},
},
},
},
},
}), "a/...")
}
35 changes: 35 additions & 0 deletions pkg/analysis/forbiddenmarkers/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
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 `forbiddenmarkers` linter ensures that types and fields do not contain any markers
* that are forbidden.
*
* By default, `forbiddenmarkers` is not enabled.
*
* It can be configured with a list of marker identifiers that are forbidden
* ```yaml
* lintersConfig:
* forbiddenMarkers:
* markers:
* - some:forbidden:marker
* - anotherforbidden
* ```
*
* Fixes are suggested to remove all markers that are forbidden.
*
*/
package forbiddenmarkers
45 changes: 45 additions & 0 deletions pkg/analysis/forbiddenmarkers/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 forbiddenmarkers

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(cfg config.LintersConfig) (*analysis.Analyzer, error) {
return NewAnalyzer(cfg.ForbiddenMarkers), nil
}

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

// +custom:forbidden
type ForbiddenMarkerType string // want `type ForbiddenMarkerType has forbidden marker "custom:forbidden"`

// +custom:AttrNoValues:fruit=apple
type ForbiddenMarkerWithAttrType string // want `type ForbiddenMarkerWithAttrType has forbidden marker "forbidden:AttrNoValues"`

// +allowed
type AllowedMarkerType string

// +custom:AttrNoValues:color=blue
type AllowedMarkerWithAttrType string

type Test struct {
// +custom:forbidden
ForbiddenMarkerField string `json:"forbiddenMarkerField"`// want `field ForbiddenMarkerField has forbidden marker "custom:forbidden"`

ForbiddenMarkerFieldTypeAlias ForbiddenMarkerType `json:"forbiddenMarkerFieldTypeAlias"` // want `field ForbiddenMarkerFieldTypeAlias has forbidden marker "forbidden"`

// +allowed
AllowedMarkerField string `json:"allowedMarkerField"`

AllowedMarkerFieldTypeAlias AllowedMarkerType `json:"AllowedMarkerFieldTypeAlias"`
}
Loading
Loading