list.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import importlib
  3. import os.path as osp
  4. import pkg_resources
  5. from email.parser import FeedParser
  6. from typing import List, Tuple
  7. import click
  8. from tabulate import tabulate
  9. @click.command('list')
  10. @click.option(
  11. '--all',
  12. is_flag=True,
  13. help='List packages of OpenMMLab projects or all the packages in the '
  14. 'python environment.')
  15. def cli(all: bool = True) -> None:
  16. """List packages.
  17. \b
  18. Example:
  19. > mim list
  20. > mim list --all
  21. """
  22. table_header = ['Package', 'Version', 'Source']
  23. table_data = list_package(all=all)
  24. click.echo(tabulate(table_data, headers=table_header, tablefmt='simple'))
  25. def list_package(all: bool = False) -> List[Tuple[str, ...]]:
  26. """List packages.
  27. List packages of OpenMMLab projects or all the packages in the python
  28. environment.
  29. Args:
  30. all (bool): List all installed packages. If all is False, it just lists
  31. the packages installed by mim. Default: False.
  32. """
  33. # refresh the pkg_resources
  34. # more datails at https://github.com/pypa/setuptools/issues/373
  35. importlib.reload(pkg_resources)
  36. pkgs_info: List[Tuple[str, ...]] = []
  37. for pkg in pkg_resources.working_set:
  38. pkg_name = pkg.project_name
  39. if all:
  40. pkgs_info.append((pkg_name, pkg.version))
  41. else:
  42. installed_path = osp.join(pkg.location, pkg_name)
  43. if not osp.exists(installed_path):
  44. module_name = None
  45. if pkg.has_metadata('top_level.txt'):
  46. module_name = pkg.get_metadata('top_level.txt').split(
  47. '\n')[0]
  48. if module_name:
  49. installed_path = osp.join(pkg.location, module_name)
  50. else:
  51. continue
  52. home_page = pkg.location
  53. if pkg.has_metadata('METADATA'):
  54. metadata = pkg.get_metadata('METADATA')
  55. feed_parser = FeedParser()
  56. feed_parser.feed(metadata)
  57. home_page = feed_parser.close().get('home-page')
  58. if pkg_name.startswith('mmcv'):
  59. pkgs_info.append((pkg_name, pkg.version, home_page))
  60. continue
  61. possible_metadata_paths = [
  62. osp.join(installed_path, '.mim', 'save_models-index.yml'),
  63. osp.join(installed_path, 'save_models-index.yml'),
  64. osp.join(installed_path, '.mim', 'model_zoo.yml'),
  65. osp.join(installed_path, 'model_zoo.yml')
  66. ]
  67. for path in possible_metadata_paths:
  68. if osp.exists(path):
  69. pkgs_info.append((pkg_name, pkg.version, home_page))
  70. break
  71. pkgs_info.sort(key=lambda pkg_info: pkg_info[0])
  72. return pkgs_info