diff options
author | Aki <please@ignore.pl> | 2023-04-15 16:07:53 +0200 |
---|---|---|
committer | Aki <please@ignore.pl> | 2023-04-15 16:07:53 +0200 |
commit | d6be952107111b6cca325ec366a2bdddb6fcd071 (patch) | |
tree | 980337cc729f997c23fa64da17c3495d36ab918b /url.py | |
download | url-master.zip url-master.tar.gz url-master.tar.bz2 |
Diffstat (limited to 'url.py')
-rw-r--r-- | url.py | 58 |
1 files changed, 58 insertions, 0 deletions
@@ -0,0 +1,58 @@ +#!/usr/bin/env python +""" +Translates URLs based on a format string. All occurrences of ``'%' letter`` patterns in format are tried to be +substituted with a component from the given URL. Following patterns are supported: + + * ``'%s'``: Scheme + * ``'%l'``: Network location + * ``'%p'``: Path + * ``'%q'``: Query + * ``'%f'``: Fragment + * ``'%u'``: Username + * ``'%w'``: Password + * ``'%h'``: Hostname + * ``'%o'``: Port + * ``'%%'``: Literal ``'%'`` + +To use see url.rewrite() or CLI utility. +""" + +import argparse +import re +from urllib.parse import urlsplit + + +def rewrite(url, fmt): + "Translates *url* to *fmt*." + url = urlsplit(url) + mapping = { + "s": url.scheme, + "l": url.netloc, + "p": url.path, + "q": url.query, + "f": url.fragment, + "u": url.username or "", + "w": url.password or "", + "h": url.hostname or "", + "o": url.port or "", + "%": "%", + } + regex = re.compile(f"%([{''.join(mapping.keys())}])") + + def _replace(match): + return mapping[match.group(1)] + + return regex.sub(_replace, fmt) + + +def main(): + "Translates URL to FMT." + parser = argparse.ArgumentParser(description=main.__doc__) + parser.add_argument("FMT") + parser.add_argument("URL") + args = parser.parse_args() + print(rewrite(args.URL, args.FMT)) + + +if __name__ == "__main__": + main() |