Skip to content

Instantly share code, notes, and snippets.

@richardpeng
Last active July 9, 2023 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardpeng/1bb97ccbf8b6508c298b3de56b55a7ac to your computer and use it in GitHub Desktop.
Save richardpeng/1bb97ccbf8b6508c298b3de56b55a7ac to your computer and use it in GitHub Desktop.
Dynamic CUE

Example Usages

Enable feature1

go run ./fill.go "features=[\"feature1\"]" 

Output:

{
        features: ["feature1"]
        application: {
                feature1: "enabled"
        }
}

Insert arbitrary data

go run ./fill.go "arbitrary=\"data\""

Output:

{
        features: [...string]
        arbitrary: "data"
        application: {}
}
package main
import (
"list"
)
features: [...string]
application: {}
if list.Contains(features, "feature1") {
application: feature1: "enabled"
}
if list.Contains(features, "feature2") {
application: feature2: "enabled"
}
package main
import (
"cuelang.org/go/cue"
"cuelang.org/go/cue/cuecontext"
"cuelang.org/go/cue/load"
"fmt"
"os"
"strings"
)
// Usage:
func main() {
// We need a cue.Context for building after loading
ctx := cuecontext.New()
params := os.Args[1:]
// Load Cue files into Cue build.Instances slice
// the second arg is a configuration object, we'll see this later
bis := load.Instances([]string{"."}, nil)
bi := bis[0]
// check for errors on the instance
// these are typically parsing errors
if bi.Err != nil {
fmt.Println("Error during load:", bi.Err)
os.Exit(1)
}
// Use cue.Context.BuildInstance to turn
// a build.Instance into a cue.Value
value := ctx.BuildInstance(bi)
if value.Err() != nil {
fmt.Println("Error during build:", value.Err())
os.Exit(1)
}
for _, arg := range params {
split := strings.Split(arg, "=")
path := split[0]
argValue := split[1]
unmarshal := ctx.CompileString(argValue)
err := unmarshal.Err()
if err != nil {
fmt.Println("Unable to compile arg:", err)
os.Exit(1)
}
value = value.FillPath(cue.ParsePath(path), unmarshal)
err = value.Err()
if value.Err() != nil {
fmt.Println("Error during filling:", err)
os.Exit(1)
}
}
// Validate the value
err := value.Validate()
if err != nil {
fmt.Println("Error during validation:", err)
os.Exit(1)
}
// Print the value
fmt.Println(value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment