Debian Codegraph @

mechanize/polyglot.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # vim:fileencoding=utf-8
3 # Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
4
5 from __future__ import (absolute_import, division, print_function,
6 unicode_literals)
7
8 import collections
9 import sys
10
11 is_py2 = sys.version_info.major < 3
12
13 if is_py2:
14 import types
15 from urllib import (
16 urlencode, pathname2url, quote, addinfourl, quote_plus,
17 urlopen, splitattr, splithost as urllib_splithost, getproxies,
18 ftpwrapper, proxy_bypass as urllib_proxy_bypass, splitpasswd,
19 splitport, splittype, splituser, splitvalue,
20 unquote, unwrap, url2pathname
21 )
22 from urllib2 import (
23 HTTPError, URLError, install_opener, build_opener, ProxyHandler
24 )
25 from robotparser import RobotFileParser
26 from urlparse import urlsplit, urljoin, urlparse, urlunparse
27 from httplib import HTTPMessage, HTTPConnection, HTTPSConnection
28 from cookielib import (
29 DEFAULT_HTTP_PORT, CookiePolicy, DefaultCookiePolicy,
30 FileCookieJar, LoadError, LWPCookieJar, _debug, domain_match,
31 eff_request_host, escape_path, is_HDN, lwp_cookie_str, reach,
32 request_path, request_port, user_domain_match, Cookie, CookieJar,
33 MozillaCookieJar, request_host)
34 from cStringIO import StringIO
35 from future_builtins import map # noqa
36
37 def is_string(x):
38 return isinstance(x, basestring)
39
40 def iteritems(x):
41 return x.iteritems()
42
43 def itervalues(x):
44 return x.itervalues()
45
46 def is_class(obj):
47 return isinstance(obj, (types.ClassType, type))
48
49 def raise_with_traceback(exc):
50 exec('raise exc, None, sys.exc_info()[2]')
51
52 def is_mapping(x):
53 return isinstance(x, collections.Mapping)
54
55 codepoint_to_chr = unichr
56 unicode_type = unicode
57 create_response_info = HTTPMessage
58
59
60 else:
61 import re
62 from urllib.error import HTTPError, URLError
63 from urllib.robotparser import RobotFileParser
64 from urllib.parse import (
65 urlsplit, urljoin, urlparse, urlunparse, urlencode, quote_plus,
66 unquote, unwrap, quote
67 )
68 from urllib.request import (
69 pathname2url, addinfourl, install_opener, build_opener,
70 ProxyHandler, urlopen as _urlopen, getproxies, ftpwrapper,
71 proxy_bypass as urllib_proxy_bypass, url2pathname, Request)
72 from http.client import (
73 HTTPMessage, parse_headers, HTTPConnection,
74 HTTPSConnection)
75 from http.cookiejar import (
76 DEFAULT_HTTP_PORT, CookiePolicy, DefaultCookiePolicy,
77 FileCookieJar, LoadError, LWPCookieJar, _debug, domain_match,
78 eff_request_host, escape_path, is_HDN, lwp_cookie_str, reach,
79 request_path, request_port, user_domain_match, Cookie, CookieJar,
80 MozillaCookieJar, request_host)
81 from io import StringIO
82
83 def splitattr(url):
84 words = url.split(';')
85 return words[0], words[1:]
86
87 def is_string(x):
88 return isinstance(x, str)
89
90 def iteritems(x):
91 return x.items()
92
93 def itervalues(x):
94 return x.values()
95
96 def is_class(obj):
97 return isinstance(obj, type)
98
99 def raise_with_traceback(exc):
100 raise exc.with_traceback(sys.exc_info()[2])
101
102 codepoint_to_chr = chr
103 unicode_type = str
104 map = map
105
106 # Legacy code expects HTTPMessage.getheaders()
107 def getheaders(self, name):
108 return self.get_all(name, failobj=[])
109 HTTPMessage.getheaders = getheaders
110
111 # We want __getitem__ to return the last header not the first
112 def getitem(self, name):
113 vals = self.get_all(name, [None])
114 return vals[-1]
115 HTTPMessage.__getitem__ = getitem
116
117 # Legacy method names
118 HTTPMessage.gettype = HTTPMessage.get_content_type
119 HTTPMessage.getmainttype = HTTPMessage.get_content_maintype
120 HTTPMessage.getsubtype = HTTPMessage.get_content_subtype
121
122 def is_mapping(x):
123 return isinstance(x, collections.abc.Mapping)
124
125 def create_response_info(fp):
126 return parse_headers(fp)
127
128 def urlopen(*a, **kw):
129 proxies = kw.pop('proxies', None)
130 if proxies is None:
131 return _urlopen(*a, **kw)
132 r = Request(a[0])
133 for k, v in proxies.items():
134 r.set_proxy(v, k)
135 return _urlopen(r, *a[1:], **kw)
136
137 _hostprog = None
138
139 def urllib_splithost(url):
140 """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
141 global _hostprog
142 if _hostprog is None:
143 _hostprog = re.compile('//([^/#?]*)(.*)', re.DOTALL)
144
145 match = _hostprog.match(url)
146 if match:
147 host_port, path = match.groups()
148 if path and path[0] != '/':
149 path = '/' + path
150 return host_port, path
151 return None, url
152
153 _typeprog = None
154
155 def splittype(url):
156 """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
157 global _typeprog
158 if _typeprog is None:
159 _typeprog = re.compile('([^/:]+):(.*)', re.DOTALL)
160
161 match = _typeprog.match(url)
162 if match:
163 scheme, data = match.groups()
164 return scheme.lower(), data
165 return None, url
166
167 def splituser(host):
168 """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
169 user, delim, host = host.rpartition('@')
170 return (user if delim else None), host
171
172 def splitpasswd(user):
173 """splitpasswd('user:passwd') -> 'user', 'passwd'."""
174 user, delim, passwd = user.partition(':')
175 return user, (passwd if delim else None)
176
177 _portprog = None
178
179 def splitport(host):
180 """splitport('host:port') --> 'host', 'port'."""
181 global _portprog
182 if _portprog is None:
183 _portprog = re.compile('(.*):([0-9]*)$', re.DOTALL)
184
185 match = _portprog.match(host)
186 if match:
187 host, port = match.groups()
188 if port:
189 return host, port
190 return host, None
191
192 def splitvalue(attr):
193 """splitvalue('attr=value') --> 'attr', 'value'."""
194 attr, delim, value = attr.partition('=')
195 return attr, (value if delim else None)
196
197
198 def as_unicode(x, encoding='utf-8', errors='strict'):
199 if isinstance(x, bytes):
200 x = x.decode('utf-8', errors=errors)
201 return x
202
203
204 if False:
205 (HTTPError, urlsplit, urljoin, urlparse, urlunparse, urlencode,
206 HTTPMessage, splitattr, urllib_splithost, getproxies, ftpwrapper,
207 urllib_proxy_bypass, splituser, splitpasswd, splitport,
208 splitvalue, splittype, unquote, unwrap, url2pathname)
209 pathname2url, RobotFileParser, URLError, quote, HTTPConnection
210 HTTPSConnection, StringIO, addinfourl, install_opener, build_opener
211 ProxyHandler, quote_plus, urlopen
212 (DEFAULT_HTTP_PORT, CookiePolicy, DefaultCookiePolicy,
213 FileCookieJar, LoadError, LWPCookieJar, _debug,
214 domain_match, eff_request_host, escape_path, is_HDN,
215 lwp_cookie_str, reach, request_path, request_port,
216 user_domain_match, Cookie, CookieJar, MozillaCookieJar, request_host)