format_control.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from typing import FrozenSet, Optional, Set
  2. from pip._vendor.packaging.utils import canonicalize_name
  3. from pip._internal.exceptions import CommandError
  4. class FormatControl:
  5. """Helper for managing formats from which a package can be installed."""
  6. __slots__ = ["no_binary", "only_binary"]
  7. def __init__(
  8. self,
  9. no_binary: Optional[Set[str]] = None,
  10. only_binary: Optional[Set[str]] = None,
  11. ) -> None:
  12. if no_binary is None:
  13. no_binary = set()
  14. if only_binary is None:
  15. only_binary = set()
  16. self.no_binary = no_binary
  17. self.only_binary = only_binary
  18. def __eq__(self, other: object) -> bool:
  19. if not isinstance(other, self.__class__):
  20. return NotImplemented
  21. if self.__slots__ != other.__slots__:
  22. return False
  23. return all(getattr(self, k) == getattr(other, k) for k in self.__slots__)
  24. def __repr__(self) -> str:
  25. return "{}({}, {})".format(
  26. self.__class__.__name__, self.no_binary, self.only_binary
  27. )
  28. @staticmethod
  29. def handle_mutual_excludes(value: str, target: Set[str], other: Set[str]) -> None:
  30. if value.startswith("-"):
  31. raise CommandError(
  32. "--no-binary / --only-binary option requires 1 argument."
  33. )
  34. new = value.split(",")
  35. while ":all:" in new:
  36. other.clear()
  37. target.clear()
  38. target.add(":all:")
  39. del new[: new.index(":all:") + 1]
  40. # Without a none, we want to discard everything as :all: covers it
  41. if ":none:" not in new:
  42. return
  43. for name in new:
  44. if name == ":none:":
  45. target.clear()
  46. continue
  47. name = canonicalize_name(name)
  48. other.discard(name)
  49. target.add(name)
  50. def get_allowed_formats(self, canonical_name: str) -> FrozenSet[str]:
  51. result = {"binary", "source"}
  52. if canonical_name in self.only_binary:
  53. result.discard("source")
  54. elif canonical_name in self.no_binary:
  55. result.discard("binary")
  56. elif ":all:" in self.only_binary:
  57. result.discard("source")
  58. elif ":all:" in self.no_binary:
  59. result.discard("binary")
  60. return frozenset(result)
  61. def disallow_binaries(self) -> None:
  62. self.handle_mutual_excludes(
  63. ":all:",
  64. self.no_binary,
  65. self.only_binary,
  66. )