File: //bin/X11/add-wp-cli-require-line.sh
#!/usr/bin/env bash
set -euo pipefail
# Refuse to run as root
if [ "${EUID:-$(id -u)}" -eq 0 ]; then
echo "Error: this script must not be run as root" >&2
exit 1
fi
CONFIG="$HOME/.wp-cli/config.yml"
REQ_LINE=" - /opt/wp-cli/wp-cli-login-command/vendor/autoload.php"
mkdir -p "$(dirname "$CONFIG")"
touch "$CONFIG"
# If the exact line already exists anywhere, do nothing.
if grep -Fxq "$REQ_LINE" "$CONFIG"; then
exit 0
fi
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT
# Bash-only (awk) YAML-ish edit:
# - If there is no `require:` key, append a new block at EOF and add the line.
# - If there is a `require:` key:
# * If it already has list items, append our line to that list.
# * If it has no list items yet, add our line right after `require:`.
# In all cases, insert BEFORE the next top-level key (non-indented line).
awk -v req_line="$REQ_LINE" '
BEGIN {
found_require = 0
in_require = 0
inserted = 0
}
# Top-level "require:" key
/^[[:space:]]*require:[[:space:]]*$/ {
print
found_require = 1
in_require = 1
next
}
# While inside require:, if we reach the next top-level key (non-indented line),
# insert our req_line before it (unless already inserted), then continue.
in_require && $0 ~ /^[^[:space:]]/ {
if (!inserted) {
print req_line
inserted = 1
}
in_require = 0
print
next
}
# If we are inside require: and we see list items, just print them.
# (We will insert at the end of the require block when we hit the next top-level key,
# or at EOF if require is the last block.)
{
print
}
END {
if (found_require) {
# require exists and may be the last block; if we never inserted, add at EOF.
if (!inserted) {
print req_line
}
} else {
# No require key at all: append a require block to EOF (with a blank line if needed)
# Note: awk cannot easily know if file ended with newline; this is fine for YAML.
print ""
print "require:"
print req_line
}
}
' "$CONFIG" > "$tmp"
# Replace atomically-ish
mv "$tmp" "$CONFIG"
trap - EXIT