depends.py 5.5 KB

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