format_control.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from __future__ import annotations
  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: set[str] | None = None,
  10. only_binary: set[str] | None = 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 f"{self.__class__.__name__}({self.no_binary}, {self.only_binary})"
  26. @staticmethod
  27. def handle_mutual_excludes(value: str, target: set[str], other: set[str]) -> None:
  28. if value.startswith("-"):
  29. raise CommandError(
  30. "--no-binary / --only-binary option requires 1 argument."
  31. )
  32. new = value.split(",")
  33. while ":all:" in new:
  34. other.clear()
  35. target.clear()
  36. target.add(":all:")
  37. del new[: new.index(":all:") + 1]
  38. # Without a none, we want to discard everything as :all: covers it
  39. if ":none:" not in new:
  40. return
  41. for name in new:
  42. if name == ":none:":
  43. target.clear()
  44. continue
  45. name = canonicalize_name(name)
  46. other.discard(name)
  47. target.add(name)
  48. def get_allowed_formats(self, canonical_name: str) -> frozenset[str]:
  49. result = {"binary", "source"}
  50. if canonical_name in self.only_binary:
  51. result.discard("source")
  52. elif canonical_name in self.no_binary:
  53. result.discard("binary")
  54. elif ":all:" in self.only_binary:
  55. result.discard("source")
  56. elif ":all:" in self.no_binary:
  57. result.discard("binary")
  58. return frozenset(result)
  59. def disallow_binaries(self) -> None:
  60. self.handle_mutual_excludes(
  61. ":all:",
  62. self.no_binary,
  63. self.only_binary,
  64. )