parser.py 11 KB

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