github.phpd.cn/hashicorp/packer@v1.3.2/builder/lxc/command.go (about) 1 package lxc 2 3 import ( 4 "bytes" 5 "fmt" 6 "log" 7 "os/exec" 8 "strings" 9 ) 10 11 // CommandWrapper is a type that given a command, will possibly modify that 12 // command in-flight. This might return an error. 13 type CommandWrapper func(string) (string, error) 14 15 // ShellCommand takes a command string and returns an *exec.Cmd to execute 16 // it within the context of a shell (/bin/sh). 17 func ShellCommand(command string) *exec.Cmd { 18 return exec.Command("/bin/sh", "-c", command) 19 } 20 21 func RunCommand(args ...string) error { 22 var stdout, stderr bytes.Buffer 23 24 log.Printf("Executing args: %#v", args) 25 cmd := exec.Command(args[0], args[1:]...) 26 cmd.Stdout = &stdout 27 cmd.Stderr = &stderr 28 err := cmd.Run() 29 30 stdoutString := strings.TrimSpace(stdout.String()) 31 stderrString := strings.TrimSpace(stderr.String()) 32 33 if _, ok := err.(*exec.ExitError); ok { 34 err = fmt.Errorf("Command error: %s", stderrString) 35 } 36 37 log.Printf("stdout: %s", stdoutString) 38 log.Printf("stderr: %s", stderrString) 39 40 return err 41 }