compat.py 14 KB

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