github.com/joomcode/cue@v0.4.4-0.20221111115225-539fe3512047/cue/registry/registry.go (about)

     1  package registry
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  
     8  	starjson "go.starlark.net/lib/json"
     9  	"go.starlark.net/starlark"
    10  )
    11  
    12  type Registry struct {
    13  	functions map[string]*starlark.Function
    14  }
    15  
    16  // NewRegistry imports functions from *.star
    17  func NewRegistry(starlarkCodePath string) (*Registry, error) {
    18  	if err := assertFileExists(starlarkCodePath); err != nil {
    19  		return nil, err
    20  	}
    21  
    22  	thread := &starlark.Thread{Name: "functions extraction"}
    23  	predeclared := starlark.StringDict{
    24  		"json":     starjson.Module,
    25  		//"validate": starlark.NewBuiltin("validate", validateSchema),
    26  	}
    27  
    28  	globals, err := starlark.ExecFile(thread, starlarkCodePath, nil, predeclared)
    29  	if err != nil {
    30  		if evalErr, ok := err.(*starlark.EvalError); ok {
    31  			log.Fatal(evalErr.Backtrace())
    32  		}
    33  		return nil, err
    34  	}
    35  
    36  	functions := make(map[string]*starlark.Function)
    37  	for k, v := range globals {
    38  		if function, isFunction := v.(*starlark.Function); isFunction {
    39  			functions[k] = function
    40  		}
    41  	}
    42  	return &Registry{functions}, nil
    43  }
    44  
    45  func (r *Registry) Function(name string) (*starlark.Function, error) {
    46  	f, found := r.functions[name]
    47  	if !found || f == nil {
    48  		return nil, fmt.Errorf("unregistered starlark function: %s", name)
    49  	}
    50  	return f, nil
    51  }
    52  
    53  func assertFileExists(path string) error {
    54  	info, err := os.Stat(path)
    55  	if err != nil {
    56  		return err
    57  	}
    58  	if info.IsDir() {
    59  		return fmt.Errorf("%s is a directory", path)
    60  	}
    61  	return nil
    62  }