requirements.py 4.2 KB

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