Skip to content
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

Generate CRD in Go code #1097

Open
chinglinwen opened this issue Nov 26, 2024 · 1 comment
Open

Generate CRD in Go code #1097

chinglinwen opened this issue Nov 26, 2024 · 1 comment

Comments

@chinglinwen
Copy link

CRD in Go code

I'd like to have crd write in go, and create crd when main.go runs, similar to this approach: https://github1s.com/k3s-io/helm-controller/blob/master/pkg/crd/crds.go

package crd

import (
	v1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1"
	"github.com/rancher/wrangler/v3/pkg/crd"
)

func List() []crd.CRD {
	chart := crd.NamespacedType("HelmChart.helm.cattle.io/v1").
		WithSchemaFromStruct(v1.HelmChart{}).
		WithColumn("Job", ".status.jobName").
		WithColumn("Chart", ".spec.chart").
		WithColumn("TargetNamespace", ".spec.targetNamespace").
		WithColumn("Version", ".spec.version").
		WithColumn("Repo", ".spec.repo").
		WithColumn("HelmVersion", ".spec.helmVersion").
		WithColumn("Bootstrap", ".spec.bootstrap").
		WithStatus()

	config := crd.NamespacedType("HelmChartConfig.helm.cattle.io/v1").
		WithSchemaFromStruct(v1.HelmChartConfig{})

	return []crd.CRD{chart, config}
}

https://github1s.com/k3s-io/helm-controller/blob/master/main.go#L60-L61

	ctx := cmd.Context()
	if err := wcrd.Create(ctx, clientConfig, crd.List()); err != nil {
		return err
	}

https://pkg.go.dev/github.com/rancher/wrangler/v3/pkg/crd

https://github.com/rancher/wrangler/blob/v3.1.0/pkg/crd/print.go#L57-L64

func Create(ctx context.Context, cfg *rest.Config, crds []CRD) error {
	factory, err := NewFactoryFromClient(cfg)
	if err != nil {
		return err
	}

	return factory.BatchCreateCRDs(ctx, crds...).BatchWait()
}

this way, it can be a lot simpler with a single deployment resource to apply.

would like kubebuilder to scaffold to generate such go file, and glue by main.go
say a file sit aside with types.go, maybe name: ${types}_crd_generated.go

@sbueringer
Copy link
Member

This seems like a simple builder on top of the crd go type?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants