github.com/octohelm/cuemod@v0.9.4/pkg/cuemodx/eval.go (about)

     1  package cuemodx
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  
     8  	"cuelang.org/go/cue/load"
     9  	cueparser "cuelang.org/go/cue/parser"
    10  	"github.com/octohelm/cuemod/pkg/cuemod"
    11  	"github.com/octohelm/cuemod/pkg/cuex"
    12  )
    13  
    14  func EvalContextWithPatches(ctx context.Context, r *cuemod.Context, inputs []string, options ...cuex.EvalOptionFunc) ([]byte, error) {
    15  	files := make([]string, 0)
    16  	inputSources := map[string]load.Source{}
    17  
    18  	c := 0
    19  	for i := range inputs {
    20  		input := inputs[i]
    21  		if input == "" {
    22  			continue
    23  		}
    24  
    25  		var s load.Source
    26  		if input[0] == '{' {
    27  			s = load.FromString(input)
    28  			input = fmt.Sprintf("./input_____%d.cue", i)
    29  		} else {
    30  			info, err := os.Stat(input)
    31  			if err != nil {
    32  				return nil, err
    33  			}
    34  
    35  			if info.IsDir() {
    36  				s = load.FromString(fmt.Sprintf(`
    37  import t "%s"
    38  t
    39  `, r.CompletePath(input)))
    40  				input = fmt.Sprintf("./input_%d.cue", i)
    41  			} else {
    42  				src, err := os.ReadFile(input)
    43  				if err != nil {
    44  					return nil, err
    45  				}
    46  				f, err := cueparser.ParseFile(input, src)
    47  				if err != nil {
    48  					return nil, err
    49  				}
    50  				s = load.FromFile(f)
    51  			}
    52  		}
    53  
    54  		input = r.CompletePath(input)
    55  
    56  		files = append(files, input)
    57  		inputSources[input] = s
    58  
    59  		c++
    60  	}
    61  
    62  	inst := r.Build(ctx, files, cuemod.OptOverlay(inputSources))
    63  
    64  	results, err := cuex.Eval(inst, options...)
    65  	if err != nil {
    66  		return nil, err
    67  	}
    68  	return results, nil
    69  }
    70  
    71  func EvalContext(ctx context.Context, r *cuemod.Context, filename string, options ...cuex.EvalOptionFunc) ([]byte, error) {
    72  	filename = r.CompletePath(filename)
    73  	inst := r.Build(ctx, []string{filename})
    74  	results, err := cuex.Eval(inst, options...)
    75  	if err != nil {
    76  		return nil, err
    77  	}
    78  	return results, nil
    79  }