github.com/grafana/tanka@v0.26.1-0.20240506093700-c22cfc35c21a/pkg/jsonnet/implementations/binary/impl.go (about)

     1  package binary
     2  
     3  import (
     4  	"fmt"
     5  	"os/exec"
     6  	"strconv"
     7  
     8  	"github.com/grafana/tanka/pkg/jsonnet/implementations/types"
     9  )
    10  
    11  type JsonnetBinaryRunner struct {
    12  	binPath string
    13  	args    []string
    14  }
    15  
    16  func (r *JsonnetBinaryRunner) EvaluateAnonymousSnippet(snippet string) (string, error) {
    17  	cmd := exec.Command(r.binPath, append(r.args, "-e", snippet)...)
    18  
    19  	out, err := cmd.CombinedOutput()
    20  	if err != nil {
    21  		return "", fmt.Errorf("error running anonymous snippet: %w\n%s", err, string(out))
    22  	}
    23  
    24  	return string(out), nil
    25  }
    26  
    27  func (r *JsonnetBinaryRunner) EvaluateFile(filename string) (string, error) {
    28  	cmd := exec.Command(r.binPath, append(r.args, filename)...)
    29  
    30  	out, err := cmd.CombinedOutput()
    31  	if err != nil {
    32  		return "", fmt.Errorf("error running file %s: %w\n%s", filename, err, string(out))
    33  	}
    34  
    35  	return string(out), nil
    36  }
    37  
    38  // JsonnetBinaryImplementation runs Jsonnet in a subprocess. It doesn't support native functions.
    39  // The interface of the binary has to compatible with the official Jsonnet CLI.
    40  // It has to support the following flags:
    41  // -J <path> for specifying import paths
    42  // --ext-code <name>=<value> for specifying external variables
    43  // --tla-code <name>=<value> for specifying top-level arguments
    44  // --max-stack <value> for specifying the maximum stack size
    45  // -e <code> for evaluating code snippets
    46  // <filename> positional arg for evaluating files
    47  type JsonnetBinaryImplementation struct {
    48  	BinPath string
    49  }
    50  
    51  func (i *JsonnetBinaryImplementation) MakeEvaluator(importPaths []string, extCode map[string]string, tlaCode map[string]string, maxStack int) types.JsonnetEvaluator {
    52  	args := []string{}
    53  	for _, p := range importPaths {
    54  		args = append(args, "-J", p)
    55  	}
    56  	if maxStack > 0 {
    57  		args = append(args, "--max-stack", strconv.Itoa(maxStack))
    58  	}
    59  	for k, v := range extCode {
    60  		args = append(args, "--ext-code", k+"="+v)
    61  	}
    62  	for k, v := range tlaCode {
    63  		args = append(args, "--tla-code", k+"="+v)
    64  	}
    65  
    66  	return &JsonnetBinaryRunner{
    67  		binPath: i.BinPath,
    68  		args:    args,
    69  	}
    70  }