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