github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/builder/build.go (about)

     1  package builder
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"runtime"
     7  
     8  	"github.com/emcfarlane/larking/starlib"
     9  	"github.com/emcfarlane/larking/starlib/starlarkrule"
    10  	"github.com/emcfarlane/larking/starlib/starlarkthread"
    11  	"github.com/go-logr/logr"
    12  	"go.starlark.net/starlark"
    13  )
    14  
    15  type buildOptions struct {
    16  	buildP int
    17  	run    bool
    18  }
    19  
    20  var defaultBuildOptions = buildOptions{
    21  	buildP: runtime.GOMAXPROCS(0),
    22  	run:    true,
    23  }
    24  
    25  // BuildOption
    26  type BuildOption func(*buildOptions)
    27  
    28  func Build(ctx context.Context, label string, opts ...BuildOption) (*starlarkrule.Action, error) {
    29  	bldOpts := defaultBuildOptions
    30  	for _, opt := range opts {
    31  		opt(&bldOpts)
    32  	}
    33  	log := logr.FromContextOrDiscard(ctx)
    34  
    35  	dir := "" // todo?
    36  	l, err := starlarkrule.ParseRelativeLabel("file://./?metadata=skip", dir)
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  
    41  	b, err := starlarkrule.NewBuilder(l)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  
    46  	globals := starlib.NewGlobals()
    47  	loader := starlib.NewLoader(globals)
    48  	resources := starlarkthread.ResourceStore{} // resources
    49  	defer resources.Close()
    50  
    51  	bktURL := l.BucketURL()
    52  	threads := make([]*starlark.Thread, bldOpts.buildP)
    53  	for i := 0; i < bldOpts.buildP; i++ {
    54  		thread := &starlark.Thread{
    55  			Name: bktURL,
    56  			Load: loader.Load,
    57  			Print: func(thread *starlark.Thread, msg string) {
    58  				fmt.Println("MSG!", msg)
    59  				log.Info(msg, "name", thread.Name)
    60  			},
    61  		}
    62  		starlarkthread.SetResourceStore(thread, &resources)
    63  		starlarkthread.SetContext(thread, ctx)
    64  		threads[i] = thread
    65  	}
    66  	thread := threads[0]
    67  
    68  	l, err = l.Parse(label)
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  
    73  	action, err := b.Build(thread, l)
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  
    78  	if bldOpts.run {
    79  		b.Run(action, threads...)
    80  	}
    81  	return action, nil
    82  }