freeze.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import sys
  2. from optparse import Values
  3. from typing import List
  4. from pip._internal.cli import cmdoptions
  5. from pip._internal.cli.base_command import Command
  6. from pip._internal.cli.status_codes import SUCCESS
  7. from pip._internal.operations.freeze import freeze
  8. from pip._internal.utils.compat import stdlib_pkgs
  9. DEV_PKGS = {"pip", "setuptools", "distribute", "wheel"}
  10. class FreezeCommand(Command):
  11. """
  12. Output installed packages in requirements format.
  13. packages are listed in a case-insensitive sorted order.
  14. """
  15. usage = """
  16. %prog [options]"""
  17. log_streams = ("ext://sys.stderr", "ext://sys.stderr")
  18. def add_options(self) -> None:
  19. self.cmd_opts.add_option(
  20. "-r",
  21. "--requirement",
  22. dest="requirements",
  23. action="append",
  24. default=[],
  25. metavar="file",
  26. help=(
  27. "Use the order in the given requirements file and its "
  28. "comments when generating output. This option can be "
  29. "used multiple times."
  30. ),
  31. )
  32. self.cmd_opts.add_option(
  33. "-l",
  34. "--local",
  35. dest="local",
  36. action="store_true",
  37. default=False,
  38. help=(
  39. "If in a virtualenv that has global access, do not output "
  40. "globally-installed packages."
  41. ),
  42. )
  43. self.cmd_opts.add_option(
  44. "--user",
  45. dest="user",
  46. action="store_true",
  47. default=False,
  48. help="Only output packages installed in user-site.",
  49. )
  50. self.cmd_opts.add_option(cmdoptions.list_path())
  51. self.cmd_opts.add_option(
  52. "--all",
  53. dest="freeze_all",
  54. action="store_true",
  55. help=(
  56. "Do not skip these packages in the output:"
  57. " {}".format(", ".join(DEV_PKGS))
  58. ),
  59. )
  60. self.cmd_opts.add_option(
  61. "--exclude-editable",
  62. dest="exclude_editable",
  63. action="store_true",
  64. help="Exclude editable package from output.",
  65. )
  66. self.cmd_opts.add_option(cmdoptions.list_exclude())
  67. self.parser.insert_option_group(0, self.cmd_opts)
  68. def run(self, options: Values, args: List[str]) -> int:
  69. skip = set(stdlib_pkgs)
  70. if not options.freeze_all:
  71. skip.update(DEV_PKGS)
  72. if options.excludes:
  73. skip.update(options.excludes)
  74. cmdoptions.check_list_path_option(options)
  75. for line in freeze(
  76. requirement=options.requirements,
  77. local_only=options.local,
  78. user_only=options.user,
  79. paths=options.path,
  80. isolated=options.isolated_mode,
  81. skip=skip,
  82. exclude_editable=options.exclude_editable,
  83. ):
  84. sys.stdout.write(line + "\n")
  85. return SUCCESS