parser.py 11 KB

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