Skip to content

Instantly share code, notes, and snippets.

@goatfryed
Created August 13, 2024 19:27
Show Gist options
  • Save goatfryed/5d6af2420ea6930da061353fc8131523 to your computer and use it in GitHub Desktop.
Save goatfryed/5d6af2420ea6930da061353fc8131523 to your computer and use it in GitHub Desktop.
sort openapi specs with yq
#!/usr/bin/env bash
set -e
INPUT=$1
# the order of keys. unmentioned keys are sorted ascending after it
TOP_LEVEL_ORDER=(openapi info servers tags paths components)
COMPONENTS_ORDER=(schemas headers parameters requestBodies responses securitySchemes examples)
PROPERTIES_ORDER=(id href title name description status)
sort_by_key_args() {
local args=""
local first=1
for key in "$@"; do
# Escape single quotes in the key
escaped_key=$(printf '%s' "$key" | sed 's/"/\\"/g')
if [ $first -eq 1 ]; then
args+=".key != \"$escaped_key\""
first=0 # Reset the flag after the first iteration
else
args+=", .key != \"$escaped_key\""
fi
done
echo "$args"
}
sort_keys() {
echo "( to_entries | sort_by($(sort_by_key_args $@), .key) | from_entries )"
}
# build the actual yq expression
rules="
(. |= $(sort_keys ${TOP_LEVEL_ORDER[@]}) )
| (.components |= $(sort_keys ${COMPONENTS_ORDER[@]}) )
| ((.. | select(kind == \"map\" and has(\"properties\") and .type == \"object\") | .properties) |= $(sort_keys ${PROPERTIES_ORDER[@]}) )
"
if [ ! -z "$DEBUG" ]; then
echo "$rules"
exit
fi
yq -o=yaml "$rules" "$INPUT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment