Last active
January 22, 2024 02:06
-
-
Save cornfeedhobo/ba7d29d60793153bf5b4b9d92d1115f4 to your computer and use it in GitHub Desktop.
Helm Macro - toYamlPretty - A recursive YAML formatter
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
{{- define "toPrettyYaml" -}} | |
{{- $out := "" -}} | |
{{- range $k, $v := . -}} | |
{{- if not (empty $v) -}} | |
{{- /* Walk any maps */ -}} | |
{{- if kindIs "map" $v -}} | |
{{- $out = (print $out | |
$k ":\n" | |
(include "toPrettyYaml" $v | indent 2) | |
"\n" | |
) | |
-}} | |
{{- /* Iterate any slices */ -}} | |
{{- else if kindIs "slice" $v -}} | |
{{- $out = (print $out $k ":\n") -}} | |
{{- range $_, $v := $v -}} | |
{{- $out = (print $out | |
" -\n" | |
(include "toPrettyYaml" $v | indent 4) | |
"\n" | |
) | |
-}} | |
{{- end -}} | |
{{- /* Quote any strings */ -}} | |
{{- else if kindIs "string" $v -}} | |
{{- if contains "\n" $v -}} | |
{{- if hasSuffix "\n" $v -}} | |
{{- if eq 1 (len (splitList "\n" $v|compact)) -}} | |
{{- $out = printf "%s%s: >\n%s\n" $out $k (wrap 80 $v|trimSuffix "\n"|indent 2) -}} | |
{{- else -}} | |
{{- $out = printf "%s%s: |\n%s\n" $out $k ($v|trimSuffix "\n"|indent 2) -}} | |
{{- end -}} | |
{{- else -}} | |
{{- $out = printf "%s%s: |-\n%s\n" $out $k ($v|indent 2) -}} | |
{{- end -}} | |
{{- else -}} | |
{{- if gt (len $v) 80 -}} | |
{{- $out = printf "%s%s: >-\n%s\n" $out $k (wrap 80 $v|indent 2) -}} | |
{{- else -}} | |
{{- $out = printf "%s%s: %q\n" $out $k $v -}} | |
{{- end -}} | |
{{- end -}} | |
{{- /* Print anything else, as it is */ -}} | |
{{- else -}} | |
{{- $out = (print $out | |
$k ": " $v | |
"\n" | |
) | |
-}} | |
{{- end -}} | |
{{- end -}} | |
{{- end -}} | |
{{- /* | |
Chop of the trailing newline so callers don't have to treat | |
this macro as special and can use `nindent` as usual. | |
*/ -}} | |
{{- $out | trimSuffix "\n" -}} | |
{{- end -}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment