main_parser.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. """A single place for constructing and exposing the main parser
  2. """
  3. import os
  4. import sys
  5. from typing import List, Tuple
  6. from pip._internal.cli import cmdoptions
  7. from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
  8. from pip._internal.commands import commands_dict, get_similar_commands
  9. from pip._internal.exceptions import CommandError
  10. from pip._internal.utils.misc import get_pip_version, get_prog
  11. __all__ = ["create_main_parser", "parse_command"]
  12. def create_main_parser() -> ConfigOptionParser:
  13. """Creates and returns the main parser for pip's CLI"""
  14. parser = ConfigOptionParser(
  15. usage="\n%prog <command> [options]",
  16. add_help_option=False,
  17. formatter=UpdatingDefaultsHelpFormatter(),
  18. name="global",
  19. prog=get_prog(),
  20. )
  21. parser.disable_interspersed_args()
  22. parser.version = get_pip_version()
  23. # add the general options
  24. gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
  25. parser.add_option_group(gen_opts)
  26. # so the help formatter knows
  27. parser.main = True # type: ignore
  28. # create command listing for description
  29. description = [""] + [
  30. f"{name:27} {command_info.summary}"
  31. for name, command_info in commands_dict.items()
  32. ]
  33. parser.description = "\n".join(description)
  34. return parser
  35. def parse_command(args: List[str]) -> Tuple[str, List[str]]:
  36. parser = create_main_parser()
  37. # Note: parser calls disable_interspersed_args(), so the result of this
  38. # call is to split the initial args into the general options before the
  39. # subcommand and everything else.
  40. # For example:
  41. # args: ['--timeout=5', 'install', '--user', 'INITools']
  42. # general_options: ['--timeout==5']
  43. # args_else: ['install', '--user', 'INITools']
  44. general_options, args_else = parser.parse_args(args)
  45. # --version
  46. if general_options.version:
  47. sys.stdout.write(parser.version)
  48. sys.stdout.write(os.linesep)
  49. sys.exit()
  50. # pip || pip help -> print_help()
  51. if not args_else or (args_else[0] == "help" and len(args_else) == 1):
  52. parser.print_help()
  53. sys.exit()
  54. # the subcommand name
  55. cmd_name = args_else[0]
  56. if cmd_name not in commands_dict:
  57. guess = get_similar_commands(cmd_name)
  58. msg = [f'unknown command "{cmd_name}"']
  59. if guess:
  60. msg.append(f'maybe you meant "{guess}"')
  61. raise CommandError(" - ".join(msg))
  62. # all the args without the subcommand
  63. cmd_args = args[:]
  64. cmd_args.remove(cmd_name)
  65. return cmd_name, cmd_args