Created
December 2, 2019 16:17
-
-
Save invidian/5a40bb8c923c5f010a6dcaf68fd8b243 to your computer and use it in GitHub Desktop.
Golang reverse formatting with regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"reflect" | |
"regexp" | |
"sort" | |
) | |
func main() { | |
// Test data | |
data := map[string]string{ | |
"foo.yaml": `apiVersion: v1 | |
metadata: | |
name: foo | |
`, | |
"bar.yaml": `kind: Pod | |
metadata: | |
name: bar | |
`, | |
} | |
// Extract keys | |
keys := []string{} | |
for k, _ := range data { | |
keys = append(keys, k) | |
} | |
sort.Strings(keys) | |
// Prepare output | |
output := "" | |
// Build the output | |
for _, k := range keys { | |
output += fmt.Sprintf("---\n# Source: %s\n%s\n", k, data[k]) | |
} | |
r := regexp.MustCompile("(?sm)^---\n^# Source: (?P<path>.*?)$\n(?P<content>.*?^$)\n") | |
matches := r.FindAllStringSubmatch(output, -1) | |
recoveredData := map[string]string{} | |
for _, match := range matches { | |
recoveredData[match[1]] = match[2] | |
} | |
fmt.Println(reflect.DeepEqual(data, recoveredData)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment