parser.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. """Base option parser setup"""
  2. # The following comment should be removed at some point in the future.
  3. # mypy: disallow-untyped-defs=False
  4. from __future__ import absolute_import
  5. import logging
  6. import optparse
  7. import sys
  8. import textwrap
  9. from distutils.util import strtobool
  10. from pip._vendor.six import string_types
  11. from pip._internal.cli.status_codes import UNKNOWN_ERROR
  12. from pip._internal.configuration import Configuration, ConfigurationError
  13. from pip._internal.utils.compat import get_terminal_size
  14. logger = logging.getLogger(__name__)
  15. class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
  16. """A prettier/less verbose help formatter for optparse."""
  17. def __init__(self, *args, **kwargs):
  18. # help position must be aligned with __init__.parseopts.description
  19. kwargs['max_help_position'] = 30
  20. kwargs['indent_increment'] = 1
  21. kwargs['width'] = get_terminal_size()[0] - 2
  22. optparse.IndentedHelpFormatter.__init__(self, *args, **kwargs)
  23. def format_option_strings(self, option):
  24. return self._format_option_strings(option)
  25. def _format_option_strings(self, option, mvarfmt=' <{}>', optsep=', '):
  26. """
  27. Return a comma-separated list of option strings and metavars.
  28. :param option: tuple of (short opt, long opt), e.g: ('-f', '--format')
  29. :param mvarfmt: metavar format string
  30. :param optsep: separator
  31. """
  32. opts = []
  33. if option._short_opts:
  34. opts.append(option._short_opts[0])
  35. if option._long_opts:
  36. opts.append(option._long_opts[0])
  37. if len(opts) > 1:
  38. opts.insert(1, optsep)
  39. if option.takes_value():
  40. metavar = option.metavar or option.dest.lower()
  41. opts.append(mvarfmt.format(metavar.lower()))
  42. return ''.join(opts)
  43. def format_heading(self, heading):
  44. if heading == 'Options':
  45. return ''
  46. return heading + ':\n'
  47. def format_usage(self, usage):
  48. """
  49. Ensure there is only one newline between usage and the first heading
  50. if there is no description.
  51. """
  52. msg = '\nUsage: {}\n'.format(
  53. self.indent_lines(textwrap.dedent(usage), " "))
  54. return msg
  55. def format_description(self, description):
  56. # leave full control over description to us
  57. if description:
  58. if hasattr(self.parser, 'main'):
  59. label = 'Commands'
  60. else:
  61. label = 'Description'
  62. # some doc strings have initial newlines, some don't
  63. description = description.lstrip('\n')
  64. # some doc strings have final newlines and spaces, some don't
  65. description = description.rstrip()
  66. # dedent, then reindent
  67. description = self.indent_lines(textwrap.dedent(description), " ")
  68. description = '{}:\n{}\n'.format(label, description)
  69. return description
  70. else:
  71. return ''
  72. def format_epilog(self, epilog):
  73. # leave full control over epilog to us
  74. if epilog:
  75. return epilog
  76. else:
  77. return ''
  78. def indent_lines(self, text, indent):
  79. new_lines = [indent + line for line in text.split('\n')]
  80. return "\n".join(new_lines)
  81. class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
  82. """Custom help formatter for use in ConfigOptionParser.
  83. This is updates the defaults before expanding them, allowing
  84. them to show up correctly in the help listing.
  85. """
  86. def expand_default(self, option):
  87. if self.parser is not None:
  88. self.parser._update_defaults(self.parser.defaults)
  89. return optparse.IndentedHelpFormatter.expand_default(self, option)
  90. class CustomOptionParser(optparse.OptionParser):
  91. def insert_option_group(self, idx, *args, **kwargs):
  92. """Insert an OptionGroup at a given position."""
  93. group = self.add_option_group(*args, **kwargs)
  94. self.option_groups.pop()
  95. self.option_groups.insert(idx, group)
  96. return group
  97. @property
  98. def option_list_all(self):
  99. """Get a list of all options, including those in option groups."""
  100. res = self.option_list[:]
  101. for i in self.option_groups:
  102. res.extend(i.option_list)
  103. return res
  104. class ConfigOptionParser(CustomOptionParser):
  105. """Custom option parser which updates its defaults by checking the
  106. configuration files and environmental variables"""
  107. def __init__(self, *args, **kwargs):
  108. self.name = kwargs.pop('name')
  109. isolated = kwargs.pop("isolated", False)
  110. self.config = Configuration(isolated)
  111. assert self.name
  112. optparse.OptionParser.__init__(self, *args, **kwargs)
  113. def check_default(self, option, key, val):
  114. try:
  115. return option.check_value(key, val)
  116. except optparse.OptionValueError as exc:
  117. print("An error occurred during configuration: {}".format(exc))
  118. sys.exit(3)
  119. def _get_ordered_configuration_items(self):
  120. # Configuration gives keys in an unordered manner. Order them.
  121. override_order = ["global", self.name, ":env:"]
  122. # Pool the options into different groups
  123. section_items = {name: [] for name in override_order}
  124. for section_key, val in self.config.items():
  125. # ignore empty values
  126. if not val:
  127. logger.debug(
  128. "Ignoring configuration key '%s' as it's value is empty.",
  129. section_key
  130. )
  131. continue
  132. section, key = section_key.split(".", 1)
  133. if section in override_order:
  134. section_items[section].append((key, val))
  135. # Yield each group in their override order
  136. for section in override_order:
  137. for key, val in section_items[section]:
  138. yield key, val
  139. def _update_defaults(self, defaults):
  140. """Updates the given defaults with values from the config files and
  141. the environ. Does a little special handling for certain types of
  142. options (lists)."""
  143. # Accumulate complex default state.
  144. self.values = optparse.Values(self.defaults)
  145. late_eval = set()
  146. # Then set the options with those values
  147. for key, val in self._get_ordered_configuration_items():
  148. # '--' because configuration supports only long names
  149. option = self.get_option('--' + key)
  150. # Ignore options not present in this parser. E.g. non-globals put
  151. # in [global] by users that want them to apply to all applicable
  152. # commands.
  153. if option is None:
  154. continue
  155. if option.action in ('store_true', 'store_false', 'count'):
  156. try:
  157. val = strtobool(val)
  158. except ValueError:
  159. error_msg = invalid_config_error_message(
  160. option.action, key, val
  161. )
  162. self.error(error_msg)
  163. elif option.action == 'append':
  164. val = val.split()
  165. val = [self.check_default(option, key, v) for v in val]
  166. elif option.action == 'callback':
  167. late_eval.add(option.dest)
  168. opt_str = option.get_opt_string()
  169. val = option.convert_value(opt_str, val)
  170. # From take_action
  171. args = option.callback_args or ()
  172. kwargs = option.callback_kwargs or {}
  173. option.callback(option, opt_str, val, self, *args, **kwargs)
  174. else:
  175. val = self.check_default(option, key, val)
  176. defaults[option.dest] = val
  177. for key in late_eval:
  178. defaults[key] = getattr(self.values, key)
  179. self.values = None
  180. return defaults
  181. def get_default_values(self):
  182. """Overriding to make updating the defaults after instantiation of
  183. the option parser possible, _update_defaults() does the dirty work."""
  184. if not self.process_default_values:
  185. # Old, pre-Optik 1.5 behaviour.
  186. return optparse.Values(self.defaults)
  187. # Load the configuration, or error out in case of an error
  188. try:
  189. self.config.load()
  190. except ConfigurationError as err:
  191. self.exit(UNKNOWN_ERROR, str(err))
  192. defaults = self._update_defaults(self.defaults.copy()) # ours
  193. for option in self._get_all_options():
  194. default = defaults.get(option.dest)
  195. if isinstance(default, string_types):
  196. opt_str = option.get_opt_string()
  197. defaults[option.dest] = option.check_value(opt_str, default)
  198. return optparse.Values(defaults)
  199. def error(self, msg):
  200. self.print_usage(sys.stderr)
  201. self.exit(UNKNOWN_ERROR, "{}\n".format(msg))
  202. def invalid_config_error_message(action, key, val):
  203. """Returns a better error message when invalid configuration option
  204. is provided."""
  205. if action in ('store_true', 'store_false'):
  206. return ("{0} is not a valid value for {1} option, "
  207. "please specify a boolean value like yes/no, "
  208. "true/false or 1/0 instead.").format(val, key)
  209. return ("{0} is not a valid value for {1} option, "
  210. "please specify a numerical value like 1/0 "
  211. "instead.").format(val, key)