depends.py 6.1 KB

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