How to walk list definitions (GO API) #2570
-
|
Hello, I would like to extract definitions that are present in a list for custom schema generation. I am walking a schema defined in cue and extracting the definitions, putting them into go structs, however when I reach a list I cannot extract the definitions that are used in it. Here's an example: package main
import (
"fmt"
"cuelang.org/go/cue"
"cuelang.org/go/cue/cuecontext"
)
const input = `
a: {
i: int
j: int | *i
k: [...#B]
}
#C: {
cLevel: int
}
#B: {
name: string | *"UNDEFINED"
test: string
next: #C
}
`
func main() {
c := cuecontext.New()
// d, _ := os.ReadFile("value.cue")
// val := c.CompileBytes(d)
val := c.CompileString(input)
// before (pre-order) traversal
preprinter := func(v cue.Value) bool {
fmt.Printf("%v\n", v)
return true
}
// after (post-order) traversal
cnt := 0
postcounter := func(v cue.Value) {
cnt++
}
Walk(val, preprinter, postcounter, customOptions...)
}
// Walk is an alternative to cue.Value.Walk which handles more field types
// You can customize this with your own options
func Walk(v cue.Value, before func(cue.Value) bool, after func(cue.Value), options ...cue.Option) {
lbl, _ := v.Label()
fmt.Println("-------------------------------------------------------------")
// call before and possibly stop recursion
if before != nil && !before(v) {
return
}
// possibly recurse
switch v.IncompleteKind() {
case cue.StructKind:
fmt.Println("Value is struct: ", lbl)
if options == nil {
options = defaultOptions
}
s, _ := v.Fields(options...)
for s.Next() {
Walk(s.Value(), before, after, options...)
}
case cue.ListKind:
fmt.Println("Value is List: ", lbl)
l, _ := v.List()
for l.Next() {
fmt.Println("Walking list")
Walk(l.Value(), before, after, options...)
}
default:
fmt.Println("Value is basic type: ", lbl)
}
if after != nil {
after(v)
}
}
// Cue's default
var defaultOptions = []cue.Option{
cue.Attributes(true),
cue.Concrete(false),
cue.Definitions(true),
cue.DisallowCycles(false),
cue.Docs(true),
cue.Hidden(false),
// The following are not set
// nor do they have a bool arg
// cue.Final(),
// cue.Raw(),
// cue.Schema(),
}
// Our custom options
var customOptions = []cue.Option{
cue.Definitions(true),
cue.Hidden(true),
cue.Optional(true),
}If you run this, you'll notice that "Walking list" never prints, I can't seem to inspect the contents of the list. How might I go about inspecting the contents of a list and extracting which definitions are present in it? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
I seem to be able to recover a Value from within the list using: typ := v.LookupPath(cue.MakePath(cue.AnyIndex))
refV, refP := typ.ReferencePath()refP contins the path to the definition relative to refV. From this I can extract the definition |
Beta Was this translation helpful? Give feedback.
I seem to be able to recover a Value from within the list using:
refP contins the path to the definition relative to refV. From this I can extract the definition