main_parser.py 2.8 KB

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