mirror of
https://github.com/wahyd4/cert-manager.git
synced 2026-08-11 14:16:52 +10:00
50 lines
1.3 KiB
Go
50 lines
1.3 KiB
Go
package util
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
|
|
"github.com/go-logr/logr"
|
|
logf "github.com/jetstack/cert-manager/hack/release/pkg/log"
|
|
)
|
|
|
|
func RunE(log logr.Logger, cmd *exec.Cmd) error {
|
|
// debug mode logs directly to stdout/stderr
|
|
if log.V(logf.LogLevelTrace).Enabled() {
|
|
cmd.Stdout = os.Stdout
|
|
cmd.Stderr = os.Stderr
|
|
|
|
log = log.WithValues("command", append([]string{cmd.Path}, cmd.Args[1:]...))
|
|
log.V(logf.LogLevelDebug).Info("executing command with default stdout/stderr")
|
|
err := cmd.Run()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to execute command: %v", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
_, err := RunPrintCombined(log, cmd)
|
|
return err
|
|
}
|
|
|
|
// RunPrintCombined will run the given command, capturing its output using CombinedOutput.
|
|
// If the command execution fails, the command output will be logged to the loggers
|
|
// underlying output Writer.
|
|
// This function will return the combined output bytes on both failure and success.
|
|
func RunPrintCombined(log logr.Logger, cmd *exec.Cmd) ([]byte, error) {
|
|
log = log.WithValues("command", append([]string{cmd.Path}, cmd.Args[1:]...))
|
|
log.V(logf.LogLevelDebug).Info("executing command")
|
|
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
logf.Output.Write(out)
|
|
if len(out) == 0 {
|
|
logf.Output.Write([]byte("(no output)"))
|
|
}
|
|
return out, fmt.Errorf("failed to execute command: %v", err)
|
|
}
|
|
return out, nil
|
|
}
|