parser.py 10 KB

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