Last active
April 2, 2025 17:38
-
-
Save tj-smith47/a2bfd15211ded59d56055a3fcdb4b9e7 to your computer and use it in GitHub Desktop.
yqi | retain newlines & list indentation with `yq e -i`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
get_yamlfmt_config() { | |
# $1 == file | |
cat <<EOF | |
formatter: | |
indentless_arrays: $( | |
first_list=$(grep -m 1 -B 1 '^ .* -' $1) | |
# If the first entry whitespace is not in (or is larger than) the list name whitespace - it's indented. | |
if ! grep -q "$(tail -n 1 <<<"$first_list" | cut -d'-' -f 1)" <<<"$(head -n 1 <<<"$first_list")"; then | |
echo "false" | |
else | |
echo "true" | |
fi | |
) | |
retain_line_breaks_single: true | |
trim_trailing_whitespace: true | |
EOF | |
} | |
yqi() { | |
# $1 == expression | $2 == file | |
# Must get yamlfmt conf pre-edit | |
conf=$(get_yamlfmt_config $2) | |
# Replace empty lines with placeholder comment -> update -> diff -> patch | |
file=$(sed 's/^$/# line/' $2 | yq eval $1 | diff -B $2 - | patch $2 -o -) | |
# Patching prints - remove that line and delete placeholder comments | |
echo -e "$(grep -v '^patching' <<<${file} | sed 's/^# line$//g')" >$2 | |
# Format in place using initial fmt config | |
yamlfmt -conf <(echo -e $conf) $2 | |
} | |
# Ensure `yamlfmt` - can remove / comment out after first use or running directly | |
command -v yamlfmt &>/dev/null || go install github.com/google/yamlfmt/cmd/yamlfmt@latest | |
# Uncomment if you just want to throw this in your PATH (e.g., download to ~/.local/bin/yqi) | |
# and run it directly as opposed to adding to your shell's rc file. | |
# yqi "$1" "$2" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment