go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/lucicfg/gens.go (about)

     1  // Copyright 2019 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package lucicfg
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"go.starlark.net/starlark"
    21  
    22  	"go.chromium.org/luci/common/errors"
    23  	"go.chromium.org/luci/starlark/builtins"
    24  )
    25  
    26  // generators is a list of registered generator callbacks.
    27  //
    28  // It lives in State. Generators are executed sequentially after all Starlark
    29  // code is loaded. They examine the state and generate configs based on it.
    30  type generators struct {
    31  	gen        []starlark.Callable
    32  	runningNow bool // true while inside 'call'
    33  }
    34  
    35  // add registers a new generator callback.
    36  func (g *generators) add(cb starlark.Callable) error {
    37  	if g.runningNow {
    38  		return fmt.Errorf("can't add a generator while already running them")
    39  	}
    40  	g.gen = append(g.gen, cb)
    41  	return nil
    42  }
    43  
    44  // call calls all registered callbacks sequentially, collecting all errors.
    45  func (g *generators) call(th *starlark.Thread, ctx *genCtx) (errs errors.MultiError) {
    46  	if g.runningNow {
    47  		return errors.MultiError{
    48  			fmt.Errorf("can't call generators while they are already running"),
    49  		}
    50  	}
    51  	g.runningNow = true
    52  	defer func() { g.runningNow = false }()
    53  
    54  	fc := builtins.GetFailureCollector(th)
    55  
    56  	for _, cb := range g.gen {
    57  		if fc != nil {
    58  			fc.Clear()
    59  		}
    60  		if _, err := starlark.Call(th, cb, starlark.Tuple{ctx}, nil); err != nil {
    61  			if fc != nil && fc.LatestFailure() != nil {
    62  				// Prefer this error, it has custom stack trace.
    63  				errs = append(errs, fc.LatestFailure())
    64  			} else {
    65  				errs = append(errs, err)
    66  			}
    67  		}
    68  	}
    69  	return
    70  }
    71  
    72  func init() {
    73  	// add_generator(cb) registers a callback that is called at the end of the
    74  	// execution to generate or mutate produced configs.
    75  	declNative("add_generator", func(call nativeCall) (starlark.Value, error) {
    76  		var cb starlark.Callable
    77  		if err := call.unpack(1, &cb); err != nil {
    78  			return nil, err
    79  		}
    80  		return starlark.None, call.State.generators.add(cb)
    81  	})
    82  
    83  	// call_generators(ctx) calls all registered generators, useful in tests.
    84  	declNative("call_generators", func(call nativeCall) (starlark.Value, error) {
    85  		var ctx *genCtx
    86  		if err := call.unpack(1, &ctx); err != nil {
    87  			return nil, err
    88  		}
    89  		switch errs := call.State.generators.call(call.Thread, ctx); {
    90  		case len(errs) == 0:
    91  			return starlark.None, nil
    92  		case len(errs) == 1:
    93  			return starlark.None, errs[0]
    94  		default:
    95  			return starlark.None, errs
    96  		}
    97  	})
    98  }