itsb/jq/helpers.jq

44 lines
2.1 KiB
Plaintext
Raw Normal View History

2020-07-19 12:46:47 +00:00
# Parse URLs into an object with {scheme, netloc, path, params, query, fragment}.
# Similar to Python's urllib.parse.urlparse.
2020-07-19 14:12:01 +00:00
def urlparse: capture("^(?:(?<scheme>[^:/?#]+):)?(?://(?<netloc>[^/?#]*))?(?:(?<path>(?:[^?#]+/)?[^?#;]*)(?:;(?<params>[^?#/]*))?)?(?:\\?(?<query>[^#]*))?(?:#(?<fragment>.*))?$");
2020-07-19 12:46:47 +00:00
# Parse URLs into an object with {scheme, netloc, path, query, fragment}. Path parameters are not parsed.
# Similar to Python's urllib.parse.urlsplit.
2020-07-19 14:12:01 +00:00
def urlsplit: capture("^(?:(?<scheme>[^:/?#]+):)?(?://(?<netloc>[^/?#]*))?(?<path>(?:[^?#]+/)?[^?#]*)?(?:\\?(?<query>[^#]*))?(?:#(?<fragment>.*))?$");
2020-07-19 12:46:47 +00:00
# Reverse operation of either urlparse or urlsplit.
def urlunparse:
(if .scheme then .scheme + "://" else "" end)
+ (.netloc // "")
+ (.path // "")
+ (if .params then ";" + .params else "" end)
+ (if .query then "?" + .query else "" end)
+ (if .fragment then "#" + .fragment else "" end);
# Resolve a possibly relative URI into an absolute URI.
def urlresolve(base):
(if type == "string" then urlsplit else . end) as $parsed
# There is a scheme: this is an absolute URL
| if $parsed.scheme then . else (
base|(if type == "string" then urlsplit else . end) as $parsedbase
# No scheme but a domain: use the base's scheme
| $parsed
| if .netloc then (
.scheme = $parsedbase.scheme
# No scheme and no domain: resolve the relative URI
) elif .path then (
.scheme = $parsedbase.scheme
| .netloc = $parsedbase.netloc
# When the path does not start with a slash, make it relative to the base's path
# Note that this assumes the base URL always points to a folder, even if it does not end with a /
| if .path|startswith("/")|not then (
.path = (($parsedbase.path|rtrimstr("/")) + "/" + ($parsed.path|ltrimstr("/")))
) else . end
) elif (.query // .fragment) then (
.scheme = $parsedbase.scheme
| .netloc = $parsedbase.netloc
| .path = $parsedbase.path
) else . end
| urlunparse
) end;