github.com/suzuken/ghq@v0.7.5-0.20160607064937-214ded0f64ec/utils/run.go (about)

     1  package utils
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  	"os/exec"
     8  	"strings"
     9  )
    10  
    11  func Run(command string, args ...string) error {
    12  	cmd := exec.Command(command, args...)
    13  	cmd.Stdout = os.Stdout
    14  	cmd.Stderr = os.Stderr
    15  
    16  	return RunCommand(cmd)
    17  }
    18  
    19  func RunSilently(command string, args ...string) error {
    20  	cmd := exec.Command(command, args...)
    21  	cmd.Stdout = ioutil.Discard
    22  	cmd.Stderr = ioutil.Discard
    23  
    24  	return RunCommand(cmd)
    25  }
    26  
    27  func RunInDir(dir, command string, args ...string) error {
    28  	cmd := exec.Command(command, args...)
    29  	cmd.Stdout = os.Stdout
    30  	cmd.Stderr = os.Stderr
    31  	cmd.Dir = dir
    32  
    33  	return RunCommand(cmd)
    34  }
    35  
    36  type RunFunc func(*exec.Cmd) error
    37  
    38  var CommandRunner = func(cmd *exec.Cmd) error {
    39  	return cmd.Run()
    40  }
    41  
    42  func RunCommand(cmd *exec.Cmd) error {
    43  	Log(cmd.Args[0], strings.Join(cmd.Args[1:], " "))
    44  
    45  	err := CommandRunner(cmd)
    46  	if err != nil {
    47  		return &RunError{cmd, err}
    48  	}
    49  
    50  	return nil
    51  }
    52  
    53  type RunError struct {
    54  	Command   *exec.Cmd
    55  	ExecError error
    56  }
    57  
    58  func (e *RunError) Error() string {
    59  	return fmt.Sprintf("%s: %s", e.Command.Path, e.ExecError)
    60  }