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