packages.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import sys
  2. import pkg_resources
  3. def get_package_version(module_name, app):
  4. version = None
  5. # Try to pull version from pkg_resource first
  6. # as it is able to detect version tagged with egg_info -b
  7. if pkg_resources is not None:
  8. # pull version from pkg_resources if distro exists
  9. try:
  10. return pkg_resources.get_distribution(module_name).version
  11. except Exception:
  12. pass
  13. if hasattr(app, "get_version"):
  14. version = app.get_version
  15. elif hasattr(app, "__version__"):
  16. version = app.__version__
  17. elif hasattr(app, "VERSION"):
  18. version = app.VERSION
  19. elif hasattr(app, "version"):
  20. version = app.version
  21. if callable(version):
  22. try:
  23. version = version()
  24. except Exception:
  25. return None
  26. if not isinstance(version, (str,) + (list, tuple)):
  27. version = None
  28. if version is None:
  29. return None
  30. if isinstance(version, (list, tuple)):
  31. version = ".".join(map(str, version))
  32. return str(version)
  33. def get_all_package_versions():
  34. packages = {}
  35. for module_name, app in sys.modules.items():
  36. # ignore items that look like submodules
  37. if "." in module_name:
  38. continue
  39. if "sys" == module_name:
  40. continue
  41. version = get_package_version(module_name, app)
  42. if version is None:
  43. continue
  44. packages[module_name] = version
  45. packages["sys"] = "{}.{}.{}".format(*sys.version_info)
  46. return packages