#!/bin/bash # # Purpose : Read and edit JSON for configure.d items. Source this file. # # macOS has no jq before macOS 15, and python3 needs the Command Line Tools, # so this uses JavaScript for Automation (osascript -l JavaScript), which # every macOS has. Expressions are JavaScript; the JSON is "d", and any # arguments after the expression are a[0], a[1], ... so values never have to # be pasted into the code. # json_get [args...] < file.json # Prints the expression's value: strings as they are, anything else as JSON. # Fails if the input isn't JSON, or the value is undefined, null, false or "". # shellcheck disable=SC2016 json_get() { osascript -l JavaScript -e ' function run(argv) { ObjC.import("Foundation"); var data = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile; var text = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding).js; var d = JSON.parse(text); var v; try { v = (new Function("d", "a", "return (" + argv[0] + ");"))(d, argv.slice(1)); } catch (e) { v = undefined; } if (v === undefined || v === null || v === false || v === "") throw new Error("no value"); return typeof v === "string" ? v : JSON.stringify(v); }' "$@" 2> /dev/null } # json_edit [args...] # Runs JavaScript statements that change "d", the file's JSON, and saves it. # A missing or empty file starts as {}. Leaves the file alone if it isn't # valid JSON. # shellcheck disable=SC2016 json_edit() { local file="$1" mkdir -p "$(dirname "$file")" || return 1 osascript -l JavaScript -e ' function run(argv) { ObjC.import("Foundation"); var path = argv[0]; var s = $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null); var text = s.isNil() ? "" : s.js; var d = text.trim() === "" ? {} : JSON.parse(text); (new Function("d", "a", argv[1]))(d, argv.slice(2)); var out = $(JSON.stringify(d, null, 2) + "\n"); if (!out.writeToFileAtomicallyEncodingError(path, true, $.NSUTF8StringEncoding, null)) { throw new Error("could not write " + path); } }' "$@" > /dev/null 2>&1 || { echo "Couldn't change $file; is it valid JSON?"; return 1; } }