requirements.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. import urllib.parse
  5. from typing import Any, List, Optional, Set
  6. from ._parser import parse_requirement
  7. from ._tokenizer import ParserSyntaxError
  8. from .markers import Marker, _normalize_extra_values
  9. from .specifiers import SpecifierSet
  10. class InvalidRequirement(ValueError):
  11. """
  12. An invalid requirement was found, users should refer to PEP 508.
  13. """
  14. class Requirement:
  15. """Parse a requirement.
  16. Parse a given requirement string into its parts, such as name, specifier,
  17. URL, and extras. Raises InvalidRequirement on a badly-formed requirement
  18. string.
  19. """
  20. # TODO: Can we test whether something is contained within a requirement?
  21. # If so how do we do that? Do we need to test against the _name_ of
  22. # the thing as well as the version? What about the markers?
  23. # TODO: Can we normalize the name and extra name?
  24. def __init__(self, requirement_string: str) -> None:
  25. try:
  26. parsed = parse_requirement(requirement_string)
  27. except ParserSyntaxError as e:
  28. raise InvalidRequirement(str(e)) from e
  29. self.name: str = parsed.name
  30. if parsed.url:
  31. parsed_url = urllib.parse.urlparse(parsed.url)
  32. if parsed_url.scheme == "file":
  33. if urllib.parse.urlunparse(parsed_url) != parsed.url:
  34. raise InvalidRequirement("Invalid URL given")
  35. elif not (parsed_url.scheme and parsed_url.netloc) or (
  36. not parsed_url.scheme and not parsed_url.netloc
  37. ):
  38. raise InvalidRequirement(f"Invalid URL: {parsed.url}")
  39. self.url: Optional[str] = parsed.url
  40. else:
  41. self.url = None
  42. self.extras: Set[str] = set(parsed.extras if parsed.extras else [])
  43. self.specifier: SpecifierSet = SpecifierSet(parsed.specifier)
  44. self.marker: Optional[Marker] = None
  45. if parsed.marker is not None:
  46. self.marker = Marker.__new__(Marker)
  47. self.marker._markers = _normalize_extra_values(parsed.marker)
  48. def __str__(self) -> str:
  49. parts: List[str] = [self.name]
  50. if self.extras:
  51. formatted_extras = ",".join(sorted(self.extras))
  52. parts.append(f"[{formatted_extras}]")
  53. if self.specifier:
  54. parts.append(str(self.specifier))
  55. if self.url:
  56. parts.append(f"@ {self.url}")
  57. if self.marker:
  58. parts.append(" ")
  59. if self.marker:
  60. parts.append(f"; {self.marker}")
  61. return "".join(parts)
  62. def __repr__(self) -> str:
  63. return f"<Requirement('{self}')>"
  64. def __hash__(self) -> int:
  65. return hash((self.__class__.__name__, str(self)))
  66. def __eq__(self, other: Any) -> bool:
  67. if not isinstance(other, Requirement):
  68. return NotImplemented
  69. return (
  70. self.name == other.name
  71. and self.extras == other.extras
  72. and self.specifier == other.specifier
  73. and self.url == other.url
  74. and self.marker == other.marker
  75. )