github.com/splunk/qbec@v0.15.2/vm/internal/ds/exec/runner.go (about)

     1  /*
     2     Copyright 2021 Splunk Inc.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package exec
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"fmt"
    23  	"os"
    24  	"os/exec"
    25  )
    26  
    27  type runner struct {
    28  	c *Config
    29  }
    30  
    31  func newRunner(c *Config) *runner {
    32  	return &runner{c: c}
    33  }
    34  
    35  func (r *runner) runWithEnv(e map[string]string) (string, error) {
    36  	ctx, cancel := context.WithTimeout(context.Background(), r.c.timeout)
    37  	defer cancel()
    38  
    39  	cmd := exec.CommandContext(ctx, r.c.Command, r.c.Args...)
    40  	var env []string
    41  	if r.c.InheritEnv {
    42  		env = os.Environ()
    43  	}
    44  	for k, v := range r.c.Env {
    45  		env = append(env, fmt.Sprintf("%s=%s", k, v))
    46  	}
    47  	for k, v := range e {
    48  		env = append(env, fmt.Sprintf("%s=%s", k, v))
    49  	}
    50  	cmd.Env = env
    51  
    52  	var capture bytes.Buffer
    53  	cmd.Stdin = bytes.NewReader([]byte(r.c.Stdin))
    54  	cmd.Stdout = &capture
    55  	cmd.Stderr = os.Stderr
    56  
    57  	if err := cmd.Run(); err != nil {
    58  		return "", err
    59  	}
    60  	return capture.String(), nil
    61  }
    62  
    63  func (r *runner) close() error {
    64  	return nil
    65  }