Skip to content

✨ Generation of typed apply clients using upstream generator #818

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
1e8762f
Stub out generator
jpbetz Nov 9, 2020
63421a4
Add apply gen to controller-tools
Jefftree Jan 19, 2021
d81dfba
Add code-generator to go.mod
JoelSpeed Jan 24, 2023
d91f503
Integrate upstream apply config generator
JoelSpeed Jan 24, 2023
c521047
Cleanup unused code from previous implementation
JoelSpeed May 19, 2023
2711c92
Convert controller-tools tags to genclient
JoelSpeed Jan 24, 2023
ba99f7a
Add generated clients
JoelSpeed Jan 24, 2023
d93d1cb
Cleanup markers, ensure correct path for non GOPATH
JoelSpeed May 19, 2023
0a5f81a
Add test to check generated content against generated master
JoelSpeed May 19, 2023
8d0a899
chore: resolve applyconfig gen correctly
jakobmoellerdev Sep 15, 2023
740e0ae
Migrate to gengo v2
JoelSpeed Feb 28, 2025
5647ec5
Update generated test data
JoelSpeed Feb 28, 2025
9aec904
Ignore testdata for the purposes of go generate
JoelSpeed Feb 28, 2025
8a7c5ec
Rename apply command to applyconfiguration
JoelSpeed Mar 21, 2025
c343c7d
Rename package to applyconfiguration
JoelSpeed Mar 21, 2025
326a20e
Rework tests to use temporary directory for output files
JoelSpeed Mar 21, 2025
0aae757
Update cronjob_types with the latest version
JoelSpeed Mar 21, 2025
c8ef095
Update groupversion inline with latest kubebuilder
JoelSpeed Mar 21, 2025
fe610e2
Update go.mod to match latest of top level
JoelSpeed Mar 21, 2025
46f9f4f
Move test apis into an API v1 folder to be more accurate
JoelSpeed Mar 21, 2025
0023b01
Add test for generating client outside of API directory
JoelSpeed Mar 21, 2025
804b842
Address feedback on gen.go
JoelSpeed Mar 21, 2025
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
20 changes: 14 additions & 6 deletions cmd/controller-gen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import (
"strings"

"github.com/spf13/cobra"

"sigs.k8s.io/controller-tools/pkg/applyconfiguration"
"sigs.k8s.io/controller-tools/pkg/crd"
"sigs.k8s.io/controller-tools/pkg/deepcopy"
"sigs.k8s.io/controller-tools/pkg/genall"
Expand All @@ -48,11 +50,12 @@ var (
// each turns into a command line option,
// and has options for output forms.
allGenerators = map[string]genall.Generator{
"crd": crd.Generator{},
"rbac": rbac.Generator{},
"object": deepcopy.Generator{},
"webhook": webhook.Generator{},
"schemapatch": schemapatcher.Generator{},
"crd": crd.Generator{},
"rbac": rbac.Generator{},
"object": deepcopy.Generator{},
"applyconfiguration": applyconfiguration.Generator{},
"webhook": webhook.Generator{},
"schemapatch": schemapatcher.Generator{},
}

// allOutputRules defines the list of all known output rules, giving
Expand Down Expand Up @@ -139,13 +142,18 @@ func main() {
controller-gen object paths=./apis/v1beta1/some_types.go

# Generate OpenAPI v3 schemas for API packages and merge them into existing CRD manifests
controller-gen schemapatch:manifests=./manifests output:dir=./manifests paths=./pkg/apis/...
controller-gen schemapatch:manifests=./manifests output:dir=./manifests paths=./pkg/apis/...

# Run all the generators for a given project
controller-gen paths=./apis/...

# Explain the markers for generating CRDs, and their arguments
controller-gen crd -ww

# Generate applyconfigurations for CRDs for use with Server Side Apply. They will be placed
# into a "applyconfiguration/" subdirectory

controller-gen applyconfiguration paths=./apis/...
`,
RunE: func(c *cobra.Command, rawOpts []string) error {
// print version if asked for it
Expand Down
11 changes: 10 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ require (
k8s.io/api v0.33.0-beta.0
k8s.io/apiextensions-apiserver v0.33.0-beta.0
k8s.io/apimachinery v0.33.0-beta.0
k8s.io/code-generator v0.33.0-beta.0
k8s.io/gengo/v2 v2.0.0-20250207200755-1244d31929d7
k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738
sigs.k8s.io/yaml v1.4.0
)
Expand All @@ -24,10 +26,15 @@ require (
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/swag v0.23.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/google/gnostic-models v0.6.9 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
Expand All @@ -39,9 +46,11 @@ require (
golang.org/x/sync v0.12.0 // indirect
golang.org/x/sys v0.31.0 // indirect
golang.org/x/text v0.23.0 // indirect
google.golang.org/protobuf v1.36.5 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
k8s.io/klog/v2 v2.130.1 // indirect
k8s.io/kube-openapi v0.0.0-20250304201544-e5f78fe3ede9 // indirect
sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect
sigs.k8s.io/randfill v1.0.0 // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.6.0 // indirect
Expand Down
23 changes: 23 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv
github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs=
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE=
github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k=
github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14=
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 h1:p104kn46Q8WdvHunIJ9dAyjPVtrBPhSr3KT2yUst43I=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
Expand All @@ -28,6 +36,8 @@ github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrU
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/google/gnostic-models v0.6.9 h1:MU/8wDLif2qCXZmzncUQ/BOfxWfthHi63KqpoNbWqVw=
github.com/google/gnostic-models v0.6.9/go.mod h1:CiWsm0s6BSQd1hRn8/QmxqB6BesYcbSZxsz9b0KuDBw=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
Expand All @@ -40,14 +50,21 @@ github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad/go.mod h1:vavhavw2zAx
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
Expand Down Expand Up @@ -173,8 +190,14 @@ k8s.io/apiextensions-apiserver v0.33.0-beta.0 h1:3oqBvfd26IOekt96KEfE8A0wA/k1wDS
k8s.io/apiextensions-apiserver v0.33.0-beta.0/go.mod h1:TKTeoFcmGvtiDNV+wj8wJfZhamZNOhvi9yOIE2d1iWs=
k8s.io/apimachinery v0.33.0-beta.0 h1:vLDBChfQwyimk6AbuT7OZOIqxSg/44JlXuxqBk85j68=
k8s.io/apimachinery v0.33.0-beta.0/go.mod h1:S2OIkExGqJOXYSYcAJwQ9zWcc6BkBUdTJUu4M7z0cvo=
k8s.io/code-generator v0.33.0-beta.0 h1:QYiWYFUT9G7lnF1ucDYr/sZUaG/kptrooX2PJxEL+Go=
k8s.io/code-generator v0.33.0-beta.0/go.mod h1:RBvFpvqtyQygCBjMayNyYqdzy+89LdzqAx0Th+dgmzQ=
k8s.io/gengo/v2 v2.0.0-20250207200755-1244d31929d7 h1:2OX19X59HxDprNCVrWi6jb7LW1PoqTlYqEq5H2oetog=
k8s.io/gengo/v2 v2.0.0-20250207200755-1244d31929d7/go.mod h1:EJykeLsmFC60UQbYJezXkEsG2FLrt0GPNkU5iK5GWxU=
k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk=
k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE=
k8s.io/kube-openapi v0.0.0-20250304201544-e5f78fe3ede9 h1:t0huyHnz6HsokckRxAF1bY0cqPFwzINKCL7yltEjZQc=
k8s.io/kube-openapi v0.0.0-20250304201544-e5f78fe3ede9/go.mod h1:5jIi+8yX4RIb8wk3XwBo5Pq2ccx4FP10ohkbSKCZoK8=
k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 h1:M3sRQVHv7vB20Xc2ybTt7ODCeFj6JSWYFzOFnYeS6Ro=
k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 h1:/Rv+M11QRah1itp8VhT6HoVx1Ray9eB4DBr+K+/sCJ8=
Expand Down
217 changes: 217 additions & 0 deletions pkg/applyconfiguration/applyconfiguration_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
/*
Copyright 2019 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 applyconfiguration

import (
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"

. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
"k8s.io/apimachinery/pkg/util/sets"

"sigs.k8s.io/controller-tools/pkg/crd"
"sigs.k8s.io/controller-tools/pkg/genall"
"sigs.k8s.io/controller-tools/pkg/loader"
"sigs.k8s.io/controller-tools/pkg/markers"
)

const (
cronjobDir = "./testdata/cronjob"
applyConfigurationDir = "applyconfiguration"
)

type outputToMap map[string]*outputFile

// Open implements genall.OutputRule.
func (m outputToMap) Open(_ *loader.Package, path string) (io.WriteCloser, error) {
if _, ok := m[path]; !ok {
m[path] = &outputFile{}
}
return m[path], nil
}

type outputFile struct {
contents []byte
}

func (o *outputFile) Write(p []byte) (int, error) {
o.contents = append(o.contents, p...)
return len(p), nil
}

func (o *outputFile) Close() error {
return nil
}

var _ = Describe("ApplyConfiguration generation from API types", func() {
var originalCWD string

BeforeEach(func() {
var tmpDir string

By("Setting up a temporary directory", func() {
var err error
tmpDir, err = os.MkdirTemp("", "applyconfiguration-integration-test")
Expect(err).NotTo(HaveOccurred(), "Should be able to create a temporary directory")

// Copy the testdata directory, but removed the generated files.
Expect(os.CopyFS(tmpDir, os.DirFS(cronjobDir))).To(Succeed(), "Should be able to copy source files")
Expect(os.RemoveAll(filepath.Join(tmpDir, "api/v1", applyConfigurationDir))).To(Succeed(), "Should be able to remove generated file from temp directory")
})

By("Switching into testdata to appease go modules", func() {
cwd, err := os.Getwd()
Expect(err).NotTo(HaveOccurred())

originalCWD = cwd

Expect(os.Chdir(tmpDir)).To(Succeed()) // go modules are directory-sensitive
})

By(fmt.Sprintf("Completed set up in %s", tmpDir))
})

AfterEach(func() {
// Reset the working directory
Expect(os.Chdir(originalCWD)).To(Succeed())
})

DescribeTable("should be able to verify generated ApplyConfiguration types for the CronJob schema", func(outputPackage string) {
Expect(replaceOutputPkgMarker("./api/v1", outputPackage)).To(Succeed())

// The output is used to capture the generated CRD file.
// The output of the applyconfiguration cannot be generated to memory, gengo handles all of the writing to disk directly.
output := make(outputToMap)

By("Initializing the runtime")
optionsRegistry := &markers.Registry{}
Expect(genall.RegisterOptionsMarkers(optionsRegistry)).To(Succeed())
Expect(optionsRegistry.Register(markers.Must(markers.MakeDefinition("crd", markers.DescribesPackage, crd.Generator{})))).To(Succeed())
Expect(optionsRegistry.Register(markers.Must(markers.MakeDefinition("applyconfiguration", markers.DescribesPackage, Generator{})))).To(Succeed())

rt, err := genall.FromOptions(optionsRegistry, []string{
"crd:allowDangerousTypes=true,ignoreUnexportedFields=true", // Run another generator first to make sure they don't interfere; see also: the comment on cronjob_types.go:UntypedBlob
"applyconfiguration",
"paths=./api/v1",
})
Expect(err).NotTo(HaveOccurred())

rt.OutputRules = genall.OutputRules{Default: output}

originalFS := os.DirFS(filepath.Join(originalCWD, cronjobDir))
tmpFS := os.DirFS(".")

By("Running the generator")
hadErrs := rt.Run()

By("Checking for generation errors")
Expect(hadErrs).To(BeFalse(), "Generator should run without errors")

filesInOriginal := make(map[string][]byte)
originalFileNames := sets.New[string]()
Expect(fs.WalkDir(originalFS, filepath.Join("api/v1", applyConfigurationDir), func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}

if d.IsDir() {
return nil
}

data, err := os.ReadFile(filepath.Join(originalCWD, cronjobDir, path))
if err != nil {
return fmt.Errorf("error reading file %s: %w", path, err)
}

// Record the path without the path prefix for comparison later.
path = strings.TrimPrefix(path, filepath.Join("api/v1", applyConfigurationDir)+"/")
originalFileNames.Insert(path)
filesInOriginal[path] = data
return nil
})).To(Succeed())

filesInOutput := make(map[string][]byte)
outputFileNames := sets.New[string]()
Expect(fs.WalkDir(tmpFS, filepath.Join("api/v1", outputPackage), func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}

if d.IsDir() {
return nil
}

data, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("error reading file %s: %w", path, err)
}

// Record the path without the path prefix for comparison later.
path = strings.TrimPrefix(path, filepath.Join("api/v1", outputPackage)+"/")
outputFileNames.Insert(path)
filesInOutput[path] = data
return nil
})).To(Succeed())

// // Every file should be in both sets, check for files not in both sets.
Expect(outputFileNames.UnsortedList()).To(ConsistOf(originalFileNames.UnsortedList()), "Generated files should match the checked in files")

for name, content := range filesInOriginal {
// If the output package uses a relative path we need to remove the "../" from the package name.
outputPackageName := strings.ReplaceAll(outputPackage, "../", "")

// Make sure the package string is correct for the newly generated content.
content = []byte(strings.Replace(string(content), "package applyconfiguration", fmt.Sprintf("package %s", outputPackageName), 1))

// 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)))

Expect(string(filesInOutput[name])).To(BeComparableTo(string(content)), "Generated files should match the checked in files, diff found in %s", name)
}
},
Entry("with the default applyconfiguration output package", "applyconfiguration"),
Entry("with the an alternative output package", "other"),
Entry("with a package outside of the current directory", "../../clients"),
)
})

func replaceOutputPkgMarker(dir string, newOutputPackage string) error {
f, err := os.Open(filepath.Join(dir, "groupversion_info.go"))
if err != nil {
return fmt.Errorf("error opening groupversion_info.go: %w", err)
}
defer f.Close()

data, err := io.ReadAll(f)
if err != nil {
return fmt.Errorf("error reading groupversion_info.go: %w", err)
}

newData := strings.Replace(string(data), "// +kubebuilder:ac:output:package=\"applyconfiguration\"", fmt.Sprintf("// +kubebuilder:ac:output:package=\"%s\"", newOutputPackage), 1)

if err := os.WriteFile(filepath.Join(dir, "groupversion_info.go"), []byte(newData), 0644); err != nil {
return fmt.Errorf("error writing groupversion_info.go: %w", err)
}

return nil
}
29 changes: 29 additions & 0 deletions pkg/applyconfiguration/applyconfiguration_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
Copyright 2019 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 applyconfiguration

import (
"testing"

. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)

func TestObjectGeneration(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "ApplyConfiguration Generation Suite")
}
Loading