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.
 
 
 
 

216 regels
6.2 KiB

  1. import sys
  2. import imp
  3. import marshal
  4. from imp import PKG_DIRECTORY, PY_COMPILED, PY_SOURCE, PY_FROZEN
  5. from distutils.version import StrictVersion
  6. from setuptools import compat
  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: f.close()
  44. return default
  45. except ImportError:
  46. return None
  47. v = get_module_constant(self.module, self.attribute, default, paths)
  48. if v is not None and v is not default and self.format is not None:
  49. return self.format(v)
  50. return v
  51. def is_present(self, paths=None):
  52. """Return true if dependency is present on 'paths'"""
  53. return self.get_version(paths) is not None
  54. def is_current(self, paths=None):
  55. """Return true if dependency is present and up-to-date on 'paths'"""
  56. version = self.get_version(paths)
  57. if version is None:
  58. return False
  59. return self.version_ok(version)
  60. def _iter_code(code):
  61. """Yield '(op,arg)' pair for each operation in code object 'code'"""
  62. from array import array
  63. from dis import HAVE_ARGUMENT, EXTENDED_ARG
  64. bytes = array('b',code.co_code)
  65. eof = len(code.co_code)
  66. ptr = 0
  67. extended_arg = 0
  68. while ptr<eof:
  69. op = bytes[ptr]
  70. if op>=HAVE_ARGUMENT:
  71. arg = bytes[ptr+1] + bytes[ptr+2]*256 + extended_arg
  72. ptr += 3
  73. if op==EXTENDED_ARG:
  74. extended_arg = arg * compat.long_type(65536)
  75. continue
  76. else:
  77. arg = None
  78. ptr += 1
  79. yield op,arg
  80. def find_module(module, paths=None):
  81. """Just like 'imp.find_module()', but with package support"""
  82. parts = module.split('.')
  83. while parts:
  84. part = parts.pop(0)
  85. f, path, (suffix,mode,kind) = info = imp.find_module(part, paths)
  86. if kind==PKG_DIRECTORY:
  87. parts = parts or ['__init__']
  88. paths = [path]
  89. elif parts:
  90. raise ImportError("Can't find %r in %s" % (parts,module))
  91. return info
  92. def get_module_constant(module, symbol, default=-1, paths=None):
  93. """Find 'module' by searching 'paths', and extract 'symbol'
  94. Return 'None' if 'module' does not exist on 'paths', or it does not define
  95. 'symbol'. If the module defines 'symbol' as a constant, return the
  96. constant. Otherwise, return 'default'."""
  97. try:
  98. f, path, (suffix, mode, kind) = find_module(module, paths)
  99. except ImportError:
  100. # Module doesn't exist
  101. return None
  102. try:
  103. if kind==PY_COMPILED:
  104. f.read(8) # skip magic & date
  105. code = marshal.load(f)
  106. elif kind==PY_FROZEN:
  107. code = imp.get_frozen_object(module)
  108. elif kind==PY_SOURCE:
  109. code = compile(f.read(), path, 'exec')
  110. else:
  111. # Not something we can parse; we'll have to import it. :(
  112. if module not in sys.modules:
  113. imp.load_module(module, f, path, (suffix, mode, kind))
  114. return getattr(sys.modules[module], symbol, None)
  115. finally:
  116. if f:
  117. f.close()
  118. return extract_constant(code, symbol, default)
  119. def extract_constant(code, symbol, default=-1):
  120. """Extract the constant value of 'symbol' from 'code'
  121. If the name 'symbol' is bound to a constant value by the Python code
  122. object 'code', return that value. If 'symbol' is bound to an expression,
  123. return 'default'. Otherwise, return 'None'.
  124. Return value is based on the first assignment to 'symbol'. 'symbol' must
  125. be a global, or at least a non-"fast" local in the code block. That is,
  126. only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'
  127. must be present in 'code.co_names'.
  128. """
  129. if symbol not in code.co_names:
  130. # name's not there, can't possibly be an assigment
  131. return None
  132. name_idx = list(code.co_names).index(symbol)
  133. STORE_NAME = 90
  134. STORE_GLOBAL = 97
  135. LOAD_CONST = 100
  136. const = default
  137. for op, arg in _iter_code(code):
  138. if op==LOAD_CONST:
  139. const = code.co_consts[arg]
  140. elif arg==name_idx and (op==STORE_NAME or op==STORE_GLOBAL):
  141. return const
  142. else:
  143. const = default
  144. def _update_globals():
  145. """
  146. Patch the globals to remove the objects not available on some platforms.
  147. XXX it'd be better to test assertions about bytecode instead.
  148. """
  149. if not sys.platform.startswith('java') and sys.platform != 'cli':
  150. return
  151. incompatible = 'extract_constant', 'get_module_constant'
  152. for name in incompatible:
  153. del globals()[name]
  154. __all__.remove(name)
  155. _update_globals()