github.com/metux/go-metabuild@v0.0.0-20240118143255-d9ed5ab697f9/util/cmd/run.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  	"os/exec"
     8  	"strings"
     9  
    10  	"github.com/metux/go-metabuild/util/strs"
    11  )
    12  
    13  func RunOut(cmdline []string, logErr bool) (string, error) {
    14  	cmd := exec.Command(cmdline[0], cmdline[1:]...)
    15  	if out, err := cmd.CombinedOutput(); err != nil {
    16  		if logErr {
    17  			log.Printf("Command error for: %s\n", cmdline)
    18  			log.Printf(">> %s\n", out)
    19  		}
    20  		return fmt.Sprintf("%s", out), err
    21  	} else {
    22  		return fmt.Sprintf("%s", out), nil
    23  	}
    24  }
    25  
    26  func RunGroup(cmdlines [][]string) ([]string, []error) {
    27  	outs := make([]string, len(cmdlines))
    28  	errs := make([]error, len(cmdlines))
    29  	cmds := make([](*exec.Cmd), len(cmdlines))
    30  
    31  	for x, y := range cmdlines {
    32  		cmds[x] = exec.Command(y[0], y[1:]...)
    33  		cmds[x].Stdout = os.Stdout
    34  		cmds[x].Stderr = os.Stderr
    35  		cmds[x].Start()
    36  	}
    37  
    38  	for x, _ := range cmdlines {
    39  		errs[x] = cmds[x].Wait()
    40  		// FIXME: capture output and stderr
    41  		outs[x] = cmds[x].String()
    42  	}
    43  
    44  	return outs, errs
    45  }
    46  
    47  func RunOutOne(cmdline []string, logErr bool) (string, error) {
    48  	out, err := RunOut(cmdline, logErr)
    49  	return strings.TrimSpace(out), err
    50  }
    51  
    52  func RunOutLines(cmdline []string, logErr bool) ([]string, error) {
    53  	out, err := RunOutOne(cmdline, logErr)
    54  	return strs.SplitNL(out), err
    55  }
    56  
    57  func RunOutCmd(cmdline []string, logErr bool) ([]string, error) {
    58  	out, err := RunOut(cmdline, logErr)
    59  	return StrCmdline(out), err
    60  }