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