utils.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from importlib import import_module
  2. from operator import attrgetter
  3. try:
  4. from collections import OrderedDict
  5. except ImportError:
  6. from ordereddict import OrderedDict
  7. import sys
  8. from reqPackage import ReqPackage
  9. from distPackage import DistPackage
  10. __version__ = '0.10.1'
  11. def build_dist_index(pkgs):
  12. """Build an index pkgs by their key as a dict.
  13. :param list pkgs: list of pkg_resources.Distribution instances
  14. :returns: index of the pkgs by the pkg key
  15. :rtype: dict
  16. """
  17. return dict((p.key, DistPackage(p)) for p in pkgs)
  18. def construct_tree(index):
  19. """Construct tree representation of the pkgs from the index.
  20. The keys of the dict representing the tree will be objects of type
  21. DistPackage and the values will be list of ReqPackage objects.
  22. :param dict index: dist index ie. index of pkgs by their keys
  23. :returns: tree of pkgs and their dependencies
  24. :rtype: dict
  25. """
  26. return dict((p, [ReqPackage(r, index.get(r.key))
  27. for r in p.requires()])
  28. for p in index.values())
  29. def sorted_tree(tree):
  30. """Sorts the dict representation of the tree
  31. The root packages as well as the intermediate packages are sorted
  32. in the alphabetical order of the package names.
  33. :param dict tree: the pkg dependency tree obtained by calling
  34. `construct_tree` function
  35. :returns: sorted tree
  36. :rtype: collections.OrderedDict
  37. """
  38. return OrderedDict(sorted([(k, sorted(v, key=attrgetter('key')))
  39. for k, v in tree.items()],
  40. key=lambda kv: kv[0].key))
  41. def guess_version(pkg_key, default='?'):
  42. """Guess the version of a pkg when pip doesn't provide it
  43. :param str pkg_key: key of the package
  44. :param str default: default version to return if unable to find
  45. :returns: version
  46. :rtype: string
  47. """
  48. try:
  49. m = import_module(pkg_key)
  50. except ImportError:
  51. return default
  52. else:
  53. return getattr(m, '__version__', default)
  54. def is_string(obj):
  55. """Check whether an object is a string"""
  56. if sys.version_info < (3,):
  57. # Python 2.x only
  58. return isinstance(obj, basestring)
  59. else:
  60. return isinstance(obj, str)