Skip to content

Commit 9fe9ade

Browse files
committed
Ensure []byte is treated correctly by maxlength analyzer
1 parent 9cf0295 commit 9fe9ade

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

pkg/analysis/maxlength/analyzer.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,18 @@ func checkTypeExpr(pass *analysis.Pass, typeExpr ast.Expr, node ast.Node, aliase
136136
func checkArrayType(pass *analysis.Pass, arrayType *ast.ArrayType, node ast.Node, aliases []*ast.TypeSpec, markersAccess markers.Markers, prefix string) {
137137
if arrayType.Elt != nil {
138138
if ident, ok := arrayType.Elt.(*ast.Ident); ok {
139+
if ident.Name == "byte" {
140+
// byte slices are a special case as they are treated as strings.
141+
// Pretend the ident is a string so that checkString can process it as expected.
142+
i := &ast.Ident{
143+
NamePos: ident.NamePos,
144+
Name: "string",
145+
}
146+
checkString(pass, i, node, aliases, markersAccess, prefix, kubebuilderMaxLength, needsStringMaxLength)
147+
148+
return
149+
}
150+
139151
checkArrayElementIdent(pass, ident, node, aliases, markersAccess, fmt.Sprintf("%s array element", prefix))
140152
}
141153
}

pkg/analysis/maxlength/testdata/src/a/a.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,18 @@ type MaxLength struct {
3232

3333
ArrayWithoutMaxItems []int // want "field ArrayWithoutMaxItems must have a maximum items, add kubebuilder:validation:MaxItems"
3434

35+
ByteSlice []byte // want "field ByteSlice must have a maximum length, add kubebuilder:validation:MaxLength marker"
36+
37+
// +kubebuilder:validation:MaxLength:=512
38+
ByteSliceWithMaxLength []byte
39+
40+
ByteSliceAlias ByteSliceAlias // want "field ByteSliceAlias type ByteSliceAlias must have a maximum length, add kubebuilder:validation:MaxLength marker"
41+
42+
// +kubebuilder:validation:MaxLength:=512
43+
ByteSliceAliasWithMaxLength ByteSliceAlias
44+
45+
ByteSliceAliasWithMaxLengthOnAlias ByteSliceAliasWithMaxLength
46+
3547
// +kubebuilder:validation:MaxItems:=128
3648
StringArrayWithMaxItemsWithoutMaxElementLength []string // want "field StringArrayWithMaxItemsWithoutMaxElementLength array element must have a maximum length, add kubebuilder:validation:items:MaxLength"
3749

@@ -72,3 +84,10 @@ type StringAliasWithMaxLength string
7284
// EnumStringAlias is a string alias that is an enum.
7385
// +kubebuilder:validation:Enum:="A";"B";"C"
7486
type EnumStringAlias string
87+
88+
// ByteSliceAlias is a byte slice without a MaxLength.
89+
type ByteSliceAlias []byte
90+
91+
// ByteSliceAliasWithMaxLength is a byte slice with a MaxLength.
92+
// +kubebuilder:validation:MaxLength:=512
93+
type ByteSliceAliasWithMaxLength []byte

0 commit comments

Comments
 (0)