depends.py 5.3 KB

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