format_control.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. """
  7. __slots__ = ["no_binary", "only_binary"]
  8. def __init__(self, no_binary=None, only_binary=None):
  9. # type: (Optional[Set[str]], Optional[Set[str]]) -> None
  10. if no_binary is None:
  11. no_binary = set()
  12. if only_binary is None:
  13. only_binary = set()
  14. self.no_binary = no_binary
  15. self.only_binary = only_binary
  16. def __eq__(self, other):
  17. # type: (object) -> bool
  18. if not isinstance(other, self.__class__):
  19. return NotImplemented
  20. if self.__slots__ != other.__slots__:
  21. return False
  22. return all(
  23. getattr(self, k) == getattr(other, k)
  24. for k in self.__slots__
  25. )
  26. def __repr__(self):
  27. # type: () -> str
  28. return "{}({}, {})".format(
  29. self.__class__.__name__,
  30. self.no_binary,
  31. self.only_binary
  32. )
  33. @staticmethod
  34. def handle_mutual_excludes(value, target, other):
  35. # type: (str, Set[str], Set[str]) -> None
  36. if value.startswith('-'):
  37. raise CommandError(
  38. "--no-binary / --only-binary option requires 1 argument."
  39. )
  40. new = value.split(',')
  41. while ':all:' in new:
  42. other.clear()
  43. target.clear()
  44. target.add(':all:')
  45. del new[:new.index(':all:') + 1]
  46. # Without a none, we want to discard everything as :all: covers it
  47. if ':none:' not in new:
  48. return
  49. for name in new:
  50. if name == ':none:':
  51. target.clear()
  52. continue
  53. name = canonicalize_name(name)
  54. other.discard(name)
  55. target.add(name)
  56. def get_allowed_formats(self, canonical_name):
  57. # type: (str) -> FrozenSet[str]
  58. result = {"binary", "source"}
  59. if canonical_name in self.only_binary:
  60. result.discard('source')
  61. elif canonical_name in self.no_binary:
  62. result.discard('binary')
  63. elif ':all:' in self.only_binary:
  64. result.discard('source')
  65. elif ':all:' in self.no_binary:
  66. result.discard('binary')
  67. return frozenset(result)
  68. def disallow_binaries(self):
  69. # type: () -> None
  70. self.handle_mutual_excludes(
  71. ':all:', self.no_binary, self.only_binary,
  72. )