From a39a52d0b1b28d4392d6f67ca7e3ebbf4d749d3c Mon Sep 17 00:00:00 2001 From: Camila Macedo Date: Tue, 13 Aug 2024 06:39:07 +0100 Subject: [PATCH] (cleanup) hack docs --- .../cronjob-tutorial/generate_cronjob.go | 203 ++++++++---------- .../generate_getting_started.go | 39 +--- hack/docs/utils/utils.go | 47 ++++ 3 files changed, 146 insertions(+), 143 deletions(-) create mode 100644 hack/docs/utils/utils.go diff --git a/hack/docs/internal/cronjob-tutorial/generate_cronjob.go b/hack/docs/internal/cronjob-tutorial/generate_cronjob.go index cde30d2ba84..604e31d72bc 100644 --- a/hack/docs/internal/cronjob-tutorial/generate_cronjob.go +++ b/hack/docs/internal/cronjob-tutorial/generate_cronjob.go @@ -17,13 +17,13 @@ limitations under the License. package cronjob import ( - "os" "os/exec" "path/filepath" log "github.com/sirupsen/logrus" "github.com/spf13/afero" + hackutils "sigs.k8s.io/kubebuilder/v4/hack/docs/utils" pluginutil "sigs.k8s.io/kubebuilder/v4/pkg/plugin/util" "sigs.k8s.io/kubebuilder/v4/test/e2e/utils" ) @@ -34,24 +34,10 @@ type Sample struct { func NewSample(binaryPath, samplePath string) Sample { log.Infof("Generating the sample context of Cronjob...") - ctx := newSampleContext(binaryPath, samplePath, "GO111MODULE=on") + ctx := hackutils.NewSampleContext(binaryPath, samplePath, "GO111MODULE=on") return Sample{&ctx} } -func newSampleContext(binaryPath string, samplePath string, env ...string) utils.TestContext { - cmdContext := &utils.CmdContext{ - Env: env, - Dir: samplePath, - } - - testContext := utils.TestContext{ - CmdContext: cmdContext, - BinaryName: binaryPath, - } - - return testContext -} - // Prepare the Context for the sample project func (sp *Sample) Prepare() { log.Infof("destroying directory for cronjob sample project") @@ -60,7 +46,7 @@ func (sp *Sample) Prepare() { log.Infof("refreshing tools and creating directory...") err := sp.ctx.Prepare() - CheckError("creating directory for sample project", err) + hackutils.CheckError("creating directory for sample project", err) } func (sp *Sample) GenerateSampleProject() { @@ -72,7 +58,7 @@ func (sp *Sample) GenerateSampleProject() { "--license", "apache2", "--owner", "The Kubernetes authors", ) - CheckError("Initializing the cronjob project", err) + hackutils.CheckError("Initializing the cronjob project", err) log.Infof("Adding a new config type") err = sp.ctx.CreateAPI( @@ -81,7 +67,7 @@ func (sp *Sample) GenerateSampleProject() { "--kind", "CronJob", "--resource", "--controller", ) - CheckError("Creating the API", err) + hackutils.CheckError("Creating the API", err) log.Infof("Implementing admission webhook") err = sp.ctx.CreateWebhook( @@ -90,36 +76,36 @@ func (sp *Sample) GenerateSampleProject() { "--kind", "CronJob", "--defaulting", "--programmatic-validation", ) - CheckError("Implementing admission webhook", err) + hackutils.CheckError("Implementing admission webhook", err) } func (sp *Sample) UpdateTutorial() { log.Println("TODO: update tutorial") // 1. update specs - updateSpec(sp) + sp.updateSpec() // 2. update webhook - updateWebhook(sp) + sp.updateWebhook() // 3. update makefile - updateMakefile(sp) + sp.updateMakefile() // 4. generate extra files - codeGen(sp) + sp.codeGen() // 5. compensate other intro in API - updateAPIStuff(sp) + sp.updateAPIStuff() // 6. update reconciliation and main.go // 6.1 update controller - updateController(sp) + sp.updateController() // 6.2 update main.go - updateMain(sp) + sp.updateMain() // 7. generate extra files - codeGen(sp) + sp.codeGen() // 8. update suite_test explanation - updateSuiteTest(sp) + sp.updateSuiteTest() // 9. uncomment kustomization - updateKustomization(sp) + sp.updateKustomization() // 10. add example - updateExample(sp) + sp.updateExample() // 11. add test - addControllerTest(sp) + sp.addControllerTest() } // CodeGen is a noop for this sample, just to make generation of all samples @@ -127,26 +113,26 @@ func (sp *Sample) UpdateTutorial() { // advantage of a separate call, but it is not necessary. func (sp *Sample) CodeGen() {} -func codeGen(sp *Sample) { +func (sp *Sample) codeGen() { cmd := exec.Command("go", "get", "github.com/robfig/cron") _, err := sp.ctx.Run(cmd) - CheckError("Failed to get package robfig/cron", err) + hackutils.CheckError("Failed to get package robfig/cron", err) cmd = exec.Command("make", "manifests") _, err = sp.ctx.Run(cmd) - CheckError("Failed to run make manifests for cronjob tutorial", err) + hackutils.CheckError("Failed to run make manifests for cronjob tutorial", err) cmd = exec.Command("make", "all") _, err = sp.ctx.Run(cmd) - CheckError("Failed to run make all for cronjob tutorial", err) + hackutils.CheckError("Failed to run make all for cronjob tutorial", err) cmd = exec.Command("go", "mod", "tidy") _, err = sp.ctx.Run(cmd) - CheckError("Failed to run go mod tidy for cronjob tutorial", err) + hackutils.CheckError("Failed to run go mod tidy for cronjob tutorial", err) } // insert code to fix docs -func updateSpec(sp *Sample) { +func (sp *Sample) updateSpec() { var err error err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_types.go"), @@ -157,7 +143,7 @@ func updateSpec(sp *Sample) { /* */`) - CheckError("fixing cronjob_types.go", err) + hackutils.CheckError("fixing cronjob_types.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_types.go"), @@ -165,7 +151,7 @@ func updateSpec(sp *Sample) { ` /* */`) - CheckError("fixing cronjob_types.go", err) + hackutils.CheckError("fixing cronjob_types.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_types.go"), @@ -173,17 +159,17 @@ func updateSpec(sp *Sample) { ` batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1"`) - CheckError("fixing cronjob_types.go", err) + hackutils.CheckError("fixing cronjob_types.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_types.go"), `to be serialized.`, CronjobSpecExplaination) - CheckError("fixing cronjob_types.go", err) + hackutils.CheckError("fixing cronjob_types.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_types.go"), `type CronJobSpec struct {`, CronjobSpecStruct) - CheckError("fixing cronjob_types.go", err) + hackutils.CheckError("fixing cronjob_types.go", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_types.go"), @@ -192,19 +178,19 @@ func updateSpec(sp *Sample) { // Foo is an example field of CronJob. Edit cronjob_types.go to remove/update Foo string`+" `"+`json:"foo,omitempty"`+"`", "") - CheckError("fixing cronjob_types.go", err) + hackutils.CheckError("fixing cronjob_types.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_types.go"), `// Important: Run "make" to regenerate code after modifying this file`, CronjobList) - CheckError("fixing cronjob_types.go", err) + hackutils.CheckError("fixing cronjob_types.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_types.go"), `SchemeBuilder.Register(&CronJob{}, &CronJobList{}) }`, ` // +kubebuilder:docs-gen:collapse=Root Object Definitions`) - CheckError("fixing cronjob_types.go", err) + hackutils.CheckError("fixing cronjob_types.go", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_types.go"), @@ -213,7 +199,7 @@ type CronJob struct {`, `// CronJob is the Schema for the cronjobs API type CronJob struct {`+` /* */`) - CheckError("fixing cronjob_types.go", err) + hackutils.CheckError("fixing cronjob_types.go", err) // fix lint err = pluginutil.ReplaceInFile( @@ -221,7 +207,7 @@ type CronJob struct {`+` ` }`, "") - CheckError("fixing cronjob_types.go", err) + hackutils.CheckError("fixing cronjob_types.go", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_types.go"), @@ -229,32 +215,32 @@ type CronJob struct {`+` }`, "") - CheckError("fixing cronjob_types.go", err) + hackutils.CheckError("fixing cronjob_types.go", err) } -func updateAPIStuff(sp *Sample) { +func (sp *Sample) updateAPIStuff() { var err error // fix groupversion_info err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "api/v1/groupversion_info.go"), `limitations under the License. */`, GroupversionIntro) - CheckError("fixing groupversion_info.go", err) + hackutils.CheckError("fixing groupversion_info.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "api/v1/groupversion_info.go"), ` "sigs.k8s.io/controller-runtime/pkg/scheme" )`, GroupversionSchema) - CheckError("fixing groupversion_info.go", err) + hackutils.CheckError("fixing groupversion_info.go", err) } -func updateController(sp *Sample) { +func (sp *Sample) updateController() { var err error err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "internal/controller/cronjob_controller.go"), `limitations under the License. */`, ControllerIntro) - CheckError("fixing cronjob_controller.go", err) + hackutils.CheckError("fixing cronjob_controller.go", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "internal/controller/cronjob_controller.go"), @@ -268,24 +254,24 @@ func updateController(sp *Sample) { batchv1 "tutorial.kubebuilder.io/project/api/v1" )`, ControllerImport) - CheckError("fixing cronjob_controller.go", err) + hackutils.CheckError("fixing cronjob_controller.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "internal/controller/cronjob_controller.go"), `Scheme *runtime.Scheme`, ` Clock`) - CheckError("fixing cronjob_controller.go", err) + hackutils.CheckError("fixing cronjob_controller.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "internal/controller/cronjob_controller.go"), ` Clock }`, ControllerMockClock) - CheckError("fixing cronjob_controller.go", err) + hackutils.CheckError("fixing cronjob_controller.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "internal/controller/cronjob_controller.go"), `// +kubebuilder:rbac:groups=batch.tutorial.kubebuilder.io,resources=cronjobs/finalizers,verbs=update`, ControllerReconcile) - CheckError("fixing cronjob_controller.go", err) + hackutils.CheckError("fixing cronjob_controller.go", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "internal/controller/cronjob_controller.go"), @@ -295,21 +281,21 @@ func updateController(sp *Sample) { return ctrl.Result{}, nil }`, ControllerReconcileLogic) - CheckError("fixing cronjob_controller.go", err) + hackutils.CheckError("fixing cronjob_controller.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "internal/controller/cronjob_controller.go"), `SetupWithManager(mgr ctrl.Manager) error {`, ControllerSetupWithManager) - CheckError("fixing cronjob_controller.go", err) + hackutils.CheckError("fixing cronjob_controller.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "internal/controller/cronjob_controller.go"), `For(&batchv1.CronJob{}).`, ` Owns(&kbatch.Job{}).`) - CheckError("fixing cronjob_controller.go", err) + hackutils.CheckError("fixing cronjob_controller.go", err) } -func updateMain(sp *Sample) { +func (sp *Sample) updateMain() { var err error err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "cmd/main.go"), @@ -317,13 +303,13 @@ func updateMain(sp *Sample) { */`, ` // +kubebuilder:docs-gen:collapse=Apache License`) - CheckError("fixing main.go", err) + hackutils.CheckError("fixing main.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "cmd/main.go"), `// +kubebuilder:scaffold:imports )`, MainBatch) - CheckError("fixing main.go", err) + hackutils.CheckError("fixing main.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "cmd/main.go"), @@ -333,14 +319,14 @@ func updateMain(sp *Sample) { The other thing that's changed is that kubebuilder has added a block calling our CronJob controller's`+" `"+`SetupWithManager`+"`"+` method. */`) - CheckError("fixing main.go", err) + hackutils.CheckError("fixing main.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "cmd/main.go"), `func main() {`, ` /* */`) - CheckError("fixing main.go", err) + hackutils.CheckError("fixing main.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "cmd/main.go"), @@ -350,14 +336,14 @@ CronJob controller's`+" `"+`SetupWithManager`+"`"+` method. }`, ` // +kubebuilder:docs-gen:collapse=old stuff`) - CheckError("fixing main.go", err) + hackutils.CheckError("fixing main.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "cmd/main.go"), `setupLog.Error(err, "unable to create controller", "controller", "CronJob") os.Exit(1) }`, MainEnableWebhook) - CheckError("fixing main.go", err) + hackutils.CheckError("fixing main.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "cmd/main.go"), @@ -365,10 +351,10 @@ CronJob controller's`+" `"+`SetupWithManager`+"`"+` method. os.Exit(1) }`, ` // +kubebuilder:docs-gen:collapse=old stuff`) - CheckError("fixing main.go", err) + hackutils.CheckError("fixing main.go", err) } -func updateMakefile(sp *Sample) { +func (sp *Sample) updateMakefile() { const originalManifestTarget = `.PHONY: manifests manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects. $(CONTROLLER_GEN) rbac:roleName=manager-role crd webhook paths="./..." output:crd:artifacts:config=config/crd/bases @@ -381,13 +367,12 @@ manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and Cust # However, it has a size limit and if the CRD is too big with so many long descriptions as this one it will cause the failure. $(CONTROLLER_GEN) rbac:roleName=manager-role crd:maxDescLen=0 webhook paths="./..." output:crd:artifacts:config=config/crd/bases ` - err := pluginutil.ReplaceInFile(filepath.Join(sp.ctx.Dir, "Makefile"), originalManifestTarget, changedManifestTarget) - CheckError("updating makefile to use maxDescLen=0 in make manifest target", err) + hackutils.CheckError("updating makefile to use maxDescLen=0 in make manifest target", err) } -func updateWebhook(sp *Sample) { +func (sp *Sample) updateWebhook() { var err error err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_webhook.go"), @@ -395,7 +380,7 @@ func updateWebhook(sp *Sample) { */`, ` // +kubebuilder:docs-gen:collapse=Apache License`) - CheckError("fixing cronjob_webhook.go by adding collapse", err) + hackutils.CheckError("fixing cronjob_webhook.go by adding collapse", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_webhook.go"), @@ -409,7 +394,7 @@ func updateWebhook(sp *Sample) { // log is for logging in this package. `, WebhookIntro) - CheckError("fixing cronjob_webhook.go", err) + hackutils.CheckError("fixing cronjob_webhook.go", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_webhook.go"), @@ -418,27 +403,27 @@ func updateWebhook(sp *Sample) { /* Then, we set up the webhook with the manager. */`) - CheckError("fixing cronjob_webhook.go by setting webhook with manager comment", err) + hackutils.CheckError("fixing cronjob_webhook.go by setting webhook with manager comment", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_webhook.go"), `// TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!`, WebhookMarker) - CheckError("fixing cronjob_webhook.go by replacing TODO", err) + hackutils.CheckError("fixing cronjob_webhook.go by replacing TODO", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_webhook.go"), `// TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation.`, "") - CheckError("fixing cronjob_webhook.go by replace TODO to change verbs", err) + hackutils.CheckError("fixing cronjob_webhook.go by replace TODO to change verbs", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_webhook.go"), `// +kubebuilder:webhook:path=/mutate-batch-tutorial-kubebuilder-io-v1-cronjob,mutating=true,failurePolicy=fail,sideEffects=None,groups=batch.tutorial.kubebuilder.io,resources=cronjobs,verbs=create;update,versions=v1,name=mcronjob.kb.io,admissionReviewVersions=v1`, "") - CheckError("fixing cronjob_webhook.go by replacing marker", err) + hackutils.CheckError("fixing cronjob_webhook.go by replacing marker", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_webhook.go"), `// +kubebuilder:webhook:path=/validate-batch-tutorial-kubebuilder-io-v1-cronjob,mutating=false,failurePolicy=fail,sideEffects=None,groups=batch.tutorial.kubebuilder.io,resources=cronjobs,verbs=create;update,versions=v1,name=vcronjob.kb.io,admissionReviewVersions=v1`, "") - CheckError("fixing cronjob_webhook.go validate batch marker", err) + hackutils.CheckError("fixing cronjob_webhook.go validate batch marker", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_webhook.go"), @@ -446,7 +431,7 @@ Then, we set up the webhook with the manager. // TODO(user): fill in your defaulting logic. `, WebhookValidate) - CheckError("fixing cronjob_webhook.go by adding logic", err) + hackutils.CheckError("fixing cronjob_webhook.go by adding logic", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_webhook.go"), @@ -454,7 +439,7 @@ Then, we set up the webhook with the manager. return nil, nil`, ` return nil, r.validateCronJob()`) - CheckError("fixing cronjob_webhook.go by fill in your validation", err) + hackutils.CheckError("fixing cronjob_webhook.go by fill in your validation", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_webhook.go"), @@ -462,7 +447,7 @@ Then, we set up the webhook with the manager. return nil, nil`, ` return nil, r.validateCronJob()`) - CheckError("fixing cronjob_webhook.go by adding validation logic upon object update", err) + hackutils.CheckError("fixing cronjob_webhook.go by adding validation logic upon object update", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_webhook.go"), @@ -472,7 +457,7 @@ Then, we set up the webhook with the manager. // TODO(user): fill in your validation logic upon object deletion. return nil, nil }`, WebhookValidateSpec) - CheckError("fixing cronjob_webhook.go", err) + hackutils.CheckError("fixing cronjob_webhook.go", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "api/v1/cronjob_webhook.go"), @@ -480,16 +465,16 @@ Then, we set up the webhook with the manager. */ }`, `validate anything on deletion. */`) - CheckError("fixing cronjob_webhook.go by adding comments to validate on deletion", err) + hackutils.CheckError("fixing cronjob_webhook.go by adding comments to validate on deletion", err) } -func updateSuiteTest(sp *Sample) { +func (sp *Sample) updateSuiteTest() { var err error err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "internal/controller/suite_test.go"), `limitations under the License. */`, SuiteTestIntro) - CheckError("updating suite_test.go to add license intro", err) + hackutils.CheckError("updating suite_test.go to add license intro", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "internal/controller/suite_test.go"), @@ -498,7 +483,7 @@ func updateSuiteTest(sp *Sample) { `, ` ctrl "sigs.k8s.io/controller-runtime" `) - CheckError("updating suite_test.go to add ctrl import", err) + hackutils.CheckError("updating suite_test.go to add ctrl import", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "internal/controller/suite_test.go"), @@ -507,13 +492,13 @@ var cfg *rest.Config var k8sClient client.Client var testEnv *envtest.Environment `, SuiteTestEnv) - CheckError("updating suite_test.go to add more variables", err) + hackutils.CheckError("updating suite_test.go to add more variables", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "internal/controller/suite_test.go"), `ctx, cancel = context.WithCancel(context.TODO()) `, SuiteTestReadCRD) - CheckError("updating suite_test.go to add text about CRD", err) + hackutils.CheckError("updating suite_test.go to add text about CRD", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "internal/controller/suite_test.go"), @@ -523,7 +508,7 @@ var testEnv *envtest.Environment /* Then, we start the envtest cluster. */`) - CheckError("updating suite_test.go to add text to show where envtest cluster start", err) + hackutils.CheckError("updating suite_test.go to add text to show where envtest cluster start", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "internal/controller/suite_test.go"), @@ -533,7 +518,7 @@ var testEnv *envtest.Environment // +kubebuilder:scaffold:scheme `, SuiteTestAddSchema) - CheckError("updating suite_test.go to add schema", err) + hackutils.CheckError("updating suite_test.go to add schema", err) err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "internal/controller/suite_test.go"), @@ -542,7 +527,7 @@ var testEnv *envtest.Environment Expect(err).NotTo(HaveOccurred()) Expect(k8sClient).NotTo(BeNil()) `, SuiteTestDescription) - CheckError("updating suite_test.go for test description", err) + hackutils.CheckError("updating suite_test.go for test description", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "internal/controller/suite_test.go"), @@ -554,62 +539,54 @@ var _ = AfterSuite(func() { Expect(err).NotTo(HaveOccurred()) }) `, SuiteTestCleanup) - CheckError("updating suite_test.go to cleanup tests", err) + hackutils.CheckError("updating suite_test.go to cleanup tests", err) } -func updateKustomization(sp *Sample) { +func (sp *Sample) updateKustomization() { var err error err = pluginutil.UncommentCode( filepath.Join(sp.ctx.Dir, "config/default/kustomization.yaml"), `#- ../certmanager`, `#`) - CheckError("fixing default/kustomization", err) + hackutils.CheckError("fixing default/kustomization", err) err = pluginutil.UncommentCode( filepath.Join(sp.ctx.Dir, "config/default/kustomization.yaml"), `#- path: webhookcainjection`, `#`) - CheckError("fixing default/kustomization", err) + hackutils.CheckError("fixing default/kustomization", err) err = pluginutil.UncommentCode( filepath.Join(sp.ctx.Dir, "config/default/kustomization.yaml"), `#- ../prometheus`, `#`) - CheckError("fixing default/kustomization", err) + hackutils.CheckError("fixing default/kustomization", err) err = pluginutil.UncommentCode( filepath.Join(sp.ctx.Dir, "config/default/kustomization.yaml"), DefaultKustomization, `#`) - CheckError("fixing default/kustomization", err) + hackutils.CheckError("fixing default/kustomization", err) err = pluginutil.UncommentCode( filepath.Join(sp.ctx.Dir, "config/crd/kustomization.yaml"), `#- path: patches/cainjection_in_cronjobs.yaml`, `#`) - CheckError("fixing crd/kustomization", err) + hackutils.CheckError("fixing crd/kustomization", err) } -func updateExample(sp *Sample) { +func (sp *Sample) updateExample() { var err error // samples/batch_v1_cronjob err = pluginutil.InsertCode( filepath.Join(sp.ctx.Dir, "config/samples/batch_v1_cronjob.yaml"), `spec:`, CronjobSample) - CheckError("fixing samples/batch_v1_cronjob.yaml", err) + hackutils.CheckError("fixing samples/batch_v1_cronjob.yaml", err) err = pluginutil.ReplaceInFile( filepath.Join(sp.ctx.Dir, "config/samples/batch_v1_cronjob.yaml"), `# TODO(user): Add fields here`, "") - CheckError("fixing samples/batch_v1_cronjob.yaml", err) + hackutils.CheckError("fixing samples/batch_v1_cronjob.yaml", err) } -func addControllerTest(sp *Sample) { +func (sp *Sample) addControllerTest() { var fs = afero.NewOsFs() err := afero.WriteFile(fs, filepath.Join(sp.ctx.Dir, "internal/controller/cronjob_controller_test.go"), []byte(ControllerTest), 0600) - CheckError("adding cronjob_controller_test", err) -} - -// CheckError will exit with exit code 1 when err is not nil. -func CheckError(msg string, err error) { - if err != nil { - log.Errorf("error %s: %s", msg, err) - os.Exit(1) - } + hackutils.CheckError("adding cronjob_controller_test", err) } diff --git a/hack/docs/internal/getting-started/generate_getting_started.go b/hack/docs/internal/getting-started/generate_getting_started.go index 48167e8c807..fb327405579 100644 --- a/hack/docs/internal/getting-started/generate_getting_started.go +++ b/hack/docs/internal/getting-started/generate_getting_started.go @@ -17,9 +17,10 @@ limitations under the License. package gettingstarted import ( - "os" "os/exec" + hackutils "sigs.k8s.io/kubebuilder/v4/hack/docs/utils" + log "github.com/sirupsen/logrus" "sigs.k8s.io/kubebuilder/v4/test/e2e/utils" ) @@ -30,7 +31,7 @@ type Sample struct { func NewSample(binaryPath, samplePath string) Sample { log.Infof("Generating the sample context of getting-started...") - ctx := newSampleContext(binaryPath, samplePath, "GO111MODULE=on") + ctx := hackutils.NewSampleContext(binaryPath, samplePath, "GO111MODULE=on") return Sample{&ctx} } @@ -38,20 +39,6 @@ func (sp *Sample) UpdateTutorial() { log.Println("TODO: update tutorial") } -func newSampleContext(binaryPath string, samplePath string, env ...string) utils.TestContext { - cmdContext := &utils.CmdContext{ - Env: env, - Dir: samplePath, - } - - testContext := utils.TestContext{ - CmdContext: cmdContext, - BinaryName: binaryPath, - } - - return testContext -} - // Prepare the Context for the sample project func (sp *Sample) Prepare() { log.Infof("Destroying directory for getting-started sample project") @@ -60,7 +47,7 @@ func (sp *Sample) Prepare() { log.Infof("Refreshing tools and creating directory...") err := sp.ctx.Prepare() - CheckError("Creating directory for sample project", err) + hackutils.CheckError("Creating directory for sample project", err) } func (sp *Sample) GenerateSampleProject() { @@ -71,7 +58,7 @@ func (sp *Sample) GenerateSampleProject() { "--license", "apache2", "--owner", "The Kubernetes authors", ) - CheckError("Initializing the getting started project", err) + hackutils.CheckError("Initializing the getting started project", err) log.Infof("Adding a new config type") err = sp.ctx.CreateAPI( @@ -85,27 +72,19 @@ func (sp *Sample) GenerateSampleProject() { "--plugins", "deploy-image/v1-alpha", "--make=false", ) - CheckError("Creating the API", err) + hackutils.CheckError("Creating the API", err) } func (sp *Sample) CodeGen() { cmd := exec.Command("make", "manifests") _, err := sp.ctx.Run(cmd) - CheckError("Failed to run make manifests for getting started tutorial", err) + hackutils.CheckError("Failed to run make manifests for getting started tutorial", err) cmd = exec.Command("make", "all") _, err = sp.ctx.Run(cmd) - CheckError("Failed to run make all for getting started tutorial", err) + hackutils.CheckError("Failed to run make all for getting started tutorial", err) cmd = exec.Command("go", "mod", "tidy") _, err = sp.ctx.Run(cmd) - CheckError("Failed to run go mod tidy all for getting started tutorial", err) -} - -// CheckError will exit with exit code 1 when err is not nil. -func CheckError(msg string, err error) { - if err != nil { - log.Errorf("error %s: %s", msg, err) - os.Exit(1) - } + hackutils.CheckError("Failed to run go mod tidy all for getting started tutorial", err) } diff --git a/hack/docs/utils/utils.go b/hack/docs/utils/utils.go new file mode 100644 index 00000000000..0c388f5c10c --- /dev/null +++ b/hack/docs/utils/utils.go @@ -0,0 +1,47 @@ +/* +Copyright 2024 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 utils + +import ( + "os" + + log "github.com/sirupsen/logrus" + "sigs.k8s.io/kubebuilder/v4/test/e2e/utils" +) + +// CheckError will exit with exit code 1 when err is not nil. +func CheckError(msg string, err error) { + if err != nil { + log.Errorf("error %s: %s", msg, err) + os.Exit(1) + } +} + +// NewSampleContext return a context for the Sample +func NewSampleContext(binaryPath string, samplePath string, env ...string) utils.TestContext { + cmdContext := &utils.CmdContext{ + Env: env, + Dir: samplePath, + } + + testContext := utils.TestContext{ + CmdContext: cmdContext, + BinaryName: binaryPath, + } + + return testContext +}