daily pastebin goal
54%
SHARE
TWEET

Untitled

a guest Feb 17th, 2019 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package services
  2.  
  3. import (
  4.     "fmt"
  5.     "github.com/go-cmd/cmd"
  6.     "github.com/golang/glog"
  7.     "time"
  8. )
  9.  
  10. type BashExecutor struct {
  11.     verbose bool
  12. }
  13.  
  14. func NewBashExecutor(verbose bool) *BashExecutor {
  15.     return &BashExecutor{
  16.         verbose: verbose,
  17.     }
  18. }
  19.  
  20. func (bs *BashExecutor) ExecuteCommand(commandString string) int {
  21.     // Disable output buffering, enable streaming
  22.     cmdOptions := cmd.Options{
  23.         Buffered:  false,
  24.         Streaming: true,
  25.     }
  26.  
  27.     mphCmd := cmd.NewCmdOptions(cmdOptions, "bash", "-c", commandString)
  28.  
  29.     if bs.verbose {
  30.         glog.Infoln("Executing bash command: " + commandString)
  31.     }
  32.  
  33.     // Print to STDOUT
  34.     if bs.verbose {
  35.         go func() {
  36.             for line := range mphCmd.Stdout {
  37.                 fmt.Println(line)
  38.             }
  39.         }()
  40.     } else {
  41.         go func() {
  42.             for range mphCmd.Stdout {
  43.                 // do nothing
  44.             }
  45.         }()
  46.     }
  47.  
  48.     // Run the command
  49.     cmdStatus := <-mphCmd.Start()
  50.  
  51.     // Cmd has finished but wait for goroutine to print all lines
  52.     for len(mphCmd.Stdout) > 0 {
  53.         time.Sleep(10 * time.Millisecond)
  54.     }
  55.  
  56.     if cmdStatus.Exit != 0 {
  57.         glog.Errorf("Exit code: %d\n", cmdStatus.Exit)
  58.         glog.Errorf("Executed command: %s\n", commandString)
  59.         glog.Errorf("Error: %+v", cmdStatus.Error)
  60.         for _, line := range cmdStatus.Stderr {
  61.             fmt.Println(line)
  62.         }
  63.         return cmdStatus.Exit
  64.     }
  65.  
  66.     glog.Infof("Command took %f seconds to complete", cmdStatus.Runtime)
  67.     return cmdStatus.Exit
  68. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top