Skip to content

Fix conversion-gen handling of unexported fields and custom conversions of pointers #133325

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 4 commits into
base: master
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
2 changes: 2 additions & 0 deletions api/api-rules/codegen_violation_exceptions.list
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ API rule violation: names_match,k8s.io/apimachinery/pkg/apis/meta/v1,StatusCause
API rule violation: names_match,k8s.io/apimachinery/pkg/apis/meta/v1,Time,Time
API rule violation: names_match,k8s.io/apimachinery/pkg/runtime,Unknown,ContentEncoding
API rule violation: names_match,k8s.io/apimachinery/pkg/runtime,Unknown,ContentType
API rule violation: names_match,k8s.io/code-generator/examples/apiserver/apis/example/v1,ConversionCustom,privateField
API rule violation: names_match,k8s.io/code-generator/examples/apiserver/apis/example/v1,ConversionPrivate,privateField
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,16 @@ func (g *genConversion) preexists(inType, outType *types.Type) (*types.Type, boo
return function, ok
}

func (g *genConversion) preexistsPointers(inType, outType *types.Type) (*types.Type, bool) {
if inType.Kind != types.Pointer {
return nil, false
}
if outType.Kind != types.Pointer {
return nil, false
}
return g.preexists(inType.Elem, outType.Elem)
}

