blob: e16983caeacc6fbaf16537d05673dea5a74014f4 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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()
|