compat.py 16 KB

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