func (g *genConversion) Init(c *generator.Context, w io.Writer) error {
klogV := klog.V(6)
if klogV.Enabled() {
Expand Down Expand Up @@ -864,9 +874,16 @@ func (g *genConversion) doMap(inType, outType *types.Type, sw *generator.Snippet
}
} else {
conversionExists := true
conditionalConversionExists := false
if function, ok := g.preexists(inType.Elem, outType.Elem); ok {
sw.Do("newVal := new($.|raw$)\n", outType.Elem)
sw.Do("if err := $.|raw$(&val, newVal, s); err != nil {\n", function)
} else if function, ok := g.preexistsPointers(inType.Elem, outType.Elem); ok {
sw.Do("newVal := new($.|raw$)\n", outType.Elem)
sw.Do("if val != nil {\n", nil)
sw.Do("*newVal = new($.|raw$)\n", outType.Elem.Elem)
sw.Do("if err := $.|raw$(val, *newVal, s); err != nil {\n", function)
conditionalConversionExists = true
} else if g.convertibleOnlyWithinPackage(inType.Elem, outType.Elem) {
sw.Do("newVal := new($.|raw$)\n", outType.Elem)
sw.Do("if err := "+nameTmpl+"(&val, newVal, s); err != nil {\n", argsFromType(inType.Elem, outType.Elem))
Expand All @@ -879,6 +896,9 @@ func (g *genConversion) doMap(inType, outType *types.Type, sw *generator.Snippet
if conversionExists {
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
if conditionalConversionExists {
sw.Do("}\n", nil)
}
if inType.Key == outType.Key {
sw.Do("(*out)[key] = *newVal\n", nil)
} else {
Expand Down Expand Up @@ -908,8 +928,14 @@ func (g *genConversion) doSlice(inType, outType *types.Type, sw *generator.Snipp
}
} else {
conversionExists := true
conditionalConversionExists := false
if function, ok := g.preexists(inType.Elem, outType.Elem); ok {
sw.Do("if err := $.|raw$(&(*in)[i], &(*out)[i], s); err != nil {\n", function)
} else if function, ok := g.preexistsPointers(inType.Elem, outType.Elem); ok {
sw.Do("if (*in)[i] != nil {\n", nil)
sw.Do("(*out)[i] = new($.|raw$)\n", outType.Elem.Elem)
sw.Do("if err := $.|raw$((*in)[i], (*out)[i], s); err != nil {\n", function)
conditionalConversionExists = true
} else if g.convertibleOnlyWithinPackage(inType.Elem, outType.Elem) {
sw.Do("if err := "+nameTmpl+"(&(*in)[i], &(*out)[i], s); err != nil {\n", argsFromType(inType.Elem, outType.Elem))
} else {
Expand All @@ -921,6 +947,9 @@ func (g *genConversion) doSlice(inType, outType *types.Type, sw *generator.Snipp
if conversionExists {
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
if conditionalConversionExists {
sw.Do("}\n", nil)
}
}
}
sw.Do("}\n", nil)
Expand All @@ -946,6 +975,17 @@ func (g *genConversion) doStruct(inType, outType *types.Type, sw *generator.Snip
continue
}

if namer.IsPrivateGoName(inMember.Name) && g.outputPackage != inType.Name.Package {
sw.Do("// WARNING: in."+inMember.Name+" is not exported and cannot be read\n", nil)
g.skippedFields[inType] = append(g.skippedFields[inType], inMember.Name)
continue
}
if namer.IsPrivateGoName(outMember.Name) && g.outputPackage != outType.Name.Package {
sw.Do("// WARNING: out."+inMember.Name+" is not exported and cannot be set\n", nil)
g.skippedFields[inType] = append(g.skippedFields[inType], inMember.Name)
continue
}

inMemberType, outMemberType := inMember.Type, outMember.Type
// create a copy of both underlying types but give them the top level alias name (since aliases
// are assignable)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,21 @@ type MemoryDifferent struct {
AllOf []MemoryDifferent
Bool bool // differs from external representation
}

type ConversionPrivate struct {
PublicField string
privateField string
}

type ConversionCustomContainer struct {
Slice []ConversionCustom
SliceP []*ConversionCustom
Map map[string]ConversionCustom
MapP map[string]*ConversionCustom
Struct ConversionCustom
StructP *ConversionCustom
}
type ConversionCustom struct {
PublicField string
privateField string
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
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 v1

import (
conversion "k8s.io/apimachinery/pkg/conversion"
example "k8s.io/code-generator/examples/apiserver/apis/example"
)

// manually created final conversion function required because the object contains private fields that cannot be auto-converted
func Convert_v1_ConversionPrivate_To_example_ConversionPrivate(in *ConversionPrivate, out *example.ConversionPrivate, scope conversion.Scope) error {
return autoConvert_v1_ConversionPrivate_To_example_ConversionPrivate(in, out, scope)
}

// manually created final conversion function required because the object contains private fields that cannot be auto-converted
func Convert_example_ConversionPrivate_To_v1_ConversionPrivate(in *example.ConversionPrivate, out *ConversionPrivate, scope conversion.Scope) error {
return autoConvert_example_ConversionPrivate_To_v1_ConversionPrivate(in, out, scope)
}

// custom conversion function to exercise use of custom functions in slice/map/pointer fields
func Convert_v1_ConversionCustom_To_example_ConversionCustom(in *ConversionCustom, out *example.ConversionCustom, scope conversion.Scope) error {
return autoConvert_v1_ConversionCustom_To_example_ConversionCustom(in, out, scope)
}

// custom conversion function to exercise use of custom functions in slice/map/pointer fields
func Convert_example_ConversionCustom_To_v1_ConversionCustom(in *example.ConversionCustom, out *ConversionCustom, scope conversion.Scope) error {
return autoConvert_example_ConversionCustom_To_v1_ConversionCustom(in, out, scope)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
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 v1

import (
"reflect"
"testing"

"k8s.io/code-generator/examples/apiserver/apis/example"
)

func TestConversion(t *testing.T) {
testcases := []struct {
name string
in *ConversionCustomContainer
}{
{
name: "nil",
in: &ConversionCustomContainer{},
},
{
name: "empty",
in: &ConversionCustomContainer{
Slice: []ConversionCustom{},
SliceP: []*ConversionCustom{},
Map: map[string]ConversionCustom{},
MapP: map[string]*ConversionCustom{},
Struct: ConversionCustom{},
StructP: &ConversionCustom{},
},
},
{
name: "nil_entries",
in: &ConversionCustomContainer{
Slice: []ConversionCustom{{}},
SliceP: []*ConversionCustom{nil},
Map: map[string]ConversionCustom{"key": {}},
MapP: map[string]*ConversionCustom{"key": nil},
},
},
{
name: "set_entries",
in: &ConversionCustomContainer{
Slice: []ConversionCustom{{PublicField: "test1"}},
SliceP: []*ConversionCustom{{PublicField: "test2"}},
Map: map[string]ConversionCustom{"key": {PublicField: "test3"}},
MapP: map[string]*ConversionCustom{"key": {PublicField: "test4"}},
Struct: ConversionCustom{PublicField: "test5"},
StructP: &ConversionCustom{PublicField: "test6"},
},
},
}

for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
original := tc.in.DeepCopy()

out := &example.ConversionCustomContainer{}
if err := Convert_v1_ConversionCustomContainer_To_example_ConversionCustomContainer(tc.in, out, nil); err != nil {
t.Fatal(err)
}

roundtrip := &ConversionCustomContainer{}
if err := Convert_example_ConversionCustomContainer_To_v1_ConversionCustomContainer(out, roundtrip, nil); err != nil {
t.Fatal(err)
}

if !reflect.DeepEqual(original, roundtrip) {
t.Fatalf("expected:\n%#v\ngot:\n%#v", original, roundtrip)
}
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,23 @@ type MemoryDifferent struct {

Bool *bool `json:"bool"` // differs from internal representation
}

type ConversionPrivate struct {
PublicField string `json:"publicField"`
privateField string `json:"privateField"`
}

type ConversionCustomContainer struct {
// +listType=atomic
Slice []ConversionCustom `json:"slice"`
// +listType=atomic
SliceP []*ConversionCustom `json:"sliceP"`
Map map[string]ConversionCustom `json:"map"`
MapP map[string]*ConversionCustom `json:"mapP"`
Struct ConversionCustom `json:"struct"`
StructP *ConversionCustom `json:"structP"`
}
type ConversionCustom struct {
PublicField string `json:"publicField"`
privateField string `json:"privateField"`
}
Loading