2013-06-06 00:01:22 -04:00
|
|
|
package vmware
|
|
|
|
|
|
|
|
import (
|
2013-06-07 17:48:59 -04:00
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2013-11-08 00:03:15 -05:00
|
|
|
"log"
|
2013-06-07 17:48:59 -04:00
|
|
|
"os"
|
2013-06-06 00:01:22 -04:00
|
|
|
"regexp"
|
2013-06-07 17:48:59 -04:00
|
|
|
"sort"
|
2013-06-06 00:01:22 -04:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ParseVMX parses the keys and values from a VMX file and returns
|
|
|
|
// them as a Go map.
|
|
|
|
func ParseVMX(contents string) map[string]string {
|
|
|
|
results := make(map[string]string)
|
|
|
|
|
|
|
|
lineRe := regexp.MustCompile(`^(.+?)\s*=\s*"(.*?)"\s*$`)
|
|
|
|
|
|
|
|
for _, line := range strings.Split(contents, "\n") {
|
|
|
|
matches := lineRe.FindStringSubmatch(line)
|
|
|
|
if matches == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2013-11-08 01:06:11 -05:00
|
|
|
key := strings.ToLower(matches[1])
|
|
|
|
results[key] = matches[2]
|
2013-06-06 00:01:22 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return results
|
|
|
|
}
|
2013-06-07 17:48:59 -04:00
|
|
|
|
|
|
|
// EncodeVMX takes a map and turns it into valid VMX contents.
|
|
|
|
func EncodeVMX(contents map[string]string) string {
|
|
|
|
var buf bytes.Buffer
|
|
|
|
|
|
|
|
i := 0
|
|
|
|
keys := make([]string, len(contents))
|
|
|
|
for k, _ := range contents {
|
|
|
|
keys[i] = k
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
|
|
|
|
sort.Strings(keys)
|
|
|
|
for _, k := range keys {
|
|
|
|
buf.WriteString(fmt.Sprintf("%s = \"%s\"\n", k, contents[k]))
|
|
|
|
}
|
|
|
|
|
|
|
|
return buf.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
// WriteVMX takes a path to a VMX file and contents in the form of a
|
|
|
|
// map and writes it out.
|
|
|
|
func WriteVMX(path string, data map[string]string) (err error) {
|
2013-11-08 00:03:15 -05:00
|
|
|
log.Printf("Writing VMX to: %s", path)
|
2013-06-07 17:48:59 -04:00
|
|
|
f, err := os.Create(path)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
var buf bytes.Buffer
|
|
|
|
buf.WriteString(EncodeVMX(data))
|
|
|
|
if _, err = io.Copy(f, &buf); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|