requirements.py 4.8 KB

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