This guide demonstrates how to generate CUE from Go types defined in some dependency of a Go module.
Initialize Go and CUE modules
Create a Go module, or use an existing one if that’s more suitable for your situation:
$ go mod init go.example
...
Create a CUE module if you don’t already have one:
$ cue mod init cue.example
Declare a Go dependency
If your Go doesn’t already depend on the module containing the Go types you’re interested in, add it as a dependency.
Create a Go file to signal the required package to the go
command.
Our example depends on a Kubernetes package:
//go:build deps
// +build deps
package deps
import _ "k8s.io/api/apps/v1"
Add a dependency on a specific version of the target Go package, and tidy the main module:
$ go get k8s.io/api/apps/v1@v0.23.4 # "@latest" would also work.
...
$ go mod tidy
...
Generate CUE from Go
Use the cue
command to generate CUE from the target Go package:
$ cue get go k8s.io/api/apps/v1
Inspect the CUE packages generated in cue.mod/gen
:
$ tree -d cue.mod/gen
cue.mod/gen
└── k8s.io
├── api
│ ├── apps
│ │ └── v1
│ └── core
│ └── v1
└── apimachinery
└── pkg
├── api
...
More CUE packages are generated than just the target. These are dependencies of the target package.
Test the generated CUE
Use the generated code in a CUE package:
package example
import (
core "k8s.io/api/core/v1"
apps "k8s.io/api/apps/v1"
)
service: [string]: core.#Service
deployment: [string]: apps.#Deployment
daemonSet: [string]: apps.#DaemonSet
statefulSet: [string]: apps.#StatefulSet
Export an empty configuration to confirm that everything works:
$ cue export --out yaml
service: {}
deployment: {}
daemonSet: {}
statefulSet: {}
Related content
- Issue #2865 tracks the plans for CUE to support finding well-known types (such as the Kubernetes example used above) at a well-known location, without having to import them manually.
- How-to Guide: Generating CUE from local Go code