Find Basepath From Api Specification Documents

PHOTO EMBED

Sat Jun 24 2023 21:15:59 GMT+0000 (Coordinated Universal Time)

Saved by @anderneo #shellscript

swagger_filepath=$1

json_content=$(yq -r -o=json "$swagger_filepath")
swagger_version=$(echo "$json_content" | jq -r '.swagger // ""')
openapi_version=$(echo "$json_content" | jq -r '.openapi // ""')

if [[ -n "$swagger_version" ]]; then
    basepath=$(echo "$json_content" | jq -r '.basePath // ""')
elif [[ -n "$openapi_version" ]]; then

    url=$(yq e '.servers[0].url' $swagger_filepath)

    before_string="//"

    find_char="/"

    before_string_index=$(awk -v a="$url" -v b="$before_string" 'BEGIN{print index(a,b)}')

    if [[ $before_string_index -ne 0 ]]; then
        substring=${url#*$before_string}

        find_char_index=$(awk -v a="$substring" -v b="$find_char" 'BEGIN{print index(a,b)}')

        if [[ $find_char_index -ne 0 ]]; then
            basepath="$find_char${substring#*$find_char}"
        else
            basepath=$find_char
        fi
    else
        basepath=$find_char
    fi

else
    echo "Unknown Swagger document version"
    exit 1
fi

echo "basepath = $basepath"
content_copyCOPY