]> git.phdru.name Git - dotfiles.git/blob - bin/webbrowser-encode-url
Feat(recode-filenames-recursive): Allow to omit parameters
[dotfiles.git] / bin / webbrowser-encode-url
1 #! /usr/bin/env python3
2
3 from getopt import getopt, GetoptError
4 from urllib.parse import urlsplit, parse_qsl, quote, quote_plus, urlencode
5 import sys
6
7 from m_lib.defenc import default_encoding
8
9 # This must be imported and called before webbrowser
10 # because webbrowser reads BROWSER environment variable at the import time
11 from browser_stack import set_current_browser
12 set_current_browser()
13
14 import webbrowser  # noqa: E402 module level import not at top of file
15
16
17 def usage():
18     sys.exit('Usage: %s [-e|--encoding=encoding] [-n|--newwin|-t|--tab] URL'
19              % sys.argv[0])
20
21
22 try:
23     options, arguments = getopt(
24         sys.argv[1:], 'e:nt', ['encoding=', 'newwin', 'tab'])
25 except GetoptError:
26     usage()
27
28 if len(arguments) != 1:
29     usage()
30
31 encoding = None
32 new = 0
33
34 for option, value in options:
35     if option in ('-e', '--encoding'):
36         encoding = value
37     elif option in ('-n', '--newwin'):
38         new = 1
39     elif option in ('-t', '--tab'):
40         new = 2
41
42 if not encoding:
43     encoding = default_encoding
44
45 url = arguments[0]
46
47 split_results = urlsplit(url)
48 protocol, netloc, path, query, tag = split_results
49 user = split_results.username
50 password = split_results.password
51 host = split_results.hostname
52 port = split_results.port
53
54 if query:
55     qlist = []
56     for name, value in parse_qsl(query):
57         if isinstance(name, bytes):
58             name = name.decode(default_encoding)
59             value = value.decode(default_encoding)
60         name = name.encode(encoding)
61         value = value.encode(encoding)
62         qlist.append((name, value))
63
64 url = protocol + "://"
65 if user:
66     if isinstance(user, bytes):
67         user = user.decode(default_encoding)
68     url += quote(user.encode(encoding))
69     if password:
70         if isinstance(password, bytes):
71             password = password.decode(default_encoding)
72         url += ':' + quote(password.encode(encoding))
73     url += '@'
74 if host:
75     if isinstance(host, bytes):
76         host = host.decode(encoding)
77     url += host.encode('idna').decode('ascii')
78     if port:
79         url += ':%d' % port
80 if path:
81     if protocol == "file":
82         url += quote(path)
83     else:
84         if isinstance(path, bytes):
85             path = path.decode(default_encoding)
86         url += quote(path.encode(encoding))
87 if query:
88     url += '?' + urlencode(qlist)
89 if tag:
90     if isinstance(tag, bytes):
91         tag = tag.decode(default_encoding)
92     url += '#' + quote_plus(tag.encode(encoding))
93
94 webbrowser.open(url, new)