Skip to content
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: 1 addition & 1 deletion .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ jobs:
- name: golangci-lint
uses: golangci/golangci-lint-action@4afd733a84b1f43292c63897423277bb7f4313a9 # tag=v8.0.0
with:
version: v2.5.0
version: v2.6.0
args: --output.text.print-linter-name=true --output.text.colors=true --timeout 10m
working-directory: ${{matrix.working-directory}}
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ linters:
- iotamixing
- makezero
- misspell
- modernize
- nakedret
- nilerr
- nolintlint
Expand Down
3 changes: 3 additions & 0 deletions pkg/applyconfiguration/applyconfiguration_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,9 @@ var _ = Describe("ApplyConfiguration generation from API types", func() {
// Make sure the import paths are correct for the newly generated content.
content = []byte(strings.ReplaceAll(string(content), "testdata/cronjob/api/v1/applyconfiguration", filepath.Join("testdata/cronjob/api/v1", outputPackage)))

// Make sure the interface{} is replaced with any.
content = []byte(strings.ReplaceAll(string(content), "any", "interface{}"))
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't understand why this is necessary, it's causes by my changing the signature of ForKind. But it's not clear to me why I can't get Golang to just output "any" on the generated code.


Expect(string(filesInOutput[name])).To(BeComparableTo(string(content)), "Generated files should match the checked in files, diff found in %s", name)
}
},
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 5 additions & 6 deletions pkg/applyconfiguration/testdata/cronjob/api/v1/cronjob_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"encoding"
"encoding/json"
"fmt"
"maps"
"net/url"
"strconv"
"time"
Expand Down Expand Up @@ -412,8 +413,8 @@ type ContainsNestedMap struct {
// +kubebuilder:validation:Type=object
// +kubebuilder:pruning:PreserveUnknownFields
type Preserved struct {
ConcreteField string `json:"concreteField"`
Rest map[string]interface{} `json:"-"`
ConcreteField string `json:"concreteField"`
Rest map[string]any `json:"-"`
}

func (p *Preserved) UnmarshalJSON(data []byte) error {
Expand All @@ -434,10 +435,8 @@ func (p *Preserved) UnmarshalJSON(data []byte) error {
}

func (p *Preserved) MarshalJSON() ([]byte, error) {
full := make(map[string]interface{}, len(p.Rest)+1)
for k, v := range p.Rest {
full[k] = v
}
full := make(map[string]any, len(p.Rest)+1)
maps.Copy(full, p.Rest)
full["concreteField"] = p.ConcreteField
return json.Marshal(full)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/crd/flatten.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ type ErrorRecorder interface {

// isOrNil checks if val is nil if val is of a nillable type, otherwise,
// it compares val to valInt (which should probably be the zero value).
func isOrNil(val reflect.Value, valInt interface{}, zeroInt interface{}) bool {
func isOrNil(val reflect.Value, valInt any, zeroInt any) bool {
switch valKind := val.Kind(); valKind {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
return val.IsNil()
Expand Down
12 changes: 6 additions & 6 deletions pkg/crd/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,15 +108,15 @@ func (Generator) RegisterMarkers(into *markers.Registry) error {
}

// transformRemoveCRDStatus ensures we do not write the CRD status field.
func transformRemoveCRDStatus(obj map[string]interface{}) error {
func transformRemoveCRDStatus(obj map[string]any) error {
delete(obj, "status")
return nil
}

// transformPreserveUnknownFields adds spec.preserveUnknownFields=value.
func transformPreserveUnknownFields(value bool) func(map[string]interface{}) error {
return func(obj map[string]interface{}) error {
if spec, ok := obj["spec"].(map[interface{}]interface{}); ok {
func transformPreserveUnknownFields(value bool) func(map[string]any) error {
return func(obj map[string]any) error {
if spec, ok := obj["spec"].(map[any]any); ok {
spec["preserveUnknownFields"] = value
}
return nil
Expand Down Expand Up @@ -185,7 +185,7 @@ func (g Generator) Generate(ctx *genall.GenerationContext) error {
// Prevent the top level metadata for the CRD to be generate regardless of the intention in the arguments
FixTopLevelMetadata(crdRaw)

versionedCRDs := make([]interface{}, len(crdVersions))
versionedCRDs := make([]any, len(crdVersions))
for i, ver := range crdVersions {
conv, err := AsVersion(crdRaw, schema.GroupVersion{Group: apiext.SchemeGroupVersion.Group, Version: ver})
if err != nil {
Expand All @@ -202,7 +202,7 @@ func (g Generator) Generate(ctx *genall.GenerationContext) error {
} else {
fileName = fmt.Sprintf("%s_%s.%s.yaml", crdRaw.Spec.Group, crdRaw.Spec.Names.Plural, crdVersions[i])
}
if err := ctx.WriteYAML(fileName, headerText, []interface{}{crd}, yamlOpts...); err != nil {
if err := ctx.WriteYAML(fileName, headerText, []any{crd}, yamlOpts...); err != nil {
return err
}
}
Expand Down
10 changes: 4 additions & 6 deletions pkg/crd/known_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ limitations under the License.
package crd

import (
"maps"

apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-tools/pkg/loader"
Expand Down Expand Up @@ -156,13 +158,9 @@ func AddKnownTypes(parser *Parser) {
// ensure everything is there before adding to PackageOverrides
// TODO(directxman12): this is a bit of a hack, maybe just use constructors?
parser.init()
for pkgName, override := range KnownPackages {
parser.PackageOverrides[pkgName] = override
}
maps.Copy(parser.PackageOverrides, KnownPackages)
// if we want to generate the embedded ObjectMeta in the CRD we need to add the ObjectMetaPackages
if parser.GenerateEmbeddedObjectMeta {
for pkgName, override := range ObjectMetaPackages {
parser.PackageOverrides[pkgName] = override
}
maps.Copy(parser.PackageOverrides, ObjectMetaPackages)
}
}
2 changes: 1 addition & 1 deletion pkg/crd/markers/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ type hasHelp interface {

// mustMakeAllWithPrefix converts each object into a marker definition using
// the object's type's with the prefix to form the marker name.
func mustMakeAllWithPrefix(prefix string, target markers.TargetType, objs ...interface{}) []*definitionWithHelp {
func mustMakeAllWithPrefix(prefix string, target markers.TargetType, objs ...any) []*definitionWithHelp {
defs := make([]*definitionWithHelp, len(objs))
for i, obj := range objs {
name := prefix + reflect.TypeOf(obj).Name()
Expand Down
10 changes: 5 additions & 5 deletions pkg/crd/markers/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ type MinProperties int

// Enum specifies that this (scalar) field is restricted to the *exact* values specified here.
// +controllertools:marker:generateHelp:category="CRD validation"
type Enum []interface{}
type Enum []any

// Format specifies additional "complex" formatting for this field.
//
Expand Down Expand Up @@ -265,7 +265,7 @@ type Nullable struct{}
// submission of the containing CRD to an apiserver.
// +controllertools:marker:generateHelp:category="CRD validation"
type Default struct {
Value interface{}
Value any
}

// Title sets the title for this field.
Expand All @@ -276,7 +276,7 @@ type Default struct {
// important context about what the schema represents.
// +controllertools:marker:generateHelp:category="CRD validation"
type Title struct {
Value interface{}
Value any
}

// KubernetesDefault sets the default value for this field.
Expand All @@ -290,7 +290,7 @@ type Title struct {
// submission of the containing CRD to an apiserver.
// +controllertools:marker:generateHelp:category="CRD validation"
type KubernetesDefault struct {
Value interface{}
Value any
}

// Example sets the example value for this field.
Expand All @@ -303,7 +303,7 @@ type KubernetesDefault struct {
// submission of the containing CRD to an apiserver.
// +controllertools:marker:generateHelp:category="CRD validation"
type Example struct {
Value interface{}
Value any
}

// XPreserveUnknownFields stops the apiserver from pruning fields which are not specified.
Expand Down
4 changes: 2 additions & 2 deletions pkg/crd/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func transform(t *testing.T, expr string) *apiext.JSONSchemaProps {
modules := []pkgstest.Module{
{
Name: moduleName,
Files: map[string]interface{}{
Files: map[string]any{
"test.go": `
package crd
type Test ` + expr,
Expand Down Expand Up @@ -121,7 +121,7 @@ func Test_Schema_ApplyMarkers(t *testing.T) {
var invocations []string

applyMarkers(ctx, markers.MarkerValues{
"blah": []interface{}{
"blah": []any{
&testPriorityMarker{
priority: 0, callback: func() {
invocations = append(invocations, "0")
Expand Down
6 changes: 3 additions & 3 deletions pkg/crd/testdata/cronjob_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -452,8 +452,8 @@ type ContainsNestedMap struct {
// +kubebuilder:validation:Type=object
// +kubebuilder:pruning:PreserveUnknownFields
type Preserved struct {
ConcreteField string `json:"concreteField"`
Rest map[string]interface{} `json:"-"`
ConcreteField string `json:"concreteField"`
Rest map[string]any `json:"-"`
}

func (p *Preserved) UnmarshalJSON(data []byte) error {
Expand All @@ -474,7 +474,7 @@ func (p *Preserved) UnmarshalJSON(data []byte) error {
}

func (p *Preserved) MarshalJSON() ([]byte, error) {
full := make(map[string]interface{}, len(p.Rest)+1)
full := make(map[string]any, len(p.Rest)+1)
for k, v := range p.Rest {
full[k] = v
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/crd/testdata/wrong_annotation_format/cronjob_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,8 @@ type ContainsNestedMap struct {
// +kubebuilder:validation:Type=object
// +kubebuilder:pruning:PreserveUnknownFields
type Preserved struct {
ConcreteField string `json:"concreteField"`
Rest map[string]interface{} `json:"-"`
ConcreteField string `json:"concreteField"`
Rest map[string]any `json:"-"`
}

func (p *Preserved) UnmarshalJSON(data []byte) error {
Expand All @@ -264,7 +264,7 @@ func (p *Preserved) UnmarshalJSON(data []byte) error {
}

func (p *Preserved) MarshalJSON() ([]byte, error) {
full := make(map[string]interface{}, len(p.Rest)+1)
full := make(map[string]any, len(p.Rest)+1)
for k, v := range p.Rest {
full[k] = v
}
Expand Down
9 changes: 3 additions & 6 deletions pkg/deepcopy/traverse.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (c *codeWriter) Line(line string) {
}

// Linef writes a single line with formatting (as per fmt.Sprintf).
func (c *codeWriter) Linef(line string, args ...interface{}) {
func (c *codeWriter) Linef(line string, args ...any) {
fmt.Fprintf(c.out, line+"\n", args...)
}

Expand Down Expand Up @@ -447,9 +447,7 @@ func (c *copyMethodMaker) genSliceDeepCopy(actualName *namingInfo, sliceType *ty
func (c *copyMethodMaker) genStructDeepCopy(_ *namingInfo, structType *types.Struct) {
c.Line("*out = *in")

for i := 0; i < structType.NumFields(); i++ {
field := structType.Field(i)

for field := range structType.Fields() {
// if we have a manual deepcopy, use that
hasDeepCopy, copyOnPtr := hasDeepCopyMethod(c.pkg, field.Type())
hasDeepCopyInto := hasDeepCopyIntoMethod(c.pkg, field.Type())
Expand Down Expand Up @@ -769,8 +767,7 @@ func fineToShallowCopy(typeInfo types.Type) bool {
return fineToShallowCopy(typeInfo.Underlying())
case *types.Struct:
// structs are fine to shallow-copy if they have all shallow-copyable fields
for i := 0; i < typeInfo.NumFields(); i++ {
field := typeInfo.Field(i)
for field := range typeInfo.Fields() {
if !fineToShallowCopy(field.Type()) {
return false
}
Expand Down
16 changes: 8 additions & 8 deletions pkg/genall/genall.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,27 +121,27 @@ type GenerationContext struct {

// WriteYAMLOptions implements the Options Pattern for WriteYAML.
type WriteYAMLOptions struct {
transform func(obj map[string]interface{}) error
transform func(obj map[string]any) error
}

// WithTransform applies a transformation to objects just before writing them.
func WithTransform(transform func(obj map[string]interface{}) error) *WriteYAMLOptions {
func WithTransform(transform func(obj map[string]any) error) *WriteYAMLOptions {
return &WriteYAMLOptions{
transform: transform,
}
}

// TransformRemoveCreationTimestamp ensures we do not write the metadata.creationTimestamp field.
func TransformRemoveCreationTimestamp(obj map[string]interface{}) error {
metadata := obj["metadata"].(map[interface{}]interface{})
func TransformRemoveCreationTimestamp(obj map[string]any) error {
metadata := obj["metadata"].(map[any]any)
delete(metadata, "creationTimestamp")
return nil
}

// WriteYAML writes the given objects out, serialized as YAML, using the
// context's OutputRule. Objects are written as separate documents, separated
// from each other by `---` (as per the YAML spec).
func (g GenerationContext) WriteYAML(itemPath, headerText string, objs []interface{}, options ...*WriteYAMLOptions) error {
func (g GenerationContext) WriteYAML(itemPath, headerText string, objs []any, options ...*WriteYAMLOptions) error {
out, err := g.Open(nil, itemPath)
if err != nil {
return err
Expand Down Expand Up @@ -171,7 +171,7 @@ func (g GenerationContext) WriteYAML(itemPath, headerText string, objs []interfa
}

// yamlMarshal is based on sigs.k8s.io/yaml.Marshal, but allows for transforming the final data before writing.
func yamlMarshal(o interface{}, options ...*WriteYAMLOptions) ([]byte, error) {
func yamlMarshal(o any, options ...*WriteYAMLOptions) ([]byte, error) {
j, err := json.Marshal(o)
if err != nil {
return nil, fmt.Errorf("error marshaling into JSON: %w", err)
Expand All @@ -183,10 +183,10 @@ func yamlMarshal(o interface{}, options ...*WriteYAMLOptions) ([]byte, error) {
// yamlJSONToYAMLWithFilter is based on sigs.k8s.io/yaml.JSONToYAML, but allows for transforming the final data before writing.
func yamlJSONToYAMLWithFilter(j []byte, options ...*WriteYAMLOptions) ([]byte, error) {
// Convert the JSON to an object.
var jsonObj map[string]interface{}
var jsonObj map[string]any
// We are using yaml.Unmarshal here (instead of json.Unmarshal) because the
// Go JSON library doesn't try to pick the right number type (int, float,
// etc.) when unmarshalling to interface{}, it just picks float64
// etc.) when unmarshalling to any, it just picks float64
// universally. go-yaml does go through the effort of picking the right
// number type, so we can preserve number type throughout this process.
if err := rawyaml.Unmarshal(j, &jsonObj); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion pkg/genall/help/pretty/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ func writePadding(out io.Writer, typ []byte, amt int) error {

num := amt / len(typ)
rem := amt % len(typ)
for i := 0; i < num; i++ {
for range num {
if _, err := out.Write(typ); err != nil {
return err
}
Expand Down
7 changes: 3 additions & 4 deletions pkg/genall/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package genall

import (
"fmt"
"maps"
"strings"

"golang.org/x/tools/go/packages"
Expand All @@ -42,7 +43,7 @@ func RegisterOptionsMarkers(into *markers.Registry) error {
return err
}
// NB(directxman12): we make this optional so we don't have a bootstrap problem with helpgen
if helpGiver, hasHelp := ((interface{})(InputPaths(nil))).(HasHelp); hasHelp {
if helpGiver, hasHelp := ((any)(InputPaths(nil))).(HasHelp); hasHelp {
into.AddHelp(InputPathsMarker, helpGiver.Help())
}
return nil
Expand Down Expand Up @@ -100,9 +101,7 @@ func FromOptionsWithConfig(cfg *packages.Config, optionsRegistry *markers.Regist
}

outRules := DirectoryPerGenerator("config", protoRt.GeneratorsByName)
for gen, rule := range protoRt.OutputRules.ByGenerator {
outRules.ByGenerator[gen] = rule
}
maps.Copy(outRules.ByGenerator, protoRt.OutputRules.ByGenerator)

genRuntime.OutputRules = outRules
return genRuntime, nil
Expand Down
Loading