main_parser.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. """A single place for constructing and exposing the main parser"""
  2. from __future__ import annotations
  3. import os
  4. import subprocess
  5. import sys
  6. from pip._internal.build_env import get_runnable_pip
  7. from pip._internal.cli import cmdoptions
  8. from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
  9. from pip._internal.commands import commands_dict, get_similar_commands
  10. from pip._internal.exceptions import CommandError
  11. from pip._internal.utils.misc import get_pip_version, get_prog
  12. __all__ = ["create_main_parser", "parse_command"]
  13. def create_main_parser() -> ConfigOptionParser:
  14. """Creates and returns the main parser for pip's CLI"""
  15. parser = ConfigOptionParser(
  16. usage="\n%prog <command> [options]",
  17. add_help_option=False,
  18. formatter=UpdatingDefaultsHelpFormatter(),
  19. name="global",
  20. prog=get_prog(),
  21. )
  22. parser.disable_interspersed_args()
  23. parser.version = get_pip_version()
  24. # add the general options
  25. gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
  26. parser.add_option_group(gen_opts)
  27. # so the help formatter knows
  28. parser.main = True # type: ignore
  29. # create command listing for description
  30. description = [""] + [
  31. f"{name:27} {command_info.summary}"
  32. for name, command_info in commands_dict.items()
  33. ]
  34. parser.description = "\n".join(description)
  35. return parser
  36. def identify_python_interpreter(python: str) -> str | None:
  37. # If the named file exists, use it.
  38. # If it's a directory, assume it's a virtual environment and
  39. # look for the environment's Python executable.
  40. if os.path.exists(python):
  41. if os.path.isdir(python):
  42. # bin/python for Unix, Scripts/python.exe for Windows
  43. # Try both in case of odd cases like cygwin.
  44. for exe in ("bin/python", "Scripts/python.exe"):
  45. py = os.path.join(python, exe)
  46. if os.path.exists(py):
  47. return py
  48. else:
  49. return python
  50. # Could not find the interpreter specified
  51. return None
  52. def parse_command(args: list[str]) -> tuple[str, list[str]]:
  53. parser = create_main_parser()
  54. # Note: parser calls disable_interspersed_args(), so the result of this
  55. # call is to split the initial args into the general options before the
  56. # subcommand and everything else.
  57. # For example:
  58. # args: ['--timeout=5', 'install', '--user', 'INITools']
  59. # general_options: ['--timeout==5']
  60. # args_else: ['install', '--user', 'INITools']
  61. general_options, args_else = parser.parse_args(args)
  62. # --python
  63. if general_options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ:
  64. # Re-invoke pip using the specified Python interpreter
  65. interpreter = identify_python_interpreter(general_options.python)
  66. if interpreter is None:
  67. raise CommandError(
  68. f"Could not locate Python interpreter {general_options.python}"
  69. )
  70. pip_cmd = [
  71. interpreter,
  72. get_runnable_pip(),
  73. ]
  74. pip_cmd.extend(args)
  75. # Set a flag so the child doesn't re-invoke itself, causing
  76. # an infinite loop.
  77. os.environ["_PIP_RUNNING_IN_SUBPROCESS"] = "1"
  78. returncode = 0
  79. try:
  80. proc = subprocess.run(pip_cmd)
  81. returncode = proc.returncode
  82. except (subprocess.SubprocessError, OSError) as exc:
  83. raise CommandError(f"Failed to run pip under {interpreter}: {exc}")
  84. sys.exit(returncode)
  85. # --version
  86. if general_options.version:
  87. sys.stdout.write(parser.version)
  88. sys.stdout.write(os.linesep)
  89. sys.exit()
  90. # pip || pip help -> print_help()
  91. if not args_else or (args_else[0] == "help" and len(args_else) == 1):
  92. parser.print_help()
  93. sys.exit()
  94. # the subcommand name
  95. cmd_name = args_else[0]
  96. if cmd_name not in commands_dict:
  97. guess = get_similar_commands(cmd_name)
  98. msg = [f'unknown command "{cmd_name}"']
  99. if guess:
  100. msg.append(f'maybe you meant "{guess}"')
  101. raise CommandError(" - ".join(msg))
  102. # all the args without the subcommand
  103. cmd_args = args[:]
  104. cmd_args.remove(cmd_name)
  105. return cmd_name, cmd_args