You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

parser.py 9.2KB

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