baseparser.py 8.3 KB

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