25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

186 lines
5.8 KiB

  1. from __future__ import annotations
  2. import contextlib
  3. import dis
  4. import marshal
  5. import sys
  6. from types import CodeType
  7. from typing import Any, Literal, TypeVar
  8. from packaging.version import Version
  9. from . import _imp
  10. from ._imp import PY_COMPILED, PY_FROZEN, PY_SOURCE, find_module
  11. _T = TypeVar("_T")
  12. __all__ = ['Require', 'find_module']
  13. class Require:
  14. """A prerequisite to building or installing a distribution"""
  15. def __init__(
  16. self,
  17. name,
  18. requested_version,
  19. module,
  20. homepage: str = '',
  21. attribute=None,
  22. format=None,
  23. ) -> None:
  24. if format is None and requested_version is not None:
  25. format = Version
  26. if format is not None:
  27. requested_version = format(requested_version)
  28. if attribute is None:
  29. attribute = '__version__'
  30. self.__dict__.update(locals())
  31. del self.self
  32. def full_name(self):
  33. """Return full package/distribution name, w/version"""
  34. if self.requested_version is not None:
  35. return f'{self.name}-{self.requested_version}'
  36. return self.name
  37. def version_ok(self, version):
  38. """Is 'version' sufficiently up-to-date?"""
  39. return (
  40. self.attribute is None
  41. or self.format is None
  42. or str(version) != "unknown"
  43. and self.format(version) >= self.requested_version
  44. )
  45. def get_version(
  46. self, paths=None, default: _T | Literal["unknown"] = "unknown"
  47. ) -> _T | Literal["unknown"] | None | Any:
  48. """Get version number of installed module, 'None', or 'default'
  49. Search 'paths' for module. If not found, return 'None'. If found,
  50. return the extracted version attribute, or 'default' if no version
  51. attribute was specified, or the value cannot be determined without
  52. importing the module. The version is formatted according to the
  53. requirement's version format (if any), unless it is 'None' or the
  54. supplied 'default'.
  55. """
  56. if self.attribute is None:
  57. try:
  58. f, _p, _i = find_module(self.module, paths)
  59. except ImportError:
  60. return None
  61. if f:
  62. f.close()
  63. return default
  64. v = get_module_constant(self.module, self.attribute, default, paths)
  65. if v is not None and v is not default and self.format is not None:
  66. return self.format(v)
  67. return v
  68. def is_present(self, paths=None):
  69. """Return true if dependency is present on 'paths'"""
  70. return self.get_version(paths) is not None
  71. def is_current(self, paths=None):
  72. """Return true if dependency is present and up-to-date on 'paths'"""
  73. version = self.get_version(paths)
  74. if version is None:
  75. return False
  76. return self.version_ok(str(version))
  77. def maybe_close(f):
  78. @contextlib.contextmanager
  79. def empty():
  80. yield
  81. return
  82. if not f:
  83. return empty()
  84. return contextlib.closing(f)
  85. # Some objects are not available on some platforms.
  86. # XXX it'd be better to test assertions about bytecode instead.
  87. if not sys.platform.startswith('java') and sys.platform != 'cli':
  88. def get_module_constant(
  89. module, symbol, default: _T | int = -1, paths=None
  90. ) -> _T | int | None | Any:
  91. """Find 'module' by searching 'paths', and extract 'symbol'
  92. Return 'None' if 'module' does not exist on 'paths', or it does not define
  93. 'symbol'. If the module defines 'symbol' as a constant, return the
  94. constant. Otherwise, return 'default'."""
  95. try:
  96. f, path, (_suffix, _mode, kind) = info = find_module(module, paths)
  97. except ImportError:
  98. # Module doesn't exist
  99. return None
  100. with maybe_close(f):
  101. if kind == PY_COMPILED:
  102. f.read(8) # skip magic & date
  103. code = marshal.load(f)
  104. elif kind == PY_FROZEN:
  105. code = _imp.get_frozen_object(module, paths)
  106. elif kind == PY_SOURCE:
  107. code = compile(f.read(), path, 'exec')
  108. else:
  109. # Not something we can parse; we'll have to import it. :(
  110. imported = _imp.get_module(module, paths, info)
  111. return getattr(imported, symbol, None)
  112. return extract_constant(code, symbol, default)
  113. def extract_constant(
  114. code: CodeType, symbol: str, default: _T | int = -1
  115. ) -> _T | int | None | Any:
  116. """Extract the constant value of 'symbol' from 'code'
  117. If the name 'symbol' is bound to a constant value by the Python code
  118. object 'code', return that value. If 'symbol' is bound to an expression,
  119. return 'default'. Otherwise, return 'None'.
  120. Return value is based on the first assignment to 'symbol'. 'symbol' must
  121. be a global, or at least a non-"fast" local in the code block. That is,
  122. only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
  123. must be present in 'code.co_names'.
  124. """
  125. if symbol not in code.co_names:
  126. # name's not there, can't possibly be an assignment
  127. return None
  128. name_idx = list(code.co_names).index(symbol)
  129. STORE_NAME = dis.opmap['STORE_NAME']
  130. STORE_GLOBAL = dis.opmap['STORE_GLOBAL']
  131. LOAD_CONST = dis.opmap['LOAD_CONST']
  132. const = default
  133. for byte_code in dis.Bytecode(code):
  134. op = byte_code.opcode
  135. arg = byte_code.arg
  136. if op == LOAD_CONST:
  137. assert arg is not None
  138. const = code.co_consts[arg]
  139. elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL):
  140. return const
  141. else:
  142. const = default
  143. return None
  144. __all__ += ['get_module_constant', 'extract_constant']