github.com/ddnomad/packer@v1.3.2/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 statPath string 17 mv string 18 } 19 20 var guestOSTypeCommands = map[string]guestOSTypeCommand{ 21 UnixOSType: { 22 chmod: "chmod %s '%s'", 23 mkdir: "mkdir -p '%s'", 24 removeDir: "rm -rf '%s'", 25 statPath: "stat '%s'", 26 mv: "mv '%s' '%s'", 27 }, 28 WindowsOSType: { 29 chmod: "echo 'skipping chmod %s %s'", // no-op 30 mkdir: "powershell.exe -Command \"New-Item -ItemType directory -Force -ErrorAction SilentlyContinue -Path %s\"", 31 removeDir: "powershell.exe -Command \"rm %s -recurse -force\"", 32 statPath: "powershell.exe -Command { if (test-path %s) { exit 0 } else { exit 1 } }", 33 mv: "powershell.exe -Command \"mv %s %s\"", 34 }, 35 } 36 37 type GuestCommands struct { 38 GuestOSType string 39 Sudo bool 40 } 41 42 func NewGuestCommands(osType string, sudo bool) (*GuestCommands, error) { 43 _, ok := guestOSTypeCommands[osType] 44 if !ok { 45 return nil, fmt.Errorf("Invalid osType: \"%s\"", osType) 46 } 47 return &GuestCommands{GuestOSType: osType, Sudo: sudo}, nil 48 } 49 50 func (g *GuestCommands) Chmod(path string, mode string) string { 51 return g.sudo(fmt.Sprintf(g.commands().chmod, mode, g.escapePath(path))) 52 } 53 54 func (g *GuestCommands) CreateDir(path string) string { 55 return g.sudo(fmt.Sprintf(g.commands().mkdir, g.escapePath(path))) 56 } 57 58 func (g *GuestCommands) RemoveDir(path string) string { 59 return g.sudo(fmt.Sprintf(g.commands().removeDir, g.escapePath(path))) 60 } 61 62 func (g *GuestCommands) commands() guestOSTypeCommand { 63 return guestOSTypeCommands[g.GuestOSType] 64 } 65 66 func (g *GuestCommands) escapePath(path string) string { 67 if g.GuestOSType == WindowsOSType { 68 return strings.Replace(path, " ", "` ", -1) 69 } 70 return path 71 } 72 73 func (g *GuestCommands) StatPath(path string) string { 74 return g.sudo(fmt.Sprintf(g.commands().statPath, g.escapePath(path))) 75 } 76 77 func (g *GuestCommands) MovePath(srcPath string, dstPath string) string { 78 return g.sudo(fmt.Sprintf(g.commands().mv, g.escapePath(srcPath), g.escapePath(dstPath))) 79 } 80 81 func (g *GuestCommands) sudo(cmd string) string { 82 if g.GuestOSType == UnixOSType && g.Sudo { 83 return "sudo " + cmd 84 } 85 return cmd 86 }