go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/cipkg/base/actions/command.go (about)

     1  // Copyright 2023 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 actions
    16  
    17  import (
    18  	"fmt"
    19  	"regexp"
    20  
    21  	"go.chromium.org/luci/cipkg/core"
    22  )
    23  
    24  // ActionCommandTransformer is the default transformer for core.ActionCommand.
    25  func ActionCommandTransformer(a *core.ActionCommand, deps []Package) (*core.Derivation, error) {
    26  	drv := &core.Derivation{
    27  		Args: a.Args,
    28  		Env:  a.Env,
    29  	}
    30  
    31  	// Render templates
    32  	dirs := make(map[string]string)
    33  	for _, d := range deps {
    34  		dirs[d.Action.Name] = d.Handler.OutputDirectory()
    35  	}
    36  	if err := renderDerivation(dirs, drv); err != nil {
    37  		return nil, err
    38  	}
    39  
    40  	return drv, nil
    41  }
    42  
    43  func renderDerivation(vals map[string]string, drv *core.Derivation) (err error) {
    44  	drv.Args, err = renderAll(drv.Args, vals)
    45  	if err != nil {
    46  		return
    47  	}
    48  	drv.Env, err = renderAll(drv.Env, vals)
    49  	if err != nil {
    50  		return err
    51  	}
    52  	return nil
    53  }
    54  
    55  func renderAll(raw []string, vals map[string]string) (ret []string, err error) {
    56  	for _, r := range raw {
    57  		re := regexp.MustCompile(`{{.+?}}`)
    58  		rendered := re.ReplaceAllStringFunc(r, func(s string) string {
    59  			// removes "{{." and "}}" from {{.something}}
    60  			if s[2] != '.' {
    61  				err = fmt.Errorf("failed to render %s: use {{.key}} to reference value", r)
    62  				return "PANIC"
    63  			}
    64  
    65  			if v, ok := vals[s[3:len(s)-2]]; ok {
    66  				return v
    67  			}
    68  			err = fmt.Errorf("failed to render %s: unknown key %s", r, s)
    69  			return "PANIC"
    70  		})
    71  		if err != nil {
    72  			return
    73  		}
    74  		ret = append(ret, rendered)
    75  	}
    76  	return ret, nil
    77  }