cue-lang / docs-and-content

A place to discuss, plan, and track documentation on cuelang.org
6 stars 1 forks source link

How to use `cue/load` to load CUE files from memory #183

Open jpluscplusm opened 1 month ago

jpluscplusm commented 1 month ago

From https://cuelang.slack.com/archives/C012UU8B72M/p1721323828896049

go mod tidy
go run .
cmp stdout stdout.golden

-- go.mod --
module mod.example

go 1.22.3

require cuelang.org/go v0.9.2

-- main.go --
package main

import (
    "fmt"
    "log"
    "os"
    "path/filepath"

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

func main() {
    td, err := os.MkdirTemp("", "")
    if err != nil {
        log.Fatal(err)
    }
    defer os.RemoveAll(td)

    overlay := map[string]load.Source{
        // cue.mod/module.cue file
        filepath.Join(td, "cue.mod", "module.cue"): load.FromString(`
module: "mod.example"
language: version: "v0.9.2"
    `),

        // File in root
        filepath.Join(td, "a.cue"): load.FromString(`
package a

a: 5
    `),

        // File in subdirectory (that does not exist)
        filepath.Join(td, "b", "b.cue"): load.FromString(`
package a

b: 4
    `),
    }

    ctx := cuecontext.New()
    bis := load.Instances([]string{".", "./b"}, &load.Config{
        Dir:     td,
        Overlay: overlay,
    })
    for _, bi := range bis {
        v := ctx.BuildInstance(bi)
        fmt.Printf("%s: %v\n", bi.ImportPath, v)
    }
}
-- stdout.golden --
mod.example@v0:a: {
    a: 5
}
mod.example/b@v0:a: {
    a: 5
    b: 4
}

"The root directory needs to exist on disk, yes, but none of its contents do. So assuming you can use a temporary directory in this way, then nothing actually needs to be written to disk."