github.com/alouche/packer@v0.3.7/builder/vmware/vmx.go (about) 1 package vmware 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "os" 8 "regexp" 9 "sort" 10 "strings" 11 ) 12 13 // ParseVMX parses the keys and values from a VMX file and returns 14 // them as a Go map. 15 func ParseVMX(contents string) map[string]string { 16 results := make(map[string]string) 17 18 lineRe := regexp.MustCompile(`^(.+?)\s*=\s*"(.*?)"\s*$`) 19 20 for _, line := range strings.Split(contents, "\n") { 21 matches := lineRe.FindStringSubmatch(line) 22 if matches == nil { 23 continue 24 } 25 26 results[matches[1]] = matches[2] 27 } 28 29 return results 30 } 31 32 // EncodeVMX takes a map and turns it into valid VMX contents. 33 func EncodeVMX(contents map[string]string) string { 34 var buf bytes.Buffer 35 36 i := 0 37 keys := make([]string, len(contents)) 38 for k, _ := range contents { 39 keys[i] = k 40 i++ 41 } 42 43 sort.Strings(keys) 44 for _, k := range keys { 45 buf.WriteString(fmt.Sprintf("%s = \"%s\"\n", k, contents[k])) 46 } 47 48 return buf.String() 49 } 50 51 // WriteVMX takes a path to a VMX file and contents in the form of a 52 // map and writes it out. 53 func WriteVMX(path string, data map[string]string) (err error) { 54 f, err := os.Create(path) 55 if err != nil { 56 return 57 } 58 defer f.Close() 59 60 var buf bytes.Buffer 61 buf.WriteString(EncodeVMX(data)) 62 if _, err = io.Copy(f, &buf); err != nil { 63 return 64 } 65 66 return 67 }