summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore4
-rw-r--r--pyproject.toml20
-rw-r--r--url.py58
3 files changed, 82 insertions, 0 deletions
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()