list.py 11 KB

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