activators.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from __future__ import annotations
  2. from argparse import ArgumentTypeError
  3. from collections import OrderedDict
  4. from typing import TYPE_CHECKING
  5. from .base import ComponentBuilder
  6. if TYPE_CHECKING:
  7. from collections.abc import Sequence
  8. from python_discovery import PythonInfo
  9. from virtualenv.activation.activator import Activator
  10. from virtualenv.config.cli.parser import VirtualEnvConfigParser, VirtualEnvOptions
  11. class ActivationSelector(ComponentBuilder):
  12. def __init__(self, interpreter: PythonInfo, parser: VirtualEnvConfigParser) -> None:
  13. self.default = None
  14. possible = OrderedDict(
  15. (k, v)
  16. for k, v in self.options("virtualenv.activate").items()
  17. if v.supports(interpreter) # ty: ignore[unresolved-attribute]
  18. )
  19. super().__init__(interpreter, parser, "activators", possible)
  20. self.parser.description = "options for activation scripts"
  21. self.active = None
  22. def add_selector_arg_parse(self, name: str, choices: Sequence[str]) -> None:
  23. self.default = ",".join(choices)
  24. self.parser.add_argument(
  25. f"--{name}",
  26. default=self.default,
  27. metavar="comma_sep_list",
  28. required=False,
  29. help="activators to generate - default is all supported",
  30. type=self._extract_activators,
  31. )
  32. def _extract_activators(self, entered_str: str) -> list[str]:
  33. elements = [e.strip() for e in entered_str.split(",") if e.strip()]
  34. missing = [e for e in elements if e not in self.possible]
  35. if missing:
  36. msg = f"the following activators are not available {','.join(missing)}"
  37. raise ArgumentTypeError(msg)
  38. return elements
  39. def handle_selected_arg_parse(self, options: VirtualEnvOptions) -> None: # ty: ignore[invalid-method-override]
  40. selected_activators = (
  41. self._extract_activators(self.default) if options.activators is self.default else options.activators
  42. )
  43. self.active = {k: v for k, v in self.possible.items() if k in selected_activators}
  44. self.parser.add_argument(
  45. "--prompt",
  46. dest="prompt",
  47. metavar="prompt",
  48. help=(
  49. "provides an alternative prompt prefix for this environment "
  50. "(value of . means name of the current working directory)"
  51. ),
  52. default=None,
  53. )
  54. for activator in self.active.values():
  55. activator.add_parser_arguments(self.parser, self.interpreter) # ty: ignore[unresolved-attribute]
  56. def create(self, options: VirtualEnvOptions) -> list[Activator]:
  57. assert self.active is not None # noqa: S101 # Set by handle_selected_arg_parse
  58. return [activator_class(options) for activator_class in self.active.values()]
  59. __all__ = [
  60. "ActivationSelector",
  61. ]