__init__.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import os
  2. import sys
  3. import warnings
  4. import xml.etree.ElementTree as etree
  5. from . import re
  6. from ._deprecated import * # noqa: F401, F403
  7. from .compat_utils import passthrough_module
  8. # XXX: Implement this the same way as other DeprecationWarnings without circular import
  9. try:
  10. passthrough_module(__name__, '._legacy', callback=lambda attr: warnings.warn(
  11. DeprecationWarning(f'{__name__}.{attr} is deprecated'), stacklevel=2))
  12. HAS_LEGACY = True
  13. except ModuleNotFoundError:
  14. # Keep working even without _legacy module
  15. HAS_LEGACY = False
  16. del passthrough_module
  17. # HTMLParseError has been deprecated in Python 3.3 and removed in
  18. # Python 3.5. Introducing dummy exception for Python >3.5 for compatible
  19. # and uniform cross-version exception handling
  20. class compat_HTMLParseError(Exception):
  21. pass
  22. class _TreeBuilder(etree.TreeBuilder):
  23. def doctype(self, name, pubid, system):
  24. pass
  25. def compat_etree_fromstring(text):
  26. return etree.XML(text, parser=etree.XMLParser(target=_TreeBuilder()))
  27. compat_os_name = os._name if os.name == 'java' else os.name
  28. if compat_os_name == 'nt':
  29. def compat_shlex_quote(s):
  30. return s if re.match(r'^[-_\w./]+$', s) else '"%s"' % s.replace('"', '\\"')
  31. else:
  32. from shlex import quote as compat_shlex_quote # noqa: F401
  33. def compat_ord(c):
  34. return c if isinstance(c, int) else ord(c)
  35. if compat_os_name == 'nt' and sys.version_info < (3, 8):
  36. # os.path.realpath on Windows does not follow symbolic links
  37. # prior to Python 3.8 (see https://bugs.python.org/issue9949)
  38. def compat_realpath(path):
  39. while os.path.islink(path):
  40. path = os.path.abspath(os.readlink(path))
  41. return os.path.realpath(path)
  42. else:
  43. compat_realpath = os.path.realpath
  44. # Python 3.8+ does not honor %HOME% on windows, but this breaks compatibility with youtube-dl
  45. # See https://github.com/yt-dlp/yt-dlp/issues/792
  46. # https://docs.python.org/3/library/os.path.html#os.path.expanduser
  47. if compat_os_name in ('nt', 'ce'):
  48. def compat_expanduser(path):
  49. HOME = os.environ.get('HOME')
  50. if not HOME:
  51. return os.path.expanduser(path)
  52. elif not path.startswith('~'):
  53. return path
  54. i = path.replace('\\', '/', 1).find('/') # ~user
  55. if i < 0:
  56. i = len(path)
  57. userhome = os.path.join(os.path.dirname(HOME), path[1:i]) if i > 1 else HOME
  58. return userhome + path[i:]
  59. else:
  60. compat_expanduser = os.path.expanduser