|
| 1 | +/* |
| 2 | +Copyright 2025 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | +package statusoptional |
| 17 | + |
| 18 | +import ( |
| 19 | + "fmt" |
| 20 | + "go/ast" |
| 21 | + |
| 22 | + "golang.org/x/tools/go/analysis" |
| 23 | + |
| 24 | + kalerrors "sigs.k8s.io/kube-api-linter/pkg/analysis/errors" |
| 25 | + "sigs.k8s.io/kube-api-linter/pkg/analysis/helpers/extractjsontags" |
| 26 | + "sigs.k8s.io/kube-api-linter/pkg/analysis/helpers/inspector" |
| 27 | + "sigs.k8s.io/kube-api-linter/pkg/analysis/helpers/markers" |
| 28 | +) |
| 29 | + |
| 30 | +const ( |
| 31 | + name = "statusoptional" |
| 32 | + |
| 33 | + statusJSONTag = "status" |
| 34 | + |
| 35 | + // OptionalMarker is the marker that indicates that a field is optional. |
| 36 | + OptionalMarker = "optional" |
| 37 | + |
| 38 | + // KubebuilderOptionalMarker is the marker that indicates that a field is optional in kubebuilder. |
| 39 | + KubebuilderOptionalMarker = "kubebuilder:validation:Optional" |
| 40 | + |
| 41 | + // RequiredMarker is the marker that indicates that a field is required. |
| 42 | + RequiredMarker = "required" |
| 43 | + |
| 44 | + // KubebuilderRequiredMarker is the marker that indicates that a field is required in kubebuilder. |
| 45 | + KubebuilderRequiredMarker = "kubebuilder:validation:Required" |
| 46 | +) |
| 47 | + |
| 48 | +func init() { |
| 49 | + markers.DefaultRegistry().Register( |
| 50 | + OptionalMarker, |
| 51 | + KubebuilderOptionalMarker, |
| 52 | + RequiredMarker, |
| 53 | + KubebuilderRequiredMarker, |
| 54 | + ) |
| 55 | +} |
| 56 | + |
| 57 | +type analyzer struct { |
| 58 | + preferredOptionalMarker string |
| 59 | +} |
| 60 | + |
| 61 | +// newAnalyzer creates a new analyzer. |
| 62 | +func newAnalyzer(preferredOptionalMarker string) *analysis.Analyzer { |
| 63 | + if preferredOptionalMarker == "" { |
| 64 | + preferredOptionalMarker = OptionalMarker |
| 65 | + } |
| 66 | + |
| 67 | + a := &analyzer{ |
| 68 | + preferredOptionalMarker: preferredOptionalMarker, |
| 69 | + } |
| 70 | + |
| 71 | + return &analysis.Analyzer{ |
| 72 | + Name: name, |
| 73 | + Doc: "Checks that all first-level children fields within status struct are marked as optional", |
| 74 | + Run: a.run, |
| 75 | + Requires: []*analysis.Analyzer{inspector.Analyzer, extractjsontags.Analyzer}, |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +func (a *analyzer) run(pass *analysis.Pass) (any, error) { |
| 80 | + inspect, ok := pass.ResultOf[inspector.Analyzer].(inspector.Inspector) |
| 81 | + if !ok { |
| 82 | + return nil, kalerrors.ErrCouldNotGetInspector |
| 83 | + } |
| 84 | + |
| 85 | + jsonTags, ok := pass.ResultOf[extractjsontags.Analyzer].(extractjsontags.StructFieldTags) |
| 86 | + if !ok { |
| 87 | + return nil, kalerrors.ErrCouldNotGetJSONTags |
| 88 | + } |
| 89 | + |
| 90 | + inspect.InspectFields(func(field *ast.Field, stack []ast.Node, jsonTagInfo extractjsontags.FieldTagInfo, markersAccess markers.Markers) { |
| 91 | + if jsonTagInfo.Name != statusJSONTag { |
| 92 | + return |
| 93 | + } |
| 94 | + |
| 95 | + statusStructType := getStructFromField(field) |
| 96 | + if statusStructType == nil { |
| 97 | + return |
| 98 | + } |
| 99 | + |
| 100 | + a.checkStatusStruct(pass, statusStructType, markersAccess, jsonTags) |
| 101 | + }) |
| 102 | + |
| 103 | + return nil, nil //nolint:nilnil |
| 104 | +} |
| 105 | + |
| 106 | +func (a *analyzer) checkStatusStruct(pass *analysis.Pass, statusType *ast.StructType, markersAccess markers.Markers, jsonTags extractjsontags.StructFieldTags) { |
| 107 | + if statusType.Fields == nil || statusType.Fields.List == nil { |
| 108 | + return |
| 109 | + } |
| 110 | + |
| 111 | + // Check each child field of the status struct |
| 112 | + for _, childField := range statusType.Fields.List { |
| 113 | + fieldName := a.getFieldName(childField) |
| 114 | + if fieldName == "" { |
| 115 | + continue |
| 116 | + } |
| 117 | + |
| 118 | + jsonTagInfo := jsonTags.FieldTags(childField) |
| 119 | + if jsonTagInfo.Ignored { |
| 120 | + continue |
| 121 | + } |
| 122 | + |
| 123 | + if !jsonTagInfo.Inline { |
| 124 | + // Check if the field has the required optional markers |
| 125 | + a.checkFieldOptionalMarker(pass, childField, fieldName, markersAccess) |
| 126 | + } else { |
| 127 | + // Inline fields should not have names |
| 128 | + if len(childField.Names) > 0 { |
| 129 | + continue |
| 130 | + } |
| 131 | + |
| 132 | + inLineStruct := getStructFromField(childField) |
| 133 | + if inLineStruct == nil { |
| 134 | + continue |
| 135 | + } |
| 136 | + |
| 137 | + // Check embedded structs recursively |
| 138 | + a.checkStatusStruct(pass, inLineStruct, markersAccess, jsonTags) |
| 139 | + } |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +// getFieldName extracts the field name from an AST field. |
| 144 | +// If the field is an embedded field, it returns the name of the embedded struct. |
| 145 | +// If the field is a pointer to an embedded struct, it returns the |
| 146 | +// name of the embedded struct preceded by a "*". |
| 147 | +// TODO: move it to utils package. |
| 148 | +func (a *analyzer) getFieldName(field *ast.Field) string { |
| 149 | + if len(field.Names) > 0 { |
| 150 | + return field.Names[0].Name |
| 151 | + } |
| 152 | + |
| 153 | + switch typ := field.Type.(type) { |
| 154 | + case *ast.Ident: |
| 155 | + return typ.Name |
| 156 | + case *ast.StarExpr: |
| 157 | + if ident, ok := typ.X.(*ast.Ident); ok { |
| 158 | + return fmt.Sprintf("*%s", ident.Name) |
| 159 | + } |
| 160 | + } |
| 161 | + return "" |
| 162 | +} |
| 163 | + |
| 164 | +// checkFieldOptionalMarker checks if a field has the required optional markers. |
| 165 | +func (a *analyzer) checkFieldOptionalMarker(pass *analysis.Pass, field *ast.Field, fieldName string, markersAccess markers.Markers) { |
| 166 | + fieldMarkers := markersAccess.FieldMarkers(field) |
| 167 | + // Check if the field has either the optional or kubebuilder:validation:Optional marker |
| 168 | + hasOptionalMarker := fieldMarkers.Has(OptionalMarker) || fieldMarkers.Has(KubebuilderOptionalMarker) |
| 169 | + if hasOptionalMarker { |
| 170 | + return |
| 171 | + } |
| 172 | + |
| 173 | + // Check if the field has required markers that need to be replaced |
| 174 | + hasRequiredMarker := fieldMarkers.Has(RequiredMarker) || fieldMarkers.Has(KubebuilderRequiredMarker) |
| 175 | + if hasRequiredMarker { |
| 176 | + // Collect all required markers that need to be removed |
| 177 | + var textEdits []analysis.TextEdit |
| 178 | + |
| 179 | + // Handle standard required markers |
| 180 | + if fieldMarkers.Has(RequiredMarker) { |
| 181 | + for _, marker := range fieldMarkers[RequiredMarker] { |
| 182 | + textEdits = append(textEdits, analysis.TextEdit{ |
| 183 | + Pos: marker.Pos, |
| 184 | + End: marker.End, |
| 185 | + // Remove the marker completely (will add preferred one separately) |
| 186 | + NewText: []byte(""), |
| 187 | + }) |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + // Handle kubebuilder required markers |
| 192 | + if fieldMarkers.Has(KubebuilderRequiredMarker) { |
| 193 | + for _, marker := range fieldMarkers[KubebuilderRequiredMarker] { |
| 194 | + textEdits = append(textEdits, analysis.TextEdit{ |
| 195 | + Pos: marker.Pos, |
| 196 | + End: marker.End, |
| 197 | + // Remove the marker completely (will add preferred one separately) |
| 198 | + NewText: []byte(""), |
| 199 | + }) |
| 200 | + } |
| 201 | + } |
| 202 | + |
| 203 | + // Add the preferred optional marker at the beginning of the field |
| 204 | + textEdits = append(textEdits, analysis.TextEdit{ |
| 205 | + Pos: field.Pos(), |
| 206 | + NewText: []byte(fmt.Sprintf("// +%s\n", a.preferredOptionalMarker)), |
| 207 | + }) |
| 208 | + |
| 209 | + pass.Report(analysis.Diagnostic{ |
| 210 | + Pos: field.Pos(), |
| 211 | + Message: fmt.Sprintf("status field %q must be marked as optional, not required", fieldName), |
| 212 | + SuggestedFixes: []analysis.SuggestedFix{{ |
| 213 | + Message: fmt.Sprintf("replace required marker(s) with %s", a.preferredOptionalMarker), |
| 214 | + TextEdits: textEdits, |
| 215 | + }}, |
| 216 | + }) |
| 217 | + } else { |
| 218 | + // Report the error and suggest a fix to add the optional marker |
| 219 | + pass.Report(analysis.Diagnostic{ |
| 220 | + Pos: field.Pos(), |
| 221 | + Message: fmt.Sprintf("status field %q must be marked as optional", fieldName), |
| 222 | + SuggestedFixes: []analysis.SuggestedFix{ |
| 223 | + { |
| 224 | + Message: "add the optional marker", |
| 225 | + TextEdits: []analysis.TextEdit{ |
| 226 | + { |
| 227 | + // Position at the beginning of the line of the field |
| 228 | + Pos: field.Pos(), |
| 229 | + // Insert the marker before the field |
| 230 | + NewText: []byte(fmt.Sprintf("// +%s\n", a.preferredOptionalMarker)), |
| 231 | + }, |
| 232 | + }, |
| 233 | + }, |
| 234 | + }, |
| 235 | + }) |
| 236 | + } |
| 237 | +} |
| 238 | + |
| 239 | +func getStructFromField(field *ast.Field) *ast.StructType { |
| 240 | + ident, ok := field.Type.(*ast.Ident) |
| 241 | + if !ok { |
| 242 | + return nil |
| 243 | + } |
| 244 | + |
| 245 | + typeSpec, ok := ident.Obj.Decl.(*ast.TypeSpec) |
| 246 | + if !ok { |
| 247 | + return nil |
| 248 | + } |
| 249 | + |
| 250 | + structType, ok := typeSpec.Type.(*ast.StructType) |
| 251 | + if !ok { |
| 252 | + return nil |
| 253 | + } |
| 254 | + |
| 255 | + return structType |
| 256 | +} |
0 commit comments