parser.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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, ' <%s>', ', ')
  25. def _format_option_strings(self, option, mvarfmt=' <%s>', 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 - evaluated as mvarfmt % metavar
  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 % 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: %s\n' % self.indent_lines(textwrap.dedent(usage), " ")
  53. return msg
  54. def format_description(self, description):
  55. # leave full control over description to us
  56. if description:
  57. if hasattr(self.parser, 'main'):
  58. label = 'Commands'
  59. else:
  60. label = 'Description'
  61. # some doc strings have initial newlines, some don't
  62. description = description.lstrip('\n')
  63. # some doc strings have final newlines and spaces, some don't
  64. description = description.rstrip()
  65. # dedent, then reindent
  66. description = self.indent_lines(textwrap.dedent(description), " ")
  67. description = '%s:\n%s\n' % (label, description)
  68. return description
  69. else:
  70. return ''
  71. def format_epilog(self, epilog):
  72. # leave full control over epilog to us
  73. if epilog:
  74. return epilog
  75. else:
  76. return ''
  77. def indent_lines(self, text, indent):
  78. new_lines = [indent + line for line in text.split('\n')]
  79. return "\n".join(new_lines)
  80. class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
  81. """Custom help formatter for use in ConfigOptionParser.
  82. This is updates the defaults before expanding them, allowing
  83. them to show up correctly in the help listing.
  84. """
  85. def expand_default(self, option):
  86. if self.parser is not None:
  87. self.parser._update_defaults(self.parser.defaults)
  88. return optparse.IndentedHelpFormatter.expand_default(self, option)
  89. class CustomOptionParser(optparse.OptionParser):
  90. def insert_option_group(self, idx, *args, **kwargs):
  91. """Insert an OptionGroup at a given position."""
  92. group = self.add_option_group(*args, **kwargs)
  93. self.option_groups.pop()
  94. self.option_groups.insert(idx, group)
  95. return group
  96. @property
  97. def option_list_all(self):
  98. """Get a list of all options, including those in option groups."""
  99. res = self.option_list[:]
  100. for i in self.option_groups:
  101. res.extend(i.option_list)
  102. return res
  103. class ConfigOptionParser(CustomOptionParser):
  104. """Custom option parser which updates its defaults by checking the
  105. configuration files and environmental variables"""
  106. def __init__(self, *args, **kwargs):
  107. self.name = kwargs.pop('name')
  108. isolated = kwargs.pop("isolated", False)
  109. self.config = Configuration(isolated)
  110. assert self.name
  111. optparse.OptionParser.__init__(self, *args, **kwargs)
  112. def check_default(self, option, key, val):
  113. try:
  114. return option.check_value(key, val)
  115. except optparse.OptionValueError as exc:
  116. print("An error occurred during configuration: %s" % exc)
  117. sys.exit(3)
  118. def _get_ordered_configuration_items(self):
  119. # Configuration gives keys in an unordered manner. Order them.
  120. override_order = ["global", self.name, ":env:"]
  121. # Pool the options into different groups
  122. section_items = {name: [] for name in override_order}
  123. for section_key, val in self.config.items():
  124. # ignore empty values
  125. if not val:
  126. logger.debug(
  127. "Ignoring configuration key '%s' as it's value is empty.",
  128. section_key
  129. )
  130. continue
  131. section, key = section_key.split(".", 1)
  132. if section in override_order:
  133. section_items[section].append((key, val))
  134. # Yield each group in their override order
  135. for section in override_order:
  136. for key, val in section_items[section]:
  137. yield key, val
  138. def _update_defaults(self, defaults):
  139. """Updates the given defaults with values from the config files and
  140. the environ. Does a little special handling for certain types of
  141. options (lists)."""
  142. # Accumulate complex default state.
  143. self.values = optparse.Values(self.defaults)
  144. late_eval = set()
  145. # Then set the options with those values
  146. for key, val in self._get_ordered_configuration_items():
  147. # '--' because configuration supports only long names
  148. option = self.get_option('--' + key)
  149. # Ignore options not present in this parser. E.g. non-globals put
  150. # in [global] by users that want them to apply to all applicable
  151. # commands.
  152. if option is None:
  153. continue
  154. if option.action in ('store_true', 'store_false', 'count'):
  155. try:
  156. val = strtobool(val)
  157. except ValueError:
  158. error_msg = invalid_config_error_message(
  159. option.action, key, val
  160. )
  161. self.error(error_msg)
  162. elif option.action == 'append':
  163. val = val.split()
  164. val = [self.check_default(option, key, v) for v in val]
  165. elif option.action == 'callback':
  166. late_eval.add(option.dest)
  167. opt_str = option.get_opt_string()
  168. val = option.convert_value(opt_str, val)
  169. # From take_action
  170. args = option.callback_args or ()
  171. kwargs = option.callback_kwargs or {}
  172. option.callback(option, opt_str, val, self, *args, **kwargs)
  173. else:
  174. val = self.check_default(option, key, val)
  175. defaults[option.dest] = val
  176. for key in late_eval:
  177. defaults[key] = getattr(self.values, key)
  178. self.values = None
  179. return defaults
  180. def get_default_values(self):
  181. """Overriding to make updating the defaults after instantiation of
  182. the option parser possible, _update_defaults() does the dirty work."""
  183. if not self.process_default_values:
  184. # Old, pre-Optik 1.5 behaviour.
  185. return optparse.Values(self.defaults)
  186. # Load the configuration, or error out in case of an error
  187. try:
  188. self.config.load()
  189. except ConfigurationError as err:
  190. self.exit(UNKNOWN_ERROR, str(err))
  191. defaults = self._update_defaults(self.defaults.copy()) # ours
  192. for option in self._get_all_options():
  193. default = defaults.get(option.dest)
  194. if isinstance(default, string_types):
  195. opt_str = option.get_opt_string()
  196. defaults[option.dest] = option.check_value(opt_str, default)
  197. return optparse.Values(defaults)
  198. def error(self, msg):
  199. self.print_usage(sys.stderr)
  200. self.exit(UNKNOWN_ERROR, "%s\n" % msg)
  201. def invalid_config_error_message(action, key, val):
  202. """Returns a better error message when invalid configuration option
  203. is provided."""
  204. if action in ('store_true', 'store_false'):
  205. return ("{0} is not a valid value for {1} option, "
  206. "please specify a boolean value like yes/no, "
  207. "true/false or 1/0 instead.").format(val, key)
  208. return ("{0} is not a valid value for {1} option, "
  209. "please specify a numerical value like 1/0 "
  210. "instead.").format(val, key)