github.com/octohelm/cuekit@v0.0.0-20240424021256-e7df8d743066/pkg/cuecontext/config.go (about)

     1  package cuecontext
     2  
     3  import (
     4  	"os"
     5  
     6  	"path/filepath"
     7  
     8  	"cuelang.org/go/cue/load"
     9  	"github.com/pkg/errors"
    10  
    11  	"github.com/octohelm/cuekit/pkg/mod/modregistry"
    12  	"github.com/octohelm/cuekit/pkg/mod/module"
    13  )
    14  
    15  type Config = load.Config
    16  
    17  type OptionFunc = func(c *ctx)
    18  
    19  func WithRoot(dir string) OptionFunc {
    20  	return func(c *ctx) {
    21  		c.Dir = dir
    22  	}
    23  }
    24  
    25  func WithModule(m *module.Module) OptionFunc {
    26  	return func(c *ctx) {
    27  		c.Module = m
    28  	}
    29  }
    30  
    31  type ctx struct {
    32  	*Config
    33  	*module.Module
    34  }
    35  
    36  func NewConfig(optionFns ...OptionFunc) (*Config, error) {
    37  	c := &ctx{
    38  		Config: &Config{},
    39  	}
    40  	for i := range optionFns {
    41  		optionFns[i](c)
    42  	}
    43  
    44  	dir, err := ResolveAbsDir(c.Dir)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	c.Dir = dir
    49  
    50  	if _, err := os.Stat(c.Dir); err != nil {
    51  		return nil, errors.Wrapf(err, "%s", c.Dir)
    52  	}
    53  
    54  	if c.Module == nil {
    55  		c.Module = &module.Module{}
    56  	}
    57  
    58  	c.Module.SourceLoc = module.SourceLocOfOSDir(c.Dir)
    59  
    60  	r, err := modregistry.NewRegistry(c.Module)
    61  	if err != nil {
    62  		return nil, err
    63  	}
    64  
    65  	c.Registry = r
    66  
    67  	return c.Config, nil
    68  }
    69  
    70  func ResolveAbsDir(dir string) (string, error) {
    71  	if dir == "" || !filepath.IsAbs(dir) {
    72  		cwd, err := os.Getwd()
    73  		if err != nil {
    74  			return "", err
    75  		}
    76  
    77  		if dir != "" {
    78  			return filepath.Join(cwd, dir), nil
    79  		}
    80  		return cwd, nil
    81  	}
    82  
    83  	return dir, nil
    84  }