copy.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package exec
  2. import (
  3. "bytes"
  4. "errors"
  5. )
  6. // Below is largely a copy from go's os/exec/exec.go
  7. // Run starts the specified command and waits for it to complete.
  8. //
  9. // The returned error is nil if the command runs, has no problems
  10. // copying stdin, stdout, and stderr, and exits with a zero exit
  11. // status.
  12. //
  13. // If the command fails to run or doesn't complete successfully, the
  14. // error is of type *ExitError. Other error types may be
  15. // returned for I/O problems.
  16. func (c *Cmd) Run() error {
  17. if err := c.Start(); err != nil {
  18. return translateError(err)
  19. }
  20. return translateError(c.Wait())
  21. }
  22. // Output runs the command and returns its standard output.
  23. // Any returned error will usually be of type *ExitError.
  24. // If c.Stderr was nil, Output populates ExitError.Stderr.
  25. func (c *Cmd) Output() ([]byte, error) {
  26. if c.Stdout != nil {
  27. return nil, errors.New("exec: Stdout already set")
  28. }
  29. var stdout bytes.Buffer
  30. c.Stdout = &stdout
  31. err := c.Run()
  32. return stdout.Bytes(), err
  33. }
  34. // CombinedOutput runs the command and returns its combined standard
  35. // output and standard error.
  36. func (c *Cmd) CombinedOutput() ([]byte, error) {
  37. if c.Stdout != nil {
  38. return nil, errors.New("exec: Stdout already set")
  39. }
  40. if c.Stderr != nil {
  41. return nil, errors.New("exec: Stderr already set")
  42. }
  43. var b bytes.Buffer
  44. c.Stdout = &b
  45. c.Stderr = &b
  46. err := c.Run()
  47. return b.Bytes(), err
  48. }