You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

depends.py 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import sys
  2. import imp
  3. import marshal
  4. from distutils.version import StrictVersion
  5. from imp import PKG_DIRECTORY, PY_COMPILED, PY_SOURCE, PY_FROZEN
  6. from .py33compat import Bytecode
  7. __all__ = [
  8. 'Require', 'find_module', 'get_module_constant', 'extract_constant'
  9. ]
  10. class Require:
  11. """A prerequisite to building or installing a distribution"""
  12. def __init__(self, name, requested_version, module, homepage='',
  13. attribute=None, format=None):
  14. if format is None and requested_version is not None:
  15. format = StrictVersion
  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 self.attribute is None or self.format is None or \
  30. str(version) != "unknown" and version >= self.requested_version
  31. def get_version(self, paths=None, default="unknown"):
  32. """Get version number of installed module, 'None', or 'default'
  33. Search 'paths' for module. If not found, return 'None'. If found,
  34. return the extracted version attribute, or 'default' if no version
  35. attribute was specified, or the value cannot be determined without
  36. importing the module. The version is formatted according to the
  37. requirement's version format (if any), unless it is 'None' or the
  38. supplied 'default'.
  39. """
  40. if self.attribute is None:
  41. try:
  42. f, p, i = find_module(self.module, paths)
  43. if f:
  44. f.close()
  45. return default
  46. except ImportError:
  47. return None
  48. v = get_module_constant(self.module, self.attribute, default, paths)
  49. if v is not None and v is not default and self.format is not None:
  50. return self.format(v)
  51. return v
  52. def is_present(self, paths=None):
  53. """Return true if dependency is present on 'paths'"""
  54. return self.get_version(paths) is not None
  55. def is_current(self, paths=None):
  56. """Return true if dependency is present and up-to-date on 'paths'"""
  57. version = self.get_version(paths)
  58. if version is None:
  59. return False
  60. return self.version_ok(version)
  61. def find_module(module, paths=None):
  62. """Just like 'imp.find_module()', but with package support"""
  63. parts = module.split('.')
  64. while parts:
  65. part = parts.pop(0)
  66. f, path, (suffix, mode, kind) = info = imp.find_module(part, paths)
  67. if kind == PKG_DIRECTORY:
  68. parts = parts or ['__init__']
  69. paths = [path]
  70. elif parts:
  71. raise ImportError("Can't find %r in %s" % (parts, module))
  72. return info
  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) = find_module(module, paths)
  80. except ImportError:
  81. # Module doesn't exist
  82. return None
  83. try:
  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)
  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. if module not in sys.modules:
  94. imp.load_module(module, f, path, (suffix, mode, kind))
  95. return getattr(sys.modules[module], symbol, None)
  96. finally:
  97. if f:
  98. f.close()
  99. return extract_constant(code, symbol, default)
  100. def extract_constant(code, symbol, default=-1):
  101. """Extract the constant value of 'symbol' from 'code'
  102. If the name 'symbol' is bound to a constant value by the Python code
  103. object 'code', return that value. If 'symbol' is bound to an expression,
  104. return 'default'. Otherwise, return 'None'.
  105. Return value is based on the first assignment to 'symbol'. 'symbol' must
  106. be a global, or at least a non-"fast" local in the code block. That is,
  107. only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
  108. must be present in 'code.co_names'.
  109. """
  110. if symbol not in code.co_names:
  111. # name's not there, can't possibly be an assignment
  112. return None
  113. name_idx = list(code.co_names).index(symbol)
  114. STORE_NAME = 90
  115. STORE_GLOBAL = 97
  116. LOAD_CONST = 100
  117. const = default
  118. for byte_code in Bytecode(code):
  119. op = byte_code.opcode
  120. arg = byte_code.arg
  121. if op == LOAD_CONST:
  122. const = code.co_consts[arg]
  123. elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL):
  124. return const
  125. else:
  126. const = default
  127. def _update_globals():
  128. """
  129. Patch the globals to remove the objects not available on some platforms.
  130. XXX it'd be better to test assertions about bytecode instead.
  131. """
  132. if not sys.platform.startswith('java') and sys.platform != 'cli':
  133. return
  134. incompatible = 'extract_constant', 'get_module_constant'
  135. for name in incompatible:
  136. del globals()[name]
  137. __all__.remove(name)
  138. _update_globals()