format_control.py 2.8 KB

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