2022-04-29 03:48:36 +02:00
|
|
|
import collections
|
2022-04-24 18:28:18 +02:00
|
|
|
import contextlib
|
|
|
|
import importlib
|
|
|
|
import sys
|
|
|
|
import types
|
|
|
|
|
2022-04-29 03:48:36 +02:00
|
|
|
_NO_ATTRIBUTE = object()
|
|
|
|
|
|
|
|
_Package = collections.namedtuple('Package', ('name', 'version'))
|
|
|
|
|
|
|
|
|
|
|
|
def get_package_info(module):
|
|
|
|
parent = module.__name__.split('.')[0]
|
|
|
|
parent_module = None
|
|
|
|
with contextlib.suppress(ImportError):
|
|
|
|
parent_module = importlib.import_module(parent)
|
|
|
|
|
|
|
|
for attr in ('__version__', 'version_string', 'version'):
|
|
|
|
version = getattr(parent_module, attr, None)
|
|
|
|
if version is not None:
|
|
|
|
break
|
|
|
|
return _Package(getattr(module, '_yt_dlp__identifier', parent), str(version))
|
|
|
|
|
|
|
|
|
2022-04-24 18:28:18 +02:00
|
|
|
def _is_package(module):
|
|
|
|
try:
|
|
|
|
module.__getattribute__('__path__')
|
|
|
|
except AttributeError:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2022-06-24 12:10:13 +02:00
|
|
|
def passthrough_module(parent, child, allowed_attributes=None, *, callback=lambda _: None):
|
2022-04-24 18:28:18 +02:00
|
|
|
parent_module = importlib.import_module(parent)
|
2022-06-15 14:30:34 +02:00
|
|
|
child_module = None # Import child module only as needed
|
2022-04-24 18:28:18 +02:00
|
|
|
|
|
|
|
class PassthroughModule(types.ModuleType):
|
|
|
|
def __getattr__(self, attr):
|
|
|
|
if _is_package(parent_module):
|
|
|
|
with contextlib.suppress(ImportError):
|
|
|
|
return importlib.import_module(f'.{attr}', parent)
|
|
|
|
|
2022-06-24 12:10:13 +02:00
|
|
|
ret = self.__from_child(attr)
|
|
|
|
if ret is _NO_ATTRIBUTE:
|
|
|
|
raise AttributeError(f'module {parent} has no attribute {attr}')
|
|
|
|
callback(attr)
|
|
|
|
return ret
|
|
|
|
|
|
|
|
def __from_child(self, attr):
|
|
|
|
if allowed_attributes is None:
|
|
|
|
if attr.startswith('__') and attr.endswith('__'):
|
|
|
|
return _NO_ATTRIBUTE
|
|
|
|
elif attr not in allowed_attributes:
|
|
|
|
return _NO_ATTRIBUTE
|
|
|
|
|
2022-06-15 14:30:34 +02:00
|
|
|
nonlocal child_module
|
|
|
|
child_module = child_module or importlib.import_module(child, parent)
|
|
|
|
|
2022-04-24 18:28:18 +02:00
|
|
|
with contextlib.suppress(AttributeError):
|
2022-06-24 12:10:13 +02:00
|
|
|
return getattr(child_module, attr)
|
2022-04-24 18:28:18 +02:00
|
|
|
|
|
|
|
if _is_package(child_module):
|
|
|
|
with contextlib.suppress(ImportError):
|
2022-06-24 12:10:13 +02:00
|
|
|
return importlib.import_module(f'.{attr}', child)
|
2022-04-24 18:28:18 +02:00
|
|
|
|
2022-06-24 12:10:13 +02:00
|
|
|
return _NO_ATTRIBUTE
|
2022-04-24 18:28:18 +02:00
|
|
|
|
|
|
|
# Python 3.6 does not have module level __getattr__
|
|
|
|
# https://peps.python.org/pep-0562/
|
|
|
|
sys.modules[parent].__class__ = PassthroughModule
|