forked from terra-farm/go-virtualbox
-
Notifications
You must be signed in to change notification settings - Fork 6
/
vbm.go
88 lines (79 loc) · 1.96 KB
/
vbm.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package virtualbox
import (
"bytes"
"errors"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
)
var (
VBM string // Path to VBoxManage utility.
Verbose bool // Verbose mode.
)
func init() {
VBM = "VBoxManage"
if p := os.Getenv("VBOX_INSTALL_PATH"); p != "" && runtime.GOOS == "windows" {
VBM = filepath.Join(p, "VBoxManage.exe")
}
}
var (
reVMNameUUID = regexp.MustCompile(`"(.+)" {([0-9a-f-]+)}`)
reVMInfoLine = regexp.MustCompile(`(?:"(.+)"|(.+))=(?:"(.*)"|(.*))`)
reColonLine = regexp.MustCompile(`(.+):\s+(.*)`)
reMachineNotFound = regexp.MustCompile(`Could not find a registered machine named '(.+)'`)
)
var (
ErrMachineExist = errors.New("machine already exists")
ErrMachineNotExist = errors.New("machine does not exist")
ErrVBMNotFound = errors.New("VBoxManage not found")
)
func vbm(args ...string) error {
cmd := exec.Command(VBM, args...)
if Verbose {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Printf("executing: %v %v", VBM, strings.Join(args, " "))
}
if err := cmd.Run(); err != nil {
if ee, ok := err.(*exec.Error); ok && ee == exec.ErrNotFound {
return ErrVBMNotFound
}
return err
}
return nil
}
func vbmOut(args ...string) (string, error) {
cmd := exec.Command(VBM, args...)
if Verbose {
cmd.Stderr = os.Stderr
log.Printf("executing: %v %v", VBM, strings.Join(args, " "))
}
b, err := cmd.Output()
if err != nil {
if ee, ok := err.(*exec.Error); ok && ee == exec.ErrNotFound {
err = ErrVBMNotFound
}
}
return string(b), err
}
func vbmOutErr(args ...string) (string, string, error) {
cmd := exec.Command(VBM, args...)
if Verbose {
log.Printf("executing: %v %v", VBM, strings.Join(args, " "))
}
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
if ee, ok := err.(*exec.Error); ok && ee == exec.ErrNotFound {
err = ErrVBMNotFound
}
}
return stdout.String(), stderr.String(), err
}