format_control.py 2.6 KB

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