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