Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package services
- import (
- "fmt"
- "github.com/go-cmd/cmd"
- "github.com/golang/glog"
- "time"
- )
- type BashExecutor struct {
- verbose bool
- }
- func NewBashExecutor(verbose bool) *BashExecutor {
- return &BashExecutor{
- verbose: verbose,
- }
- }
- func (bs *BashExecutor) ExecuteCommand(commandString string) int {
- // Disable output buffering, enable streaming
- cmdOptions := cmd.Options{
- Buffered: false,
- Streaming: true,
- }
- mphCmd := cmd.NewCmdOptions(cmdOptions, "bash", "-c", commandString)
- if bs.verbose {
- glog.Infoln("Executing bash command: " + commandString)
- }
- // Print to STDOUT
- if bs.verbose {
- go func() {
- for line := range mphCmd.Stdout {
- fmt.Println(line)
- }
- }()
- } else {
- go func() {
- for range mphCmd.Stdout {
- // do nothing
- }
- }()
- }
- // Run the command
- cmdStatus := <-mphCmd.Start()
- // Cmd has finished but wait for goroutine to print all lines
- for len(mphCmd.Stdout) > 0 {
- time.Sleep(10 * time.Millisecond)
- }
- if cmdStatus.Exit != 0 {
- glog.Errorf("Exit code: %d\n", cmdStatus.Exit)
- glog.Errorf("Executed command: %s\n", commandString)
- glog.Errorf("Error: %+v", cmdStatus.Error)
- for _, line := range cmdStatus.Stderr {
- fmt.Println(line)
- }
- return cmdStatus.Exit
- }
- glog.Infof("Command took %f seconds to complete", cmdStatus.Runtime)
- return cmdStatus.Exit
- }
Add Comment
Please, Sign In to add comment