parser.py 11 KB

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