github.com/jkawamoto/roadie-azure@v0.3.5/roadie/util.go (about)

     1  //
     2  // roadie/util.go
     3  //
     4  // Copyright (c) 2017 Junpei Kawamoto
     5  //
     6  // This file is part of Roadie Azure.
     7  //
     8  // Roadie Azure is free software: you can redistribute it and/or modify
     9  // it under the terms of the GNU General Public License as published by
    10  // the Free Software Foundation, either version 3 of the License, or
    11  // (at your option) any later version.
    12  //
    13  // Roadie Azure is distributed in the hope that it will be useful,
    14  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    15  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    16  // GNU General Public License for more details.
    17  //
    18  // You should have received a copy of the GNU General Public License
    19  // along with Roadie Azure. If not, see <http://www.gnu.org/licenses/>.
    20  //
    21  
    22  package roadie
    23  
    24  import (
    25  	"bufio"
    26  	"log"
    27  	"os/exec"
    28  	"path/filepath"
    29  	"sync"
    30  )
    31  
    32  // ExecCommand runs a given command forwarding its outputs to a given logger.
    33  func ExecCommand(cmd *exec.Cmd, logger *log.Logger) (err error) {
    34  
    35  	var wg sync.WaitGroup
    36  
    37  	stdout, err := cmd.StdoutPipe()
    38  	if err != nil {
    39  		logger.Printf("cannot read stdout of %v: %v", filepath.Base(cmd.Path), err)
    40  	} else {
    41  		wg.Add(1)
    42  		go func() {
    43  			defer wg.Done()
    44  			defer stdout.Close()
    45  			scanner := bufio.NewScanner(stdout)
    46  			for scanner.Scan() {
    47  				logger.Println(scanner.Text())
    48  			}
    49  		}()
    50  	}
    51  
    52  	stderr, err := cmd.StderrPipe()
    53  	if err != nil {
    54  		logger.Printf("cannot read stderr of %v: %v", filepath.Base(cmd.Path), err)
    55  	} else {
    56  		wg.Add(1)
    57  		go func() {
    58  			defer wg.Done()
    59  			defer stderr.Close()
    60  			scanner := bufio.NewScanner(stderr)
    61  			for scanner.Scan() {
    62  				logger.Println(scanner.Text())
    63  			}
    64  		}()
    65  	}
    66  
    67  	err = cmd.Start()
    68  	if err == nil {
    69  		err = cmd.Wait()
    70  	}
    71  	wg.Wait()
    72  	return
    73  
    74  }