Printing Cue



CUE supports the fmt.Printf modifiers for when you want to quickly print values. For fine grained control when printing, you can use the cue/format package.

Printing with go/fmt

print.go

package main

import (
	"fmt"

	"cuelang.org/go/cue"
	"cuelang.org/go/cue/cuecontext"
)

const val = `
i: int
s: string
t: [string]: string
_h: "hidden"
#d: foo: "bar"
`

func main() {
	var (
		c *cue.Context
		v cue.Value
	)

	// create a context
	c = cuecontext.New()

	// compile some CUE into a Value
	v = c.CompileString(val)

	// print the value
	fmt.Printf("// %%v\n%v\n\n// %%# v\n%# v\n", v, v)
}

go run print.go

// %v
{
	i: int
	s: string
	t: {}
}

// %# v
i: int
s: string
t: {
	[string]: string
}
_h: "hidden"
#d: {
	foo: "bar"
}

Printing with cue/format

When we run cue eval and cue def, we have more options to control what gets printed through the flags. Those flags map onto the cue.Option type which is supplied to cue.Value.Syntax, a function that returns the Abstract Syntax Tree (AST) for the value. We then use Cue’s format.Node to pretty print a Cue AST.

format.go

package main

import (
	"fmt"

	"cuelang.org/go/cue"
	"cuelang.org/go/cue/cuecontext"
	"cuelang.org/go/cue/format"
)

const val = `
i: int
s: string
t: [string]: string
_h: "hidden"
#d: foo: "bar"
`

func main() {
	var (
		c *cue.Context
		v cue.Value
	)

	// create a context
	c = cuecontext.New()

	// compile some CUE into a Value
	v = c.CompileString(val)

	// Generate an AST
	//   try out different options
	syn := v.Syntax(
		cue.Final(),         // close structs and lists
		cue.Concrete(false), // allow incomplete values
		cue.Definitions(false),
		cue.Hidden(true),
		cue.Optional(true),
		cue.Attributes(true),
		cue.Docs(true),
	)

	// Pretty print the AST, returns ([]byte, error)
	bs, _ := format.Node(
		syn,
		// format.TabIndent(false),
		// format.UseSpaces(2),
	)

	// print to stdout
	fmt.Println(string(bs))
}

go run format.go

{
	i: int
	s: string
	t: {}
	_h: "hidden"
	#d: {
		foo: "bar"
	}
}
cue.Value.Syntax - function for returning AST
cue.Option - options for Syntax (and other funcs)
cue/format.Node - function for pretty-printing an AST
We'll never share your email with anyone else.
2022 Hofstadter, Inc