list.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. from __future__ import absolute_import
  2. import json
  3. import logging
  4. from pip._vendor import six
  5. from pip._internal.cli import cmdoptions
  6. from pip._internal.cli.req_command import IndexGroupCommand
  7. from pip._internal.cli.status_codes import SUCCESS
  8. from pip._internal.exceptions import CommandError
  9. from pip._internal.index.collector import LinkCollector
  10. from pip._internal.index.package_finder import PackageFinder
  11. from pip._internal.models.selection_prefs import SelectionPreferences
  12. from pip._internal.utils.misc import (
  13. dist_is_editable,
  14. get_installed_distributions,
  15. tabulate,
  16. write_output,
  17. )
  18. from pip._internal.utils.packaging import get_installer
  19. from pip._internal.utils.parallel import map_multithread
  20. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  21. if MYPY_CHECK_RUNNING:
  22. from optparse import Values
  23. from typing import List, Set, Tuple, Iterator
  24. from pip._internal.network.session import PipSession
  25. from pip._vendor.pkg_resources import Distribution
  26. logger = logging.getLogger(__name__)
  27. class ListCommand(IndexGroupCommand):
  28. """
  29. List installed packages, including editables.
  30. Packages are listed in a case-insensitive sorted order.
  31. """
  32. ignore_require_venv = True
  33. usage = """
  34. %prog [options]"""
  35. def add_options(self):
  36. # type: () -> None
  37. self.cmd_opts.add_option(
  38. '-o', '--outdated',
  39. action='store_true',
  40. default=False,
  41. help='List outdated packages')
  42. self.cmd_opts.add_option(
  43. '-u', '--uptodate',
  44. action='store_true',
  45. default=False,
  46. help='List uptodate packages')
  47. self.cmd_opts.add_option(
  48. '-e', '--editable',
  49. action='store_true',
  50. default=False,
  51. help='List editable projects.')
  52. self.cmd_opts.add_option(
  53. '-l', '--local',
  54. action='store_true',
  55. default=False,
  56. help=('If in a virtualenv that has global access, do not list '
  57. 'globally-installed packages.'),
  58. )
  59. self.cmd_opts.add_option(
  60. '--user',
  61. dest='user',
  62. action='store_true',
  63. default=False,
  64. help='Only output packages installed in user-site.')
  65. self.cmd_opts.add_option(cmdoptions.list_path())
  66. self.cmd_opts.add_option(
  67. '--pre',
  68. action='store_true',
  69. default=False,
  70. help=("Include pre-release and development versions. By default, "
  71. "pip only finds stable versions."),
  72. )
  73. self.cmd_opts.add_option(
  74. '--format',
  75. action='store',
  76. dest='list_format',
  77. default="columns",
  78. choices=('columns', 'freeze', 'json'),
  79. help="Select the output format among: columns (default), freeze, "
  80. "or json",
  81. )
  82. self.cmd_opts.add_option(
  83. '--not-required',
  84. action='store_true',
  85. dest='not_required',
  86. help="List packages that are not dependencies of "
  87. "installed packages.",
  88. )
  89. self.cmd_opts.add_option(
  90. '--exclude-editable',
  91. action='store_false',
  92. dest='include_editable',
  93. help='Exclude editable package from output.',
  94. )
  95. self.cmd_opts.add_option(
  96. '--include-editable',
  97. action='store_true',
  98. dest='include_editable',
  99. help='Include editable package from output.',
  100. default=True,
  101. )
  102. index_opts = cmdoptions.make_option_group(
  103. cmdoptions.index_group, self.parser
  104. )
  105. self.parser.insert_option_group(0, index_opts)
  106. self.parser.insert_option_group(0, self.cmd_opts)
  107. def _build_package_finder(self, options, session):
  108. # type: (Values, PipSession) -> PackageFinder
  109. """
  110. Create a package finder appropriate to this list command.
  111. """
  112. link_collector = LinkCollector.create(session, options=options)
  113. # Pass allow_yanked=False to ignore yanked versions.
  114. selection_prefs = SelectionPreferences(
  115. allow_yanked=False,
  116. allow_all_prereleases=options.pre,
  117. )
  118. return PackageFinder.create(
  119. link_collector=link_collector,
  120. selection_prefs=selection_prefs,
  121. )
  122. def run(self, options, args):
  123. # type: (Values, List[str]) -> int
  124. if options.outdated and options.uptodate:
  125. raise CommandError(
  126. "Options --outdated and --uptodate cannot be combined.")
  127. cmdoptions.check_list_path_option(options)
  128. packages = get_installed_distributions(
  129. local_only=options.local,
  130. user_only=options.user,
  131. editables_only=options.editable,
  132. include_editables=options.include_editable,
  133. paths=options.path,
  134. )
  135. # get_not_required must be called firstly in order to find and
  136. # filter out all dependencies correctly. Otherwise a package
  137. # can't be identified as requirement because some parent packages
  138. # could be filtered out before.
  139. if options.not_required:
  140. packages = self.get_not_required(packages, options)
  141. if options.outdated:
  142. packages = self.get_outdated(packages, options)
  143. elif options.uptodate:
  144. packages = self.get_uptodate(packages, options)
  145. self.output_package_listing(packages, options)
  146. return SUCCESS
  147. def get_outdated(self, packages, options):
  148. # type: (List[Distribution], Values) -> List[Distribution]
  149. return [
  150. dist for dist in self.iter_packages_latest_infos(packages, options)
  151. if dist.latest_version > dist.parsed_version
  152. ]
  153. def get_uptodate(self, packages, options):
  154. # type: (List[Distribution], Values) -> List[Distribution]
  155. return [
  156. dist for dist in self.iter_packages_latest_infos(packages, options)
  157. if dist.latest_version == dist.parsed_version
  158. ]
  159. def get_not_required(self, packages, options):
  160. # type: (List[Distribution], Values) -> List[Distribution]
  161. dep_keys = set() # type: Set[Distribution]
  162. for dist in packages:
  163. dep_keys.update(requirement.key for requirement in dist.requires())
  164. # Create a set to remove duplicate packages, and cast it to a list
  165. # to keep the return type consistent with get_outdated and
  166. # get_uptodate
  167. return list({pkg for pkg in packages if pkg.key not in dep_keys})
  168. def iter_packages_latest_infos(self, packages, options):
  169. # type: (List[Distribution], Values) -> Iterator[Distribution]
  170. with self._build_session(options) as session:
  171. finder = self._build_package_finder(options, session)
  172. def latest_info(dist):
  173. # type: (Distribution) -> Distribution
  174. typ = 'unknown'
  175. all_candidates = finder.find_all_candidates(dist.key)
  176. if not options.pre:
  177. # Remove prereleases
  178. all_candidates = [candidate for candidate in all_candidates
  179. if not candidate.version.is_prerelease]
  180. evaluator = finder.make_candidate_evaluator(
  181. project_name=dist.project_name,
  182. )
  183. best_candidate = evaluator.sort_best_candidate(all_candidates)
  184. if best_candidate is None:
  185. return None
  186. remote_version = best_candidate.version
  187. if best_candidate.link.is_wheel:
  188. typ = 'wheel'
  189. else:
  190. typ = 'sdist'
  191. # This is dirty but makes the rest of the code much cleaner
  192. dist.latest_version = remote_version
  193. dist.latest_filetype = typ
  194. return dist
  195. for dist in map_multithread(latest_info, packages):
  196. if dist is not None:
  197. yield dist
  198. def output_package_listing(self, packages, options):
  199. # type: (List[Distribution], Values) -> None
  200. packages = sorted(
  201. packages,
  202. key=lambda dist: dist.project_name.lower(),
  203. )
  204. if options.list_format == 'columns' and packages:
  205. data, header = format_for_columns(packages, options)
  206. self.output_package_listing_columns(data, header)
  207. elif options.list_format == 'freeze':
  208. for dist in packages:
  209. if options.verbose >= 1:
  210. write_output("%s==%s (%s)", dist.project_name,
  211. dist.version, dist.location)
  212. else:
  213. write_output("%s==%s", dist.project_name, dist.version)
  214. elif options.list_format == 'json':
  215. write_output(format_for_json(packages, options))
  216. def output_package_listing_columns(self, data, header):
  217. # type: (List[List[str]], List[str]) -> None
  218. # insert the header first: we need to know the size of column names
  219. if len(data) > 0:
  220. data.insert(0, header)
  221. pkg_strings, sizes = tabulate(data)
  222. # Create and add a separator.
  223. if len(data) > 0:
  224. pkg_strings.insert(1, " ".join(map(lambda x: '-' * x, sizes)))
  225. for val in pkg_strings:
  226. write_output(val)
  227. def format_for_columns(pkgs, options):
  228. # type: (List[Distribution], Values) -> Tuple[List[List[str]], List[str]]
  229. """
  230. Convert the package data into something usable
  231. by output_package_listing_columns.
  232. """
  233. running_outdated = options.outdated
  234. # Adjust the header for the `pip list --outdated` case.
  235. if running_outdated:
  236. header = ["Package", "Version", "Latest", "Type"]
  237. else:
  238. header = ["Package", "Version"]
  239. data = []
  240. if options.verbose >= 1 or any(dist_is_editable(x) for x in pkgs):
  241. header.append("Location")
  242. if options.verbose >= 1:
  243. header.append("Installer")
  244. for proj in pkgs:
  245. # if we're working on the 'outdated' list, separate out the
  246. # latest_version and type
  247. row = [proj.project_name, proj.version]
  248. if running_outdated:
  249. row.append(proj.latest_version)
  250. row.append(proj.latest_filetype)
  251. if options.verbose >= 1 or dist_is_editable(proj):
  252. row.append(proj.location)
  253. if options.verbose >= 1:
  254. row.append(get_installer(proj))
  255. data.append(row)
  256. return data, header
  257. def format_for_json(packages, options):
  258. # type: (List[Distribution], Values) -> str
  259. data = []
  260. for dist in packages:
  261. info = {
  262. 'name': dist.project_name,
  263. 'version': six.text_type(dist.version),
  264. }
  265. if options.verbose >= 1:
  266. info['location'] = dist.location
  267. info['installer'] = get_installer(dist)
  268. if options.outdated:
  269. info['latest_version'] = six.text_type(dist.latest_version)
  270. info['latest_filetype'] = dist.latest_filetype
  271. data.append(info)
  272. return json.dumps(data)