requirements.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. from __future__ import absolute_import, division, print_function
  5. import string
  6. import re
  7. import sys
  8. from pip._vendor.pyparsing import stringStart, stringEnd, originalTextFor, ParseException
  9. from pip._vendor.pyparsing import ZeroOrMore, Word, Optional, Regex, Combine
  10. from pip._vendor.pyparsing import Literal as L # noqa
  11. from ._typing import TYPE_CHECKING
  12. from .markers import MARKER_EXPR, Marker
  13. from .specifiers import LegacySpecifier, Specifier, SpecifierSet
  14. if sys.version_info[0] >= 3:
  15. from urllib import parse as urlparse # pragma: no cover
  16. else: # pragma: no cover
  17. import urlparse
  18. if TYPE_CHECKING: # pragma: no cover
  19. from typing import List, Optional as TOptional, Set
  20. class InvalidRequirement(ValueError):
  21. """
  22. An invalid requirement was found, users should refer to PEP 508.
  23. """
  24. ALPHANUM = Word(string.ascii_letters + string.digits)
  25. LBRACKET = L("[").suppress()
  26. RBRACKET = L("]").suppress()
  27. LPAREN = L("(").suppress()
  28. RPAREN = L(")").suppress()
  29. COMMA = L(",").suppress()
  30. SEMICOLON = L(";").suppress()
  31. AT = L("@").suppress()
  32. PUNCTUATION = Word("-_.")
  33. IDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM)
  34. IDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END))
  35. NAME = IDENTIFIER("name")
  36. EXTRA = IDENTIFIER
  37. URI = Regex(r"[^ ]+")("url")
  38. URL = AT + URI
  39. EXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA)
  40. EXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)("extras")
  41. VERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE)
  42. VERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE)
  43. VERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY
  44. VERSION_MANY = Combine(
  45. VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE), joinString=",", adjacent=False
  46. )("_raw_spec")
  47. _VERSION_SPEC = Optional(((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY))
  48. _VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or "")
  49. VERSION_SPEC = originalTextFor(_VERSION_SPEC)("specifier")
  50. VERSION_SPEC.setParseAction(lambda s, l, t: t[1])
  51. MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker")
  52. MARKER_EXPR.setParseAction(
  53. lambda s, l, t: Marker(s[t._original_start : t._original_end])
  54. )
  55. MARKER_SEPARATOR = SEMICOLON
  56. MARKER = MARKER_SEPARATOR + MARKER_EXPR
  57. VERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER)
  58. URL_AND_MARKER = URL + Optional(MARKER)
  59. NAMED_REQUIREMENT = NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER)
  60. REQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd
  61. # pyparsing isn't thread safe during initialization, so we do it eagerly, see
  62. # issue #104
  63. REQUIREMENT.parseString("x[]")
  64. class Requirement(object):
  65. """Parse a requirement.
  66. Parse a given requirement string into its parts, such as name, specifier,
  67. URL, and extras. Raises InvalidRequirement on a badly-formed requirement
  68. string.
  69. """
  70. # TODO: Can we test whether something is contained within a requirement?
  71. # If so how do we do that? Do we need to test against the _name_ of
  72. # the thing as well as the version? What about the markers?
  73. # TODO: Can we normalize the name and extra name?
  74. def __init__(self, requirement_string):
  75. # type: (str) -> None
  76. try:
  77. req = REQUIREMENT.parseString(requirement_string)
  78. except ParseException as e:
  79. raise InvalidRequirement(
  80. 'Parse error at "{0!r}": {1}'.format(
  81. requirement_string[e.loc : e.loc + 8], e.msg
  82. )
  83. )
  84. self.name = req.name # type: str
  85. if req.url:
  86. parsed_url = urlparse.urlparse(req.url)
  87. if parsed_url.scheme == "file":
  88. if urlparse.urlunparse(parsed_url) != req.url:
  89. raise InvalidRequirement("Invalid URL given")
  90. elif not (parsed_url.scheme and parsed_url.netloc) or (
  91. not parsed_url.scheme and not parsed_url.netloc
  92. ):
  93. raise InvalidRequirement("Invalid URL: {0}".format(req.url))
  94. self.url = req.url # type: TOptional[str]
  95. else:
  96. self.url = None
  97. self.extras = set(req.extras.asList() if req.extras else []) # type: Set[str]
  98. self.specifier = SpecifierSet(req.specifier) # type: SpecifierSet
  99. self.marker = req.marker if req.marker else None # type: TOptional[Marker]
  100. def __str__(self):
  101. # type: () -> str
  102. parts = [self.name] # type: List[str]
  103. if self.extras:
  104. parts.append("[{0}]".format(",".join(sorted(self.extras))))
  105. if self.specifier:
  106. parts.append(str(self.specifier))
  107. if self.url:
  108. parts.append("@ {0}".format(self.url))
  109. if self.marker:
  110. parts.append(" ")
  111. if self.marker:
  112. parts.append("; {0}".format(self.marker))
  113. return "".join(parts)
  114. def __repr__(self):
  115. # type: () -> str
  116. return "<Requirement({0!r})>".format(str(self))