yaml.sh 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/env bash
  2. # shellcheck disable=SC1003
  3. # Based on https://gist.github.com/pkuczynski/8665367
  4. parse_yaml() {
  5. local yaml_file=$1
  6. local prefix=$2
  7. local s
  8. local w
  9. local fs
  10. s='[[:space:]]*'
  11. w='[a-zA-Z0-9_.-]*'
  12. fs="$(echo @|tr @ '\034')"
  13. (
  14. sed -e '/- [^\“]'"[^\']"'.*: /s|\([ ]*\)- \([[:space:]]*\)|\1-\'$'\n'' \1\2|g' |
  15. sed -ne '/^--/s|--||g; s|\"|\\\"|g; s/[[:space:]]*$//g;' \
  16. -e "/#.*[\"\']/!s| #.*||g; /^#/s|#.*||g;" \
  17. -e "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
  18. -e "s|^\($s\)\($w\)${s}[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" |
  19. awk -F"$fs" '{
  20. indent = length($1)/2;
  21. if (length($2) == 0) { conj[indent]="+";} else {conj[indent]="";}
  22. vname[indent] = $2;
  23. for (i in vname) {if (i > indent) {delete vname[i]}}
  24. if (length($3) > 0) {
  25. vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
  26. printf("%s%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, conj[indent-1],$3);
  27. }
  28. }' |
  29. sed -e 's/_=/+=/g' |
  30. awk 'BEGIN {
  31. FS="=";
  32. OFS="="
  33. }
  34. /(-|\.).*=/ {
  35. gsub("-|\\.", "_", $1)
  36. }
  37. { print }'
  38. ) < "$yaml_file"
  39. }
  40. create_variables() {
  41. local yaml_file="$1"
  42. local prefix="$2"
  43. eval "$(parse_yaml "$yaml_file" "$prefix")"
  44. }