parser.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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, Generator, 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(
  141. self,
  142. ) -> Generator[Tuple[str, Any], None, None]:
  143. # Configuration gives keys in an unordered manner. Order them.
  144. override_order = ["global", self.name, ":env:"]
  145. # Pool the options into different groups
  146. section_items: Dict[str, List[Tuple[str, Any]]] = {
  147. name: [] for name in override_order
  148. }
  149. for section_key, val in self.config.items():
  150. # ignore empty values
  151. if not val:
  152. logger.debug(
  153. "Ignoring configuration key '%s' as it's value is empty.",
  154. section_key,
  155. )
  156. continue
  157. section, key = section_key.split(".", 1)
  158. if section in override_order:
  159. section_items[section].append((key, val))
  160. # Yield each group in their override order
  161. for section in override_order:
  162. for key, val in section_items[section]:
  163. yield key, val
  164. def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]:
  165. """Updates the given defaults with values from the config files and
  166. the environ. Does a little special handling for certain types of
  167. options (lists)."""
  168. # Accumulate complex default state.
  169. self.values = optparse.Values(self.defaults)
  170. late_eval = set()
  171. # Then set the options with those values
  172. for key, val in self._get_ordered_configuration_items():
  173. # '--' because configuration supports only long names
  174. option = self.get_option("--" + key)
  175. # Ignore options not present in this parser. E.g. non-globals put
  176. # in [global] by users that want them to apply to all applicable
  177. # commands.
  178. if option is None:
  179. continue
  180. assert option.dest is not None
  181. if option.action in ("store_true", "store_false"):
  182. try:
  183. val = strtobool(val)
  184. except ValueError:
  185. self.error(
  186. "{} is not a valid value for {} option, " # noqa
  187. "please specify a boolean value like yes/no, "
  188. "true/false or 1/0 instead.".format(val, key)
  189. )
  190. elif option.action == "count":
  191. with suppress(ValueError):
  192. val = strtobool(val)
  193. with suppress(ValueError):
  194. val = int(val)
  195. if not isinstance(val, int) or val < 0:
  196. self.error(
  197. "{} is not a valid value for {} option, " # noqa
  198. "please instead specify either a non-negative integer "
  199. "or a boolean value like yes/no or false/true "
  200. "which is equivalent to 1/0.".format(val, key)
  201. )
  202. elif option.action == "append":
  203. val = val.split()
  204. val = [self.check_default(option, key, v) for v in val]
  205. elif option.action == "callback":
  206. assert option.callback is not None
  207. late_eval.add(option.dest)
  208. opt_str = option.get_opt_string()
  209. val = option.convert_value(opt_str, val)
  210. # From take_action
  211. args = option.callback_args or ()
  212. kwargs = option.callback_kwargs or {}
  213. option.callback(option, opt_str, val, self, *args, **kwargs)
  214. else:
  215. val = self.check_default(option, key, val)
  216. defaults[option.dest] = val
  217. for key in late_eval:
  218. defaults[key] = getattr(self.values, key)
  219. self.values = None
  220. return defaults
  221. def get_default_values(self) -> optparse.Values:
  222. """Overriding to make updating the defaults after instantiation of
  223. the option parser possible, _update_defaults() does the dirty work."""
  224. if not self.process_default_values:
  225. # Old, pre-Optik 1.5 behaviour.
  226. return optparse.Values(self.defaults)
  227. # Load the configuration, or error out in case of an error
  228. try:
  229. self.config.load()
  230. except ConfigurationError as err:
  231. self.exit(UNKNOWN_ERROR, str(err))
  232. defaults = self._update_defaults(self.defaults.copy()) # ours
  233. for option in self._get_all_options():
  234. assert option.dest is not None
  235. default = defaults.get(option.dest)
  236. if isinstance(default, str):
  237. opt_str = option.get_opt_string()
  238. defaults[option.dest] = option.check_value(opt_str, default)
  239. return optparse.Values(defaults)
  240. def error(self, msg: str) -> None:
  241. self.print_usage(sys.stderr)
  242. self.exit(UNKNOWN_ERROR, f"{msg}\n")