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