__init__.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import os
  2. import re
  3. import sys
  4. from module.base.decorator import cached_property
  5. from module.logger import logger
  6. """
  7. Importing pkg_resources is so slow, like 0.4 ~ 1.0s, just google it you will find it indeed really slow.
  8. Since it was some kind of standard library there is no way to modify it or speed it up.
  9. So here's a poor but fast implementation of pkg_resources returning the things in need.
  10. To patch:
  11. ```
  12. # Patch pkg_resources before importing adbutils and uiautomator2
  13. from module.device.pkg_resources import get_distribution
  14. # Just avoid being removed by import optimization
  15. _ = get_distribution
  16. ```
  17. """
  18. # Inject sys.modules, pretend we have pkg_resources imported
  19. try:
  20. sys.modules['pkg_resources'] = sys.modules['module.device.pkg_resources']
  21. except KeyError:
  22. logger.error('Patch pkg_resources failed, patch module does not exists')
  23. def remove_suffix(s, suffix):
  24. """
  25. Remove suffix of a string or bytes like `string.removesuffix(suffix)`, which is on Python3.9+
  26. Args:
  27. s (str, bytes):
  28. suffix (str, bytes):
  29. Returns:
  30. str, bytes:
  31. """
  32. return s[:-len(suffix)] if s.endswith(suffix) else s
  33. class FakeDistributionObject:
  34. def __init__(self, dist, version):
  35. self.dist = dist
  36. self.version = version
  37. def __str__(self):
  38. return f'{self.__class__.__name__}({self.dist}={self.version})'
  39. __repr__ = __str__
  40. class PackageCache:
  41. @cached_property
  42. def site_packages(self):
  43. # Just whatever library to locate the `site-packages` directory
  44. import requests
  45. path = os.path.abspath(os.path.join(requests.__file__, '../../'))
  46. return path
  47. @cached_property
  48. def dict_installed_packages(self):
  49. """
  50. Returns:
  51. dict: Key: str, package name
  52. Value: FakeDistributionObject
  53. """
  54. dic = {}
  55. for file in os.listdir(self.site_packages):
  56. # mxnet_cu101-1.6.0.dist-info
  57. # adbutils-0.11.0-py3.7.egg-info
  58. res = re.match(r'^([a-zA-Z0-9._]+)-([a-zA-Z0-9._]+)-', file)
  59. if res:
  60. version = remove_suffix(res.group(2), '.dist')
  61. # version = res.group(2)
  62. obj = FakeDistributionObject(
  63. dist=res.group(1),
  64. version=version,
  65. )
  66. dic[obj.dist] = obj
  67. return dic
  68. PACKAGE_CACHE = PackageCache()
  69. def resource_filename(*args):
  70. if args == ("adbutils", "binaries"):
  71. path = os.path.abspath(os.path.join(PACKAGE_CACHE.site_packages, *args))
  72. return path
  73. def get_distribution(dist):
  74. """Return a current distribution object for a Requirement or string"""
  75. if dist == 'adbutils':
  76. return PACKAGE_CACHE.dict_installed_packages.get(
  77. 'adbutils',
  78. FakeDistributionObject('adbutils', '0.11.0'),
  79. )
  80. if dist == 'uiautomator2':
  81. return PACKAGE_CACHE.dict_installed_packages.get(
  82. 'uiautomator2',
  83. FakeDistributionObject('uiautomator2', '2.16.17'),
  84. )
  85. class DistributionNotFound(Exception):
  86. pass