compat.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. from __future__ import unicode_literals
  2. import collections
  3. import getpass
  4. import optparse
  5. import os
  6. import re
  7. import shutil
  8. import socket
  9. import subprocess
  10. import sys
  11. try:
  12. import urllib.request as compat_urllib_request
  13. except ImportError: # Python 2
  14. import urllib2 as compat_urllib_request
  15. try:
  16. import urllib.error as compat_urllib_error
  17. except ImportError: # Python 2
  18. import urllib2 as compat_urllib_error
  19. try:
  20. import urllib.parse as compat_urllib_parse
  21. except ImportError: # Python 2
  22. import urllib as compat_urllib_parse
  23. try:
  24. from urllib.parse import urlparse as compat_urllib_parse_urlparse
  25. except ImportError: # Python 2
  26. from urlparse import urlparse as compat_urllib_parse_urlparse
  27. try:
  28. import urllib.parse as compat_urlparse
  29. except ImportError: # Python 2
  30. import urlparse as compat_urlparse
  31. try:
  32. import http.cookiejar as compat_cookiejar
  33. except ImportError: # Python 2
  34. import cookielib as compat_cookiejar
  35. try:
  36. import html.entities as compat_html_entities
  37. except ImportError: # Python 2
  38. import htmlentitydefs as compat_html_entities
  39. try:
  40. import http.client as compat_http_client
  41. except ImportError: # Python 2
  42. import httplib as compat_http_client
  43. try:
  44. from urllib.error import HTTPError as compat_HTTPError
  45. except ImportError: # Python 2
  46. from urllib2 import HTTPError as compat_HTTPError
  47. try:
  48. from urllib.request import urlretrieve as compat_urlretrieve
  49. except ImportError: # Python 2
  50. from urllib import urlretrieve as compat_urlretrieve
  51. try:
  52. from subprocess import DEVNULL
  53. compat_subprocess_get_DEVNULL = lambda: DEVNULL
  54. except ImportError:
  55. compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
  56. try:
  57. import http.server as compat_http_server
  58. except ImportError:
  59. import BaseHTTPServer as compat_http_server
  60. try:
  61. from urllib.parse import unquote as compat_urllib_parse_unquote
  62. except ImportError:
  63. def compat_urllib_parse_unquote(string, encoding='utf-8', errors='replace'):
  64. if string == '':
  65. return string
  66. res = string.split('%')
  67. if len(res) == 1:
  68. return string
  69. if encoding is None:
  70. encoding = 'utf-8'
  71. if errors is None:
  72. errors = 'replace'
  73. # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
  74. pct_sequence = b''
  75. string = res[0]
  76. for item in res[1:]:
  77. try:
  78. if not item:
  79. raise ValueError
  80. pct_sequence += item[:2].decode('hex')
  81. rest = item[2:]
  82. if not rest:
  83. # This segment was just a single percent-encoded character.
  84. # May be part of a sequence of code units, so delay decoding.
  85. # (Stored in pct_sequence).
  86. continue
  87. except ValueError:
  88. rest = '%' + item
  89. # Encountered non-percent-encoded characters. Flush the current
  90. # pct_sequence.
  91. string += pct_sequence.decode(encoding, errors) + rest
  92. pct_sequence = b''
  93. if pct_sequence:
  94. # Flush the final pct_sequence
  95. string += pct_sequence.decode(encoding, errors)
  96. return string
  97. try:
  98. compat_str = unicode # Python 2
  99. except NameError:
  100. compat_str = str
  101. try:
  102. compat_basestring = basestring # Python 2
  103. except NameError:
  104. compat_basestring = str
  105. try:
  106. compat_chr = unichr # Python 2
  107. except NameError:
  108. compat_chr = chr
  109. try:
  110. from xml.etree.ElementTree import ParseError as compat_xml_parse_error
  111. except ImportError: # Python 2.6
  112. from xml.parsers.expat import ExpatError as compat_xml_parse_error
  113. try:
  114. from urllib.parse import parse_qs as compat_parse_qs
  115. except ImportError: # Python 2
  116. # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
  117. # Python 2's version is apparently totally broken
  118. def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
  119. encoding='utf-8', errors='replace'):
  120. qs, _coerce_result = qs, compat_str
  121. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  122. r = []
  123. for name_value in pairs:
  124. if not name_value and not strict_parsing:
  125. continue
  126. nv = name_value.split('=', 1)
  127. if len(nv) != 2:
  128. if strict_parsing:
  129. raise ValueError("bad query field: %r" % (name_value,))
  130. # Handle case of a control-name with no equal sign
  131. if keep_blank_values:
  132. nv.append('')
  133. else:
  134. continue
  135. if len(nv[1]) or keep_blank_values:
  136. name = nv[0].replace('+', ' ')
  137. name = compat_urllib_parse_unquote(
  138. name, encoding=encoding, errors=errors)
  139. name = _coerce_result(name)
  140. value = nv[1].replace('+', ' ')
  141. value = compat_urllib_parse_unquote(
  142. value, encoding=encoding, errors=errors)
  143. value = _coerce_result(value)
  144. r.append((name, value))
  145. return r
  146. def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  147. encoding='utf-8', errors='replace'):
  148. parsed_result = {}
  149. pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
  150. encoding=encoding, errors=errors)
  151. for name, value in pairs:
  152. if name in parsed_result:
  153. parsed_result[name].append(value)
  154. else:
  155. parsed_result[name] = [value]
  156. return parsed_result
  157. try:
  158. from shlex import quote as shlex_quote
  159. except ImportError: # Python < 3.3
  160. def shlex_quote(s):
  161. if re.match(r'^[-_\w./]+$', s):
  162. return s
  163. else:
  164. return "'" + s.replace("'", "'\"'\"'") + "'"
  165. def compat_ord(c):
  166. if type(c) is int:
  167. return c
  168. else:
  169. return ord(c)
  170. if sys.version_info >= (3, 0):
  171. compat_getenv = os.getenv
  172. compat_expanduser = os.path.expanduser
  173. else:
  174. # Environment variables should be decoded with filesystem encoding.
  175. # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
  176. def compat_getenv(key, default=None):
  177. from .utils import get_filesystem_encoding
  178. env = os.getenv(key, default)
  179. if env:
  180. env = env.decode(get_filesystem_encoding())
  181. return env
  182. # HACK: The default implementations of os.path.expanduser from cpython do not decode
  183. # environment variables with filesystem encoding. We will work around this by
  184. # providing adjusted implementations.
  185. # The following are os.path.expanduser implementations from cpython 2.7.8 stdlib
  186. # for different platforms with correct environment variables decoding.
  187. if os.name == 'posix':
  188. def compat_expanduser(path):
  189. """Expand ~ and ~user constructions. If user or $HOME is unknown,
  190. do nothing."""
  191. if not path.startswith('~'):
  192. return path
  193. i = path.find('/', 1)
  194. if i < 0:
  195. i = len(path)
  196. if i == 1:
  197. if 'HOME' not in os.environ:
  198. import pwd
  199. userhome = pwd.getpwuid(os.getuid()).pw_dir
  200. else:
  201. userhome = compat_getenv('HOME')
  202. else:
  203. import pwd
  204. try:
  205. pwent = pwd.getpwnam(path[1:i])
  206. except KeyError:
  207. return path
  208. userhome = pwent.pw_dir
  209. userhome = userhome.rstrip('/')
  210. return (userhome + path[i:]) or '/'
  211. elif os.name == 'nt' or os.name == 'ce':
  212. def compat_expanduser(path):
  213. """Expand ~ and ~user constructs.
  214. If user or $HOME is unknown, do nothing."""
  215. if path[:1] != '~':
  216. return path
  217. i, n = 1, len(path)
  218. while i < n and path[i] not in '/\\':
  219. i = i + 1
  220. if 'HOME' in os.environ:
  221. userhome = compat_getenv('HOME')
  222. elif 'USERPROFILE' in os.environ:
  223. userhome = compat_getenv('USERPROFILE')
  224. elif 'HOMEPATH' not in os.environ:
  225. return path
  226. else:
  227. try:
  228. drive = compat_getenv('HOMEDRIVE')
  229. except KeyError:
  230. drive = ''
  231. userhome = os.path.join(drive, compat_getenv('HOMEPATH'))
  232. if i != 1: # ~user
  233. userhome = os.path.join(os.path.dirname(userhome), path[1:i])
  234. return userhome + path[i:]
  235. else:
  236. compat_expanduser = os.path.expanduser
  237. if sys.version_info < (3, 0):
  238. def compat_print(s):
  239. from .utils import preferredencoding
  240. print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
  241. else:
  242. def compat_print(s):
  243. assert isinstance(s, compat_str)
  244. print(s)
  245. try:
  246. subprocess_check_output = subprocess.check_output
  247. except AttributeError:
  248. def subprocess_check_output(*args, **kwargs):
  249. assert 'input' not in kwargs
  250. p = subprocess.Popen(*args, stdout=subprocess.PIPE, **kwargs)
  251. output, _ = p.communicate()
  252. ret = p.poll()
  253. if ret:
  254. raise subprocess.CalledProcessError(ret, p.args, output=output)
  255. return output
  256. if sys.version_info < (3, 0) and sys.platform == 'win32':
  257. def compat_getpass(prompt, *args, **kwargs):
  258. if isinstance(prompt, compat_str):
  259. from .utils import preferredencoding
  260. prompt = prompt.encode(preferredencoding())
  261. return getpass.getpass(prompt, *args, **kwargs)
  262. else:
  263. compat_getpass = getpass.getpass
  264. # Old 2.6 and 2.7 releases require kwargs to be bytes
  265. try:
  266. def _testfunc(x):
  267. pass
  268. _testfunc(**{'x': 0})
  269. except TypeError:
  270. def compat_kwargs(kwargs):
  271. return dict((bytes(k), v) for k, v in kwargs.items())
  272. else:
  273. compat_kwargs = lambda kwargs: kwargs
  274. if sys.version_info < (2, 7):
  275. def compat_socket_create_connection(address, timeout, source_address=None):
  276. host, port = address
  277. err = None
  278. for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  279. af, socktype, proto, canonname, sa = res
  280. sock = None
  281. try:
  282. sock = socket.socket(af, socktype, proto)
  283. sock.settimeout(timeout)
  284. if source_address:
  285. sock.bind(source_address)
  286. sock.connect(sa)
  287. return sock
  288. except socket.error as _:
  289. err = _
  290. if sock is not None:
  291. sock.close()
  292. if err is not None:
  293. raise err
  294. else:
  295. raise socket.error("getaddrinfo returns an empty list")
  296. else:
  297. compat_socket_create_connection = socket.create_connection
  298. # Fix https://github.com/rg3/youtube-dl/issues/4223
  299. # See http://bugs.python.org/issue9161 for what is broken
  300. def workaround_optparse_bug9161():
  301. op = optparse.OptionParser()
  302. og = optparse.OptionGroup(op, 'foo')
  303. try:
  304. og.add_option('-t')
  305. except TypeError:
  306. real_add_option = optparse.OptionGroup.add_option
  307. def _compat_add_option(self, *args, **kwargs):
  308. enc = lambda v: (
  309. v.encode('ascii', 'replace') if isinstance(v, compat_str)
  310. else v)
  311. bargs = [enc(a) for a in args]
  312. bkwargs = dict(
  313. (k, enc(v)) for k, v in kwargs.items())
  314. return real_add_option(self, *bargs, **bkwargs)
  315. optparse.OptionGroup.add_option = _compat_add_option
  316. if hasattr(shutil, 'get_terminal_size'): # Python >= 3.3
  317. compat_get_terminal_size = shutil.get_terminal_size
  318. else:
  319. _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines'])
  320. def compat_get_terminal_size():
  321. columns = compat_getenv('COLUMNS', None)
  322. if columns:
  323. columns = int(columns)
  324. else:
  325. columns = None
  326. lines = compat_getenv('LINES', None)
  327. if lines:
  328. lines = int(lines)
  329. else:
  330. lines = None
  331. try:
  332. sp = subprocess.Popen(
  333. ['stty', 'size'],
  334. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  335. out, err = sp.communicate()
  336. lines, columns = map(int, out.split())
  337. except Exception:
  338. pass
  339. return _terminal_size(columns, lines)
  340. __all__ = [
  341. 'compat_HTTPError',
  342. 'compat_basestring',
  343. 'compat_chr',
  344. 'compat_cookiejar',
  345. 'compat_expanduser',
  346. 'compat_get_terminal_size',
  347. 'compat_getenv',
  348. 'compat_getpass',
  349. 'compat_html_entities',
  350. 'compat_http_client',
  351. 'compat_http_server',
  352. 'compat_kwargs',
  353. 'compat_ord',
  354. 'compat_parse_qs',
  355. 'compat_print',
  356. 'compat_socket_create_connection',
  357. 'compat_str',
  358. 'compat_subprocess_get_DEVNULL',
  359. 'compat_urllib_error',
  360. 'compat_urllib_parse',
  361. 'compat_urllib_parse_unquote',
  362. 'compat_urllib_parse_urlparse',
  363. 'compat_urllib_request',
  364. 'compat_urlparse',
  365. 'compat_urlretrieve',
  366. 'compat_xml_parse_error',
  367. 'shlex_quote',
  368. 'subprocess_check_output',
  369. 'workaround_optparse_bug9161',
  370. ]