-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathvmx.go
116 lines (92 loc) · 2.05 KB
/
vmx.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package vix
import (
"bytes"
"io"
"io/ioutil"
"os"
"sort"
"strings"
"sync"
"github.com/hooklift/govmx"
)
// VMXFile manages VMX files
type VMXFile struct {
sync.Mutex
model *vmx.VirtualMachine
path string
}
// Read reads VMX file from disk and unmarshals it
func (vmxfile *VMXFile) Read() error {
data, err := ioutil.ReadFile(vmxfile.path)
if err != nil {
return err
}
model := new(vmx.VirtualMachine)
err = vmx.Unmarshal(data, model)
if err != nil {
return err
}
vmxfile.model = model
return nil
}
// Write marshals and writes VMX file to disk
func (vmxfile *VMXFile) Write() error {
file, err := os.Create(vmxfile.path)
if err != nil {
return err
}
defer file.Close()
data, err := vmx.Marshal(vmxfile.model)
if err != nil {
return err
}
_, err = file.Write(data)
if err != nil {
return err
}
return nil
}
// TODO(c4milo): Legacy function, this is to be removed once we migrate
// the dependant code
func readVmx(path string) (map[string]string, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
vmx := make(map[string]string)
for _, line := range strings.Split(string(data), "\n") {
values := strings.Split(line, "=")
if len(values) == 2 {
vmx[strings.TrimSpace(values[0])] = strings.Trim(strings.TrimSpace(values[1]), `"`)
}
}
return vmx, nil
}
// TODO(c4milo): Legacy function, this is to be removed once we migrate
// the dependant code
func writeVmx(path string, vmx map[string]string) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
keys := make([]string, len(vmx))
i := 0
for k := range vmx {
keys[i] = k
i++
}
sort.Strings(keys)
var buf bytes.Buffer
for _, key := range keys {
buf.WriteString(key + " = " + `"` + vmx[key] + `"`)
buf.WriteString("\n")
}
if _, err = io.Copy(f, &buf); err != nil {
return err
}
return nil
}