github.com/verrazzano/verrazzano@v1.7.0/pkg/os/exec.go (about)

     1  // Copyright (c) 2020, 2022, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package os
     5  
     6  import (
     7  	"bytes"
     8  	"fmt"
     9  	"os/exec"
    10  )
    11  
    12  // CmdRunner defines the interface to run an external command
    13  type CmdRunner interface {
    14  	Run(cmd *exec.Cmd) (stdout []byte, stderr []byte, err error)
    15  }
    16  
    17  // DefaultRunner is used to run an external command
    18  type DefaultRunner struct {
    19  }
    20  
    21  // Verify that Verrazzano implements Component
    22  var _ CmdRunner = DefaultRunner{}
    23  
    24  // neecmdRunFunc is needed for unit test
    25  var cmdRunFunc func(cmd *exec.Cmd) error
    26  
    27  // Run runs an external command.  The caller is expected to initialize the
    28  // cmd name and args, for example using exec.Command(...)
    29  func (r DefaultRunner) Run(cmd *exec.Cmd) (stdout []byte, stderr []byte, err error) {
    30  	stdoutBuffer := &bytes.Buffer{}
    31  	stderrBuffer := &bytes.Buffer{}
    32  	cmd.Stdout = stdoutBuffer
    33  	cmd.Stderr = stderrBuffer
    34  	if cmdRunFunc != nil {
    35  		err = cmdRunFunc(cmd)
    36  	} else {
    37  		err = cmd.Run()
    38  	}
    39  	if err != nil {
    40  		return stdoutBuffer.Bytes(), stderrBuffer.Bytes(), fmt.Errorf("Failed to run '%s :  Error %s", cmd, err)
    41  	}
    42  	return stdoutBuffer.Bytes(), stderrBuffer.Bytes(), nil
    43  }
    44  
    45  // GenericTestRunner is used to run generic OS commands with expected results
    46  type GenericTestRunner struct {
    47  	StdOut []byte
    48  	StdErr []byte
    49  	Err    error
    50  }
    51  
    52  // Run GenericTestRunner executor
    53  func (r GenericTestRunner) Run(_ *exec.Cmd) (stdout []byte, stderr []byte, err error) {
    54  	return r.StdOut, r.StdErr, r.Err
    55  }