From d6be952107111b6cca325ec366a2bdddb6fcd071 Mon Sep 17 00:00:00 2001 From: Aki Date: Sat, 15 Apr 2023 16:07:53 +0200 Subject: Implemented small utility to rewrite urls from CLI easily --- .gitignore | 4 ++++ pyproject.toml | 20 ++++++++++++++++++++ url.py | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 82 insertions(+) create mode 100644 .gitignore create mode 100644 pyproject.toml create mode 100644 url.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..45c0524 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +__pycache__/ +build/ +dist/ +*.egg-info/ diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..1f47c09 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,20 @@ +[project] +name="url" +dynamic=["version"] + + +[project.scripts] +url="url:main" + + +[tool.setuptools_scm] +fallback_version="0" +version_scheme="post-release" + + +[build-system] +build-backend="setuptools.build_meta" +requires=[ + "setuptools>=45", + "setuptools_scm[toml]>=3.4", +] diff --git a/url.py b/url.py new file mode 100644 index 0000000..e16983c --- /dev/null +++ b/url.py @@ -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() -- cgit v1.1