yaml.sh (2272B)
1 #!/usr/bin/env bash
2 # shellcheck disable=SC1003
3
4 # Based on https://gist.github.com/pkuczynski/8665367
5
6 parse_yaml() {
7 local yaml_file=$1
8 local prefix=$2
9 local s
10 local w
11 local fs
12
13 s='[[:space:]]*'
14 w='[a-zA-Z0-9_.-]*'
15 fs="$(echo @ | tr @ '\034')"
16
17 (
18 sed -e '/- [^\“]'"[^\']"'.*: /s|\([ ]*\)- \([[:space:]]*\)|\1-\'$'\n'' \1\2|g' |
19 sed -ne '/^--/s|--||g; s|\"|\\\"|g; s/[[:space:]]*$//g;' \
20 -e 's/\$/\\\$/g' \
21 -e "/#.*[\"\']/!s| #.*||g; /^#/s|#.*||g;" \
22 -e "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
23 -e "s|^\($s\)\($w\)${s}[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" |
24 awk -F"$fs" '{
25 indent = length($1)/2;
26 if (length($2) == 0) { conj[indent]="+";} else {conj[indent]="";}
27 vname[indent] = $2;
28 for (i in vname) {if (i > indent) {delete vname[i]}}
29 if (length($3) > 0) {
30 vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
31 printf("%s%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, conj[indent-1], $3);
32 }
33 }' |
34 sed -e 's/_=/+=/g' |
35 awk 'BEGIN {
36 FS="=";
37 OFS="="
38 }
39 /(-|\.).*=/ {
40 gsub("-|\\.", "_", $1)
41 }
42 { print }'
43 ) <"$yaml_file"
44 }
45
46 unset_variables() {
47 # Pulls out the variable names and unsets them.
48 #shellcheck disable=SC2048,SC2206 #Permit variables without quotes
49 local variable_string=($*)
50 unset variables
51 variables=()
52 for variable in "${variable_string[@]}"; do
53 tmpvar=$(echo "$variable" | grep '=' | sed 's/=.*//' | sed 's/+.*//')
54 variables+=("$tmpvar")
55 done
56 for variable in "${variables[@]}"; do
57 if [ -n "$variable" ]; then
58 unset "$variable"
59 fi
60 done
61 }
62
63 create_variables() {
64 local yaml_file="$1"
65 local prefix="$2"
66 local yaml_string
67 yaml_string="$(parse_yaml "$yaml_file" "$prefix")"
68 unset_variables "${yaml_string}"
69 eval "${yaml_string}"
70 }
71
72 # Execute parse_yaml() direct from command line
73
74 if [ "x" != "x${1}" ] && [ "x--debug" != "x${1}" ]; then
75 parse_yaml "${1}" "${2}"
76 fi