From a4d09aa6aeb1961f7ee8f239fec5b5c5f9297857 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 24 Jan 2024 09:55:52 -0500 Subject: export-json.bash WIP --- wordpress/export-json.bash | 103 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 wordpress/export-json.bash (limited to 'wordpress/export-json.bash') diff --git a/wordpress/export-json.bash b/wordpress/export-json.bash new file mode 100644 index 0000000..343e66d --- /dev/null +++ b/wordpress/export-json.bash @@ -0,0 +1,103 @@ +#!/bin/bash + +# This script allows bash to export environment +# variables as JSON. It uses the external tool +# "jq" to parse string values # placed in jq's +# argument list by bash and then encode them +# as JSON string values. This is no accidental +# dependency. The jq program is the foundation of +# the trustworthiness of this code. If we were +# encoding JSON strings in bash (and not just JSON +# objects containing strings) we would have to be +# a lot more careful. + +# This is the simple code I wanted to replace: +# +# jq --arg SITE "$SITE" "$json" +# jq -n \ +# --arg h "$db_host" \ +# --arg u "$db_user" \ +# --arg p "$db_password" \ +# --arg n "$db_name" \ +# --arg t "$table_prefix" \ +# '{ db_host: $h +# , db_user: $u +# , db_password: $p +# , db_name: $n +# , table_prefix: $t +# }' +# +# The problem with the above is that the names are repeated. +# This creates the possibility that the names not match, +# creating a bug. +# This code allows the names to be specified only one time. +# It allows the bug where the names do not match to be fixed only one +# time by one person. +# IF ... the fix can be distributed back to the extant copies. +# How to get the beneficial mutations +# back into the living organisms? +# Life tries not to answer this question +# until very late in its development +# since after all +# the extant copies are the past +# and life looks into the future +# but because consciousness +# is the mirror of time +# the question is asked +# eventually + +export_JSON() +{ + declare -a exported_vars=() + declare -A displayname=() + while [ $# -gt 0 ] + do + case "$1" in + v | exported_vars | displayname | jqargs | jqjson | n ) + continue + ;; + *[^a-zA-Z0-9_=]* | *=*=* ) + continue + ;; + [a-zA-Z_]*=* ) + exported_vars+=("${1%=*}") + displayname["${1%=*}"]=${1#*=} + ;; + [a-zA-Z_]* ) + exported_vars+=("$1") + ;; + esac + shift + done + export_with_jq +} + +export_with_jq() +{ + n=$'\n' + jqargs=("-n") + jqjson= + for v in "${exported_vars[@]}" + do + if ! [ -v "$v" ] + then + echo "Warning: not defined: $v" >&2 + continue + fi + jqargs+=(--arg "$v" "${!v}") + if [ "$jqjson" ] + then + p=',' + else + p='{' + fi + dv=${displayname[$v]} + jqjson="$jqjson$p ${dv:-$v}: \$$v$n" + done + if [ "$jqjson" ] + then + jqjson="$jqjson}$n" + fi + jq -n "${jqargs[@]}" "$jqjson" +} + -- cgit v1.2.3