github.com/rsyabuta/packer@v1.1.4-0.20180119234903-5ef0c2280f0b/provisioner/guest_commands.go (about)

     1  package provisioner
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  const UnixOSType = "unix"
     9  const WindowsOSType = "windows"
    10  const DefaultOSType = UnixOSType
    11  
    12  type guestOSTypeCommand struct {
    13  	chmod     string
    14  	mkdir     string
    15  	removeDir string
    16  }
    17  
    18  var guestOSTypeCommands = map[string]guestOSTypeCommand{
    19  	UnixOSType: {
    20  		chmod:     "chmod %s '%s'",
    21  		mkdir:     "mkdir -p '%s'",
    22  		removeDir: "rm -rf '%s'",
    23  	},
    24  	WindowsOSType: {
    25  		chmod:     "echo 'skipping chmod %s %s'", // no-op
    26  		mkdir:     "powershell.exe -Command \"New-Item -ItemType directory -Force -ErrorAction SilentlyContinue -Path %s\"",
    27  		removeDir: "powershell.exe -Command \"rm %s -recurse -force\"",
    28  	},
    29  }
    30  
    31  type GuestCommands struct {
    32  	GuestOSType string
    33  	Sudo        bool
    34  }
    35  
    36  func NewGuestCommands(osType string, sudo bool) (*GuestCommands, error) {
    37  	_, ok := guestOSTypeCommands[osType]
    38  	if !ok {
    39  		return nil, fmt.Errorf("Invalid osType: \"%s\"", osType)
    40  	}
    41  	return &GuestCommands{GuestOSType: osType, Sudo: sudo}, nil
    42  }
    43  
    44  func (g *GuestCommands) Chmod(path string, mode string) string {
    45  	return g.sudo(fmt.Sprintf(g.commands().chmod, mode, g.escapePath(path)))
    46  }
    47  
    48  func (g *GuestCommands) CreateDir(path string) string {
    49  	return g.sudo(fmt.Sprintf(g.commands().mkdir, g.escapePath(path)))
    50  }
    51  
    52  func (g *GuestCommands) RemoveDir(path string) string {
    53  	return g.sudo(fmt.Sprintf(g.commands().removeDir, g.escapePath(path)))
    54  }
    55  
    56  func (g *GuestCommands) commands() guestOSTypeCommand {
    57  	return guestOSTypeCommands[g.GuestOSType]
    58  }
    59  
    60  func (g *GuestCommands) escapePath(path string) string {
    61  	if g.GuestOSType == WindowsOSType {
    62  		return strings.Replace(path, " ", "` ", -1)
    63  	}
    64  	return path
    65  }
    66  
    67  func (g *GuestCommands) sudo(cmd string) string {
    68  	if g.GuestOSType == UnixOSType && g.Sudo {
    69  		return "sudo " + cmd
    70  	}
    71  	return cmd
    72  }