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