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