github.phpd.cn/hashicorp/packer@v1.3.2/builder/lxd/command.go (about)

     1  package lxd
     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  // Yeah...LXD calls `lxc` because the command line is different between the
    22  // packages. This should also avoid a naming collision between the LXC builder.
    23  func LXDCommand(args ...string) (string, error) {
    24  	var stdout, stderr bytes.Buffer
    25  
    26  	log.Printf("Executing lxc command: %#v", args)
    27  	cmd := exec.Command("lxc", args...)
    28  	cmd.Stdout = &stdout
    29  	cmd.Stderr = &stderr
    30  	err := cmd.Run()
    31  
    32  	stdoutString := strings.TrimSpace(stdout.String())
    33  	stderrString := strings.TrimSpace(stderr.String())
    34  
    35  	if _, ok := err.(*exec.ExitError); ok {
    36  		err = fmt.Errorf("LXD command error: %s", stderrString)
    37  	}
    38  
    39  	log.Printf("stdout: %s", stdoutString)
    40  	log.Printf("stderr: %s", stderrString)
    41  
    42  	return stdoutString, err
    43  